Fortune
Fortune

Reputation: 3

Android ViewPager Frame Listview Crash

I am trying to make a TabLayout (ViewPager) App with Three Fragments. In one of those tabs, I want display a json parsed custom list view. The Custom list view and Tab Layout works fine individually (codes from tutorial). When I combine these two, App crashes immediately, I couldn't figure out what is going wrong. Hope you guys can help

Thank you Sam_0829....you saved me

The Problems were 1. Instead of MainActivity, Getmessages must be in Fragment

  1. View Was empty while calling onViewCreated, So i declared a private view variable

    private View v;

    //then onCreate

    View v = inflater.inflate(R.layout.message_tab, container, false);

    and passed it into

onViewCreated public void onViewCreated(View v, @Nullable Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState); contactList = new ArrayList<>();

    lv = (ListView) v.findViewById(R.id.list);

    new Getmessages().execute();
}

and life became awesome

Thank yo sam you taught me to trouble shoot via logs...something i never trusted before

Message Fragment (Solved Code) ->

    package com.example.user.newton;

 public class MessageTab extends Fragment {
    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;
    private View v;
    // URL to get messages JSON

    private static String url = "http://myjson.com/17oyz5";

    ArrayList<HashMap<String, String>> contactList;
    private MainActivity.SectionsPagerAdapter mSectionsPagerAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

       View v =  inflater.inflate(R.layout.message_tab, container, false);
        return v;
    }
    private class Getmessages extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray messages = jsonObj.getJSONArray("messages");

                    // looping through All messages
                    for (int i = 0; i < messages.length(); i++) {
                        JSONObject c = messages.getJSONObject(i);

                        String message= c.getString("message");
                        String sender= c.getString("sender");
                        String mtime= c.getString("time");

                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("message", message);
                        contact.put("sender", sender);
                        contact.put("mtime", mtime);

                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), contactList,
                    R.layout.custom_layout, new String[]{"message", "sender",
                    "mtime"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            lv.setAdapter(adapter);
        }

    }

    @Override
    public void onViewCreated(View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        contactList = new ArrayList<>();

        lv = (ListView) v.findViewById(R.id.list);

        new Getmessages().execute();
    }
}

MessageFragment Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Upvotes: 0

Views: 86

Answers (3)

Haileapp
Haileapp

Reputation: 775

if (lv!= null) {

lv.setAdapter(adapter)

}

Upvotes: 0

Sandip Fichadiya
Sandip Fichadiya

Reputation: 3480

Please change

pDialog = new ProgressDialog(getApplicationContext());

to

pDialog = new ProgressDialog(MainActivity.this);

& try.

Upvotes: 0

Brian Yencho
Brian Yencho

Reputation: 2958

It looks like you are trying to update the ListView contents in the wrong place : you're referencing the ListView as lv in your MainActivity, but it needs to be updated in your MessageFragment. You should move your Getmessages to (for example) onCreateView of your MessageFragment instead.

Upvotes: 0

Related Questions