1

I am trying to make a listView which will load more items when the last listView item is visible. I have the code to get data from JSON which is working good.

This is my MyFragment.java

    public class MyFragment extends Fragment {

        JSONObject jsonobject;
        JSONObject newjsonobject;
        JSONArray jsonarray;
        JSONArray newjsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ArrayList<HashMap<String, String>> arraylist;
        ArrayList<HashMap<String, String>> newarraylist;
        public static String NAME = "name";
        private int preLast;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.listview_main, container, false);
            new DownloadJSON().execute();
            return rootView;

        }

        private class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... params) {

                arraylist = new ArrayList<HashMap<String, String>>();           
                jsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.103/contacts.json");

                try {

                    jsonarray = jsonobject.getJSONArray("contacts");                
                    for (int i = 0; i < jsonarray.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);                
                        map.put("name", jsonobject.getString("name"));          
                        arraylist.add(map);

                    }

                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }               
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {

                listview = (ListView) getActivity().findViewById(R.id.listview);
                adapter = new ListViewAdapter(getActivity(), arraylist);

                listview.setOnScrollListener(new AbsListView.OnScrollListener(){

                    @Override
                    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                        final int lastItem = firstVisibleItem + visibleItemCount;

                        newarraylist = new ArrayList<HashMap<String, String>>();

                        if(lastItem == totalItemCount) {
                            if(preLast!=lastItem){

                                preLast = lastItem;                     

                                newjsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.103/contacts2.json");

                                try {

                                    newjsonarray = newjsonobject.getJSONArray("contacts");

                                    for (int i = 0; i < newjsonarray.length(); i++) {
                                        HashMap<String, String> newmap = new HashMap<String, String>();

                                        newjsonobject = newjsonarray.getJSONObject(i);

                                        newmap.put("name", newjsonobject.getString("name"));

                                        newarraylist.add(newmap);

                                    }
                                } catch (JSONException e) {
                                    Log.e("Error", e.getMessage());
                                    e.printStackTrace();
                                }

                                arraylist.addAll(newarraylist);

                                adapter.notifyDataSetChanged();

                            }

                        }

                    }

                    @Override
                    public void onScrollStateChanged(AbsListView view, int scrollState){}

                });

                listview.setAdapter(adapter);

            }

        }   

    }

It works good if I try like this

    newmap.put("name", "Name");

    newarraylist.add(newmap);                           

    arraylist.addAll(newarraylist);

    adapter.notifyDataSetChanged();

But when I try to get data from JSON, when I scroll to the last item application stops working. What I am doing wrong?

Contacts2.json

{
    "contacts": [
        {
            "name": "Name"
        },
        {

            "name": "Name 2"
        }
    ]
}
learner
  • 3,017
  • 2
  • 20
  • 31
Enve
  • 6,298
  • 10
  • 38
  • 82
  • What do you mean by "application stops working"? If there's an exception thrown, add it to your question, and point out on which line this exception is thrown. – nhaarman Apr 28 '14 at 22:29
  • When I install application in my phone and if I scroll down to the last item it shows an alert "Unfortunately, Application has stopped.". – Enve Apr 28 '14 at 22:32
  • Check the `logcat` panel. It contains a stacktrace which exactly tells you where and why your application crashed. Take a look at [What is a stacktrace?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) for more information. – nhaarman Apr 28 '14 at 22:35
  • It is showing this `at com.myapp.application.MyFragment$DownloadJSON$1.onScroll(MyFragment.java:185)` which is this line `newjsonarray = newjsonobject.getJSONArray("contacts");` – Enve Apr 28 '14 at 23:14
  • What is the part before `at`? That tells you which Exception was thrown. If it's a `NullPointerException`, than that is because the call to `JSONFunctions.getJsonFromUrl(...)` returned `null`. – nhaarman Apr 28 '14 at 23:27
  • Here is the full `log 04-28 23:09:50.349: E/AndroidRuntime(666):at com.myapp.application.MyFragment$DownloadJSON$1.onScroll(MyFragment.java:185)` – Enve Apr 28 '14 at 23:36
  • I'm sorry, that was not what I meant. There should be more lines above this line with extra information. – nhaarman Apr 28 '14 at 23:38
  • One line above is `java.lang.NullPointerException` – Enve Apr 28 '14 at 23:40
  • There you go. The line `jsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.103/contacts.json");` returns `null`. Try to find out why that is. – nhaarman Apr 28 '14 at 23:53
  • Is there any reason why it returns null? I updated the JSON in my question. Also the same code is working on `onCreateView`. – Enve Apr 29 '14 at 00:02
  • If you're using https://code.google.com/p/cabbiemagnet/source/browse/trunk/CabbieMagnetAndroid/src/com/cabbiemagnet/android/JSONfunctions.java?r=27, then somewhere above your stack trace, there should be a line stating "Error in http connection", "Error converting result", or "Error parsing data ". Maybe that helps. – nhaarman Apr 29 '14 at 00:05
  • Yes there are all three error `Error in http connection android.os.NetworkOnMainThreadException`, `Error converting result java.lang.NullPointerException`, `Error parsing data org.json.JSONException: End of input at character 0 of`. But why the same code is working a few lines above? – Enve Apr 29 '14 at 00:12
  • 1
    Ah yes. The first time, you're executing your code in `doInBackground`, which is on a separate thread. The second time, you're executing the code on the main thread, which is not allowed. See http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception . – nhaarman Apr 29 '14 at 00:14
  • Thank you very much. It is working now. – Enve Apr 29 '14 at 00:24

0 Answers0