简体   繁体   中英

Null pointer exception in Fragment when loading data from server

I am new to android. I am developing an application in which i have two tabs. first i want to load data from server and save them in shared preferences and dislay in list view. if there is data in shared prefernces, the data will be displayed from shared preferences first and again load data from server and replace the same. both tabs contains different data from same url. the data is shown properly in list view but the problem is when the data is loading from server the app crashes with null pointer exception at shared prefernces when i go back to main activity when the data is still lodaing from the server.

Below is my code

public class Tab1 extends Fragment {
ListView ll;
Pojo pojo;
ListView dosList;
ProgressDialog nDialog;
String strServerResponse = null;
ArrayList<Pojo> dos;
DosAdapter dosAdapter;
SharedPreferences MyPrefs1;
ProgressBar nPregress;
ArrayList<String> tii1;
LayoutInflater inf;


@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tab_1, container, false);

       return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


    dosList = (ListView) view.findViewById(R.id.doList);
    nPregress = (ProgressBar) getActivity().findViewById(R.id.toolbar_progress_bar);
    nPregress.setVisibility(View.GONE);
    dos = new ArrayList<Pojo>();

    SharedPreferences prefs = getActivity().getSharedPreferences("MyPref1", 0);
    Set<String> set = prefs.getStringSet("does", null);
    if (set != null) {

        for (String p : set) {
            pojo = new Pojo();
            pojo.setType(p);
            dos.add(pojo);

        }
        dosAdapter = new DosAdapter(getContext(), dos);
        dosList.setAdapter(dosAdapter);


    } else {
        new NetCheck(getContext()).execute();
    }

    new NetCheck(getContext()).execute();

}

private class NetCheck extends AsyncTask<Void, Void, Void> {
    private Context context;
    public NetCheck(Context context)
    {
        this.context=context;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        nPregress.setVisibility(View.VISIBLE);

    }

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

        dos.clear();
        nPregress.setVisibility(View.GONE);
        SharedPreferences prefs = getActivity().getSharedPreferences("MyPref1", 0);
        Set<String> set = prefs.getStringSet("does", null);
        for (String p : set) {
            pojo = new Pojo();
            pojo.setType(p);
            dos.add(pojo);

        }
        dosAdapter = new DosAdapter(getContext(), dos);
        dosList.setAdapter(dosAdapter);


        return;
    }

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

        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpRequest = new HttpPost(
                    "http://tipseducation.com/system/eadmin/getdoes_n_doesnot/");
            //"http://techie-web.com/android/testm/gcm_server_php/dosndonts.php");
            //"http://192.168.56.1:8080/Project/categories.php");
            httpRequest.setHeader("Content-Type", "application/json");

            JSONObject json = new JSONObject();

            StringEntity se = new StringEntity(json.toString());

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            httpRequest.setEntity(se);
            HttpResponse httpRes = httpClient.execute(httpRequest);

            java.io.InputStream inputStream = httpRes.getEntity()
                    .getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            strServerResponse = sb.toString();

            Log.e("Server Response", "" + strServerResponse.toString());

            if (strServerResponse != null) {
                try {

                    JSONArray arr = new JSONArray(strServerResponse);
                    JSONObject jsonObj = arr.getJSONObject(0);
                    tii1 = new ArrayList<String>();
                    for (int i = 0; i < arr.length(); i++) {
                        pojo = new Pojo();
                        JSONObject jobj2 = arr.getJSONObject(i);
                        String does = jobj2.optString("does");
                        tii1.add(does);

                    }

                    List<String> listTemp1 = tii1;
                    Set<String> temp1 = new HashSet<String>(listTemp1);
                    ////////////////////////Crashhhhhhhhhhhh///////////////////////////////
                    SharedPreferences.Editor editor5 = context.getSharedPreferences("MyPref1", 0).edit();
                    temp1.addAll(listTemp1);
                    editor5.putStringSet("does", temp1);
                    editor5.commit();


                } catch (JSONException e) {
                    e.printStackTrace();
                }

Is there something wrong in the code. Same is the code for another tab. Can anyone please help me

Logcat

   java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException
        at com.example.priyanka.newdentalapp.Tab2$NetCheck.doInBackground(Tab2.java:192)
        at com.example.priyanka.newdentalapp.Tab2$NetCheck.doInBackground(Tab2.java:83)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)

In asynctask class you have to create a constructor like below:

private Context context;
public NetCheck(Context context)
{
      this.context=context;
}

After this you have to change your all getActivity() line with context. That's it. try this and it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM