简体   繁体   English

从服务器加载数据时,片段中的空指针异常

[英]Null pointer exception in Fragment when loading data from server

I am new to android. 我是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 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: 在asynctask类中,您必须创建如下的构造函数:

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

After this you have to change your all getActivity() line with context. 之后,您必须使用上下文更改所有的getActivity()行。 That's it. 而已。 try this and it will work. 试试这个,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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