-1

I am creating an app with dynamic ListView, which should fetch data from the server and bind them after getting the responses, on a Button click. I've done upto receiving response. But dont know how to bind the data to ListView. I've also created an Adapter that is used to bind. But doesnt know the way to bind the data via adapter. Can anyone help me? I've given my codes below for reference..

Main Activity.java (from onCreate):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_take_payment);

    list = (ListView) findViewById(R.id.take_payment_list);
    adapter = new CustomListAdapter(this, notifications);
    list.setAdapter(adapter);

    refresh_btn = (Button) findViewById(R.id.refresh_btn);

    refresh_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HttpHandler httpHandler1 = new HttpHandler();
            String res = null;


            try {

                Log.d("edwLog", TAG + " get_payment_notifications " + HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/");
                res = httpHandler1.makeServiceCall(HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/", HttpHandler.GET);
                Log.d("edwLog", TAG + " response > " + res);
                if (res != null) {
                    JSONObject jsonObject = new JSONObject(res);
                    String responseType = jsonObject.getString("type");
                    if (responseType.equals("success")) {
                        if (jsonObject.has("response")) {

                            JSONArray jsonArray = jsonObject.getJSONArray("response");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                notificationsresponse.add(jsonArray.getJSONObject(i));
                            }


                        }
                    }
                }



            } catch (Exception e) {
                e.printStackTrace();
                Log.d("edwLog", TAG + " IOException > " + e.toString());
            }

            adapter.notifyDataSetChanged();
        }
    });

Adapter Class:

public class CustomListAdapter extends BaseAdapter {

private final Activity activity;
private LayoutInflater inflater;
private List<Users> notifications;

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Users> notifications) {
    this.activity = activity;
    this.notifications = notifications;
}

@Override
public int getCount() {
    return notifications.size();
}

@Override
public Object getItem(int location) {
    return notifications.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null)
        convertView = inflater.inflate(R.layout.custom_rows, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();

    NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);


    TextView name = (TextView) convertView.findViewById(R.id.txt_customer_name4);
    TextView time = (TextView) convertView.findViewById(R.id.txt_notification_time4);

    // getting notifications data for the row
    Users m = notifications.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailurl(), imageLoader);

    // name
    name.setText(m.getName());

    // notification time
    /*time.setText(String.valueOf(m.getTime()));*/
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(m.getTime()), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
            time.setText(timeAgo);


    return convertView;
}



}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vss
  • 1,093
  • 1
  • 20
  • 33

5 Answers5

2

First create a adapter , which you have already done :

list = (ListView) findViewById(R.id.take_payment_list);
adapter = new CustomListAdapter(this, notifications);
list.setAdapter(adapter);

But In the 2nd line list item is missing, rest is all fine:

adapter = new CustomListAdapter(this,<<listItem>>, notifications);

now after getting the response

add your items to the notifications array and then change adapter to have the new notifications array :

notifications.add("data");
adapter = new CustomListAdapter(this,<<listItem>>, notifications);
  • What does that <> actually mean Rajesh? – vss Jul 16 '15 at 10:51
  • 1
    It should be R.layout.custom_rows in your case . – Rajesh Khetan Jul 16 '15 at 11:34
  • It doesnt help Rajesh. Shows error on including ` adapter = new CustomListAdapter(this,R.layout.custom_rows, notifications);` – vss Jul 16 '15 at 12:14
  • 1
    ok change the constructor to have 2nd parameter as a integer . public CustomListAdapter(Activity activity, int textViewResourseId ,List notifications) { } – Rajesh Khetan Jul 16 '15 at 12:35
  • I now got it Rajesh...! I did like this: adapter = new CustomListAdapter(MainActivity.this, R.layout.custom_rows, (ArrayList) notificationsresponse); list.setAdapter(adapter); adapter.notifyDataSetChanged(); And its done...! Cheers...! – vss Jul 17 '15 at 11:29
0

Do simple steps:

Override method in your adapter:

public void notifyDataSetChanged(List<Users> notifications){
   this.notifications = notifications;
   super.notifyDataSetChanged();
}

Now, instead of calling:

adapter.notifyDataSetChanged();

call it as:

adapter.notifyDataSetChanged(notificationsresponse);

Also, your approach of fetching data from server is not correct. As you are trying to fetch data on main UI thread which will slow down user experience. You should call server/database call only in Async thread and update that response on UI thread.

Kinnar Vasa
  • 397
  • 1
  • 9
0

First of all never call the web services on the main thread call them in AsyncTask. The AsyncTask will be the inner class of your Activity/Fragment class.

private class WebServiceCaller extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
        //Call your web service here
        }
        return response; //the json response you get
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        //here bind the data using your adapter to the listview
        //Parse the JSONObject you get as the response and add them to the list of Your User
        //now call the adapter
        adapter= new CustomListAdapter(MainActiviy.this,List);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}
Vishwajit Palankar
  • 3,033
  • 3
  • 28
  • 48
0

If you want the fetched data to be used again then first store it in Sqlite Database, if not then use an ArrayAdapter to bind data to listView.

Refer this link.

Community
  • 1
  • 1
rusted brain
  • 1,052
  • 10
  • 23
0

Found it out successfully with the help of you guys. Its just these 3 lines of code to be added after getting response. For my app, it goes like this:

adapter = new CustomListAdapter(TakePayment.this, R.layout.custom_rows, (ArrayList<JSONObject>) notificationsresponse);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
vss
  • 1,093
  • 1
  • 20
  • 33