【问题标题】:android return null after fetching from db Unable to start activity ComponentInfo: java.lang.NullPointerException: storage == nullandroid从db获取后返回null无法启动活动ComponentInfo:java.lang.NullPointerException:storage == null
【发布时间】:2017-05-10 02:20:06
【问题描述】:

我正在尝试将项目动态添加到列表视图。但是,我遇到了运行时异常。请帮忙。全局变量“值”有问题吗?我尝试通过打印日志进行调试,并且能够看到存储在变量中的值。当它返回结果时会出现问题(我使用它是因为我从数据库中获取信息)

它可以很好地从数据库中获取,但是当它返回 try 块中的结果时 int 在函数结束时跳转到另一个 return 语句然后它崩溃了

代码

public class choose_buffet_items extends AppCompatActivity {
    String []categouries;
    ArrayAdapter adapter;
    private static int SPLASH_TIME_OUT=2000;
    AlertDialog alertDialog;
    private boolean loggedIn = false;
    String type;
    String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_buffet_items);
        new JSONParse().execute();
        adapter = new ArrayAdapter<String>(this,
                R.layout.buffet_list_view, categouries);

        ListView listView = (ListView) findViewById(R.id.listView_buffetitem);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String s =(String)adapter.getItem(i);
                if(s.equals("Drinks"))
                {
                    Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_drinks.class);
                    startActivity(numbersIntent);
                }
                else if(s.equals("Cakes"))
                {
                    Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_cake.class);
                    startActivity(numbersIntent);
                }
                else if(s.equals("Appetizers"))
                {
                    Intent numbersIntent = new Intent(choose_buffet_items.this,buffet_appetizers.class);
                    startActivity(numbersIntent);
                }
                else {Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_lunch.class);
                    startActivity(numbersIntent);}

            }
        });


        listView.setAdapter(adapter);
    }
    private class JSONParse extends AsyncTask<String, String, String> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            alertDialog=new AlertDialog.Builder(choose_buffet_items.this).create();
            alertDialog.setTitle("Upadting Data");
            pDialog = new ProgressDialog(choose_buffet_items.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();


        }


        @Override
        protected String doInBackground(String... args) {



                String login_URL = "http://2f179dfb.ngrok.io/getcat.php";
                try {

                    //Fetching the boolean value form sharedpreferences


                    URL url = new URL(login_URL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                    result = "";
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    Log.e("RESULT", result);
                    JSONObject jsonObject = new JSONObject(result);

                    JSONArray result1 = jsonObject.getJSONArray("result");
                    categouries=new String[result1.length()];
                    for (int i = 0; i < result1.length(); i++) {
                        JSONObject c = result1.getJSONObject(i);
                        String category = c.getString("buffCategory");
                        categouries[i]=category;
                    }

                    return result;


                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return result;
            }




        @Override
        protected void onPostExecute(String r) {
            adapter.notifyDataSetChanged();
            pDialog.dismiss();



        }
    }
}
日志猫

12-25 02:45:27.532 7109-7109/com.rematchka.weddinghall E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.rematchka.weddinghall, PID: 7109
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rematchka.weddinghall/com.rematchka.weddinghall.choose_buffet_items}: java.lang.NullPointerException: storage == null
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                             at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                          Caused by: java.lang.NullPointerException: storage == null
                                                                             at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
                                                                             at java.util.Arrays.asList(Arrays.java:155)
                                                                             at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
                                                                             at com.rematchka.weddinghall.choose_buffet_items.onCreate(choose_buffet_items.java:49)
                                                                             at android.app.Activity.performCreate(Activity.java:6237)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                             at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             at android.os.Looper.loop(Looper.java:148) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
12-25 02:45:27.962 7109-7473/com.rematchka.weddinghall E/RESULT: {"result":[{"buffCategory":"Drinks"},{"buffCategory":"Cakes"},{"buffCategory":"Appetizers"},{"buffCategory":"Lunch"}]}

【问题讨论】:

  • 添加 logcat ,以便人们可以看到崩溃的位置
  • 返回结果时崩溃
  • 在 doInBackground 函数中
  • 你想在后台做什么返回,因为你的结果变量是保存Json字符串,如果直接传递给onPostExecute(),那你为什么在doInBackground中解析json
  • 我应该发送字符串说配对成功,但我还没有编辑它,因为它想在字符串的 onPostExecute() 中显示某些消息

标签: java android arrays listview arraylist


【解决方案1】:

你可以使用List&lt;String&gt; 代替String[],你知道吗?

无论如何,您假设 AsyncTask 立即完成。它不是。

当您将数组放入适配器时,您的数组为空。

改为调用 AsyncTask,但在数据准备好之前不要使用数据

public class choose_buffet_items extends AppCompatActivity {
    String []categouries;
    ArrayAdapter adapter;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_buffet_items);
        new JSONParse().execute(); // Let this work in the background...

        // adapter = new ArrayAdapter<String>(this,
        //        R.layout.buffet_list_view, categouries);

onPostExecute 中列表不为空时设置适配器

    @Override
    protected void onPostExecute(String r) {
        adapter = new ArrayAdapter<String>(choose_buffet_items.this,
            R.layout.buffet_list_view, categouries);
        listView.setAdapter(adapter);

        pDialog.dismiss();
    }

注意:如果你让AsyncTask 使用&lt;Void, Void, String[]&gt;,(Void 因为你没有要监控的参数或进度),那么你可以return 类别字符串数组。现在,您返回原始 JSON 字符串,但从未在 onPostExecute 中使用它

【讨论】:

    【解决方案2】:

    当传递给 ArrayAdapter(Context, int, T[]) 的数组参数为 null 时,将引发此特定异常(“storage == null”)。

    在oncreate方法的这一行中:

       adapter = new ArrayAdapter<String>(this,
                R.layout.buffet_list_view, categouries);
    

    Categouries 为空,您需要对其进行初始化,然后才执行该行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2016-01-06
      • 2018-06-02
      • 1970-01-01
      • 2017-05-22
      • 2018-02-26
      相关资源
      最近更新 更多