-1

I am a newbie in android. I am getting a null pointer exception while trying to access the list view in a method.

Following is the code for the fragment:-

public class ExamSyllabus extends Fragment {

public static final boolean D = false;
private TextView text;
public InputStream is;
String examId[];
String examName[];
String schoolDetaiID[];
String sectionID[];
int selectedStudent;
private ProgressDialog pDialog;
ListView lv;

public ExamSyllabus() {
    // TODO Auto-generated constructor stub

}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Loading...");
    pDialog.setCancelable(false);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = LayoutInflater.from(getActivity()).inflate(R.layout.layout, null);
    lv = (ListView) getActivity().findViewById(R.id.f1_lv);
    text = (TextView) v.findViewById(R.id.text);
    if (getArguments() != null) {
        //
        try {
            String value = getArguments().getString("key");
            schoolDetaiID = getArguments().getStringArray("school_detail_id");

            sectionID = getArguments().getStringArray("section_id");
            text.setText("Current Tab is: " + value);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    SharedPreferences sharedpreferences = getActivity()
            .getSharedPreferences(MainActivity.STUDENT_SELECTED_PREFERENCES, getActivity().MODE_PRIVATE);
    selectedStudent = sharedpreferences.getInt(MainActivity.STUDENT_SELECTED, 0);

    String params[] = new String[] { schoolDetaiID[selectedStudent], sectionID[selectedStudent] };
    if (!CheckConnection.haveNetworkConnection(getActivity())) {
        UiHandler.showLongToast(getActivity(), getString(R.string.no_internet_connection));

    } else {
        new ExamsList().execute(params);

    }

    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}


//
public class ExamsList extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        UiHandler.ShowProgressDialog(getActivity(), getString(R.string.loading));
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        if (result.equalsIgnoreCase("success")) {

            ArrayAdapter<String> listAdatpter = new ArrayAdapter<String>(getActivity(),
                    R.layout.rowa_for_all_listview, examName);

            lv.setAdapter(listAdatpter);
            UiHandler.StopProgressDialog(getActivity());
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // TODO Auto-generated method stub
                    if (!CheckConnection.haveNetworkConnection(getActivity())) {
                        UiHandler.showShortToast(getActivity(), getString(R.string.no_internet_connection));
                        return;
                    }
                    Intent i = new Intent(getActivity(), ExamSyllabusDetails.class);
                    i.putExtra("school_detail_id", schoolDetaiID[selectedStudent]);
                    i.putExtra("section_id", sectionID[selectedStudent]);
                    i.putExtra("exam_id", examId[position]);
                    startActivity(i);

                    getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                }
            });

        } else {
            Toast.makeText(getActivity(), result + "", Toast.LENGTH_LONG).show();
            UiHandler.StopProgressDialog(getActivity());
        }

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        // parameters for login
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();

        parameters.add(new BasicNameValuePair("school_detail_id", params[0]));
        parameters.add(new BasicNameValuePair("section_id", params[1]));


        DefaultHttpClient httpClient = new DefaultHttpClient();


        HttpPost httpPost = new HttpPost(ServerUrl.URL_EXAM_LIST);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(parameters));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");

                if (D)
                    Log.e("inside while", line);

            }

            is.close();

            // reading json responses and checking status of response
            String msgg = sb.toString();

            JSONObject JObject = new JSONObject(msgg);
            msgg = JObject.getString(Login.LOGIN_RESPONSE_MESSAGE);
            int status = JObject.getInt(Login.LOGIN_RESPONSE_STATUS);
            if (status == Login.LOGIN_RESPONSE_STATUS_SUCCESS) {

                msgg = JObject.getString(Login.LOGIN_RESPONSE_MESSAGE);
                JSONArray data = JObject.getJSONArray("data");
                examId = new String[data.length()];
                examName = new String[data.length()];

                for (int i = 0; i < data.length(); i++) {
                    JSONObject objj = data.getJSONObject(i);
                    examId[i] = objj.getString("exam_id");
                    examName[i] = objj.getString("exam_name");

                }


                return msgg;
            } else {
                // msgg=JObject.getString(LOGIN_RESPONSE_MESSAGE);
                return msgg;
            }

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

}

And following is the error log:-

    12-31 17:15:30.323: E/AndroidRuntime(17197): FATAL EXCEPTION: main
12-31 17:15:30.323: E/AndroidRuntime(17197): Process: com.enso.ezcomm, PID: 17197
12-31 17:15:30.323: E/AndroidRuntime(17197): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
12-31 17:15:30.323: E/AndroidRuntime(17197):    at com.enso.tabhost1.ExamSyllabus$ExamsList.onPostExecute(ExamSyllabus.java:161)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at com.enso.tabhost1.ExamSyllabus$ExamsList.onPostExecute(ExamSyllabus.java:1)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.os.AsyncTask.finish(AsyncTask.java:651)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.os.AsyncTask.-wrap1(AsyncTask.java)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.os.Handler.dispatchMessage(Handler.java:102)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.os.Looper.loop(Looper.java:148)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at android.app.ActivityThread.main(ActivityThread.java:5417)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at java.lang.reflect.Method.invoke(Native Method)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
12-31 17:15:30.323: E/AndroidRuntime(17197):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

There is a null pointer exception on listview because of getActivity() i.e its not getting the context of the MainActivity. I am not getting this issue anyways. Please help me to fix the problem.

Thanks!!!

Abhinav singh
  • 1,448
  • 1
  • 14
  • 31
Swapnil Lanjewar
  • 646
  • 10
  • 26

1 Answers1

2

Probably is because you are trying to findViewById of your ListView with the wrong view.

Try this:

View v = LayoutInflater.from(getActivity()).inflate(R.layout.layout, null);
    lv = (ListView) v.findViewById(R.id.f1_lv);

I suppose that the ListView is inside of the R.layout.layout file you are inflating.

Hope it helps!!!

Kostas Drak
  • 3,222
  • 6
  • 28
  • 60