如何在Android中的同一活动中使用两个Volley请求时修复空指针异常?

时间:2016-05-09 08:24:03

标签: android android-volley

我添加了一个"特色"寻呼机视图作为我的列表视图的标题。寻呼机视图从列表视图中的单独URL接收其数据,因此我正在进行两个单独的Volley请求。我已经在一个单独的项目中测试了寻呼机视图,它完美无缺。列表视图无需额外的截击请求即可完美运行。这是我的主要活动。

    public class MainActivity extends AppCompatActivity {
    private ProgressDialog dialog=null ;
    private CustomAdapter adapter;
    private ListView list;
    ArrayList<RowData> rowdata;
    private SearchView searchView;
    private MenuItem myActionMenuItem;
    private ViewPager pageView;
    private ArrayList<FeatureModel> fdata;
    private FeatureAdapter featAdapt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        LayoutInflater inflater = getLayoutInflater();
        ViewGroup header = (ViewGroup) inflater.inflate(R.layout.feature_view, list,
                false);
        pageView = (ViewPager)findViewById(R.id.featuredView);

        list=(ListView) findViewById(R.id.listView1);
        list.addHeaderView(header);
        list.setTextFilterEnabled(true);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Get item at position
                RowData item = (RowData)parent.getItemAtPosition(position);

                //Pass the image title and url to DetailsActivity
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("image", item.getImageURL());
                intent.putExtra("size", item.getProdSize());
                intent.putExtra("date", item.getProdDate());
                intent.putExtra("region", item.getRegionURL());
                intent.putExtra("desc", item.getDetailURL());

                //Start details activity
                startActivity(intent);
            }
        });
        rowdata=new ArrayList<RowData>();

        dialog= new ProgressDialog(this, R.style.AppTheme);

        dialog.setMessage("Loading...");
        dialog.show();

        JsonArrayRequest request = new JsonArrayRequest(url+url_file,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString()); try {
                            for(int i=0;i<response.length();i++){
                                String title=response.getJSONObject(i).getString("prod_name");
                                String size=response.getJSONObject(i).getString("prod_size");
                                String img_url;
                                String date = response.getJSONObject(i).getString("prod_date");
                                String detail_url = response.getJSONObject(i).getString("prod_desc");
                                String region_url = response.getJSONObject(i).getString("prod_region");

                                img_url = response.getJSONObject(i).getString("prod_image");

                                rowdata.add(new RowData(title, size, img_url,detail_url,region_url,date));
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        adapter=new CustomAdapter(MainActivity.this, rowdata);
                        list.setAdapter(adapter);
                        dialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
                dialog.dismiss();
            }
        });

        VolleyController.getInstance().addToRequestQueue(request, tag_json_arry);

        loadFeatures();


    }

    public void loadFeatures(){
        JsonArrayRequest stringRequest = new JsonArrayRequest(FEAT_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString()); try {
                            for(int i=0;i<response.length();i++){
                                String sid=response.getJSONObject(i).getString("fid");
                                String name=response.getJSONObject(i).getString("feat_name");
                                String img = response.getJSONObject(i).getString("feat_pic");

                                fdata.add(new FeatureModel(sid, name, img));
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        featAdapt=new FeatureAdapter(MainActivity.this, fdata);
                        pageView.setAdapter(featAdapt);
                        //dialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
                //dialog.dismiss();
            }
        });

        VolleyController.getInstance().addToRequestQueue(stringRequest, TAG);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        myActionMenuItem = menu.findItem(R.id.action_search);
        searchView = (SearchView) myActionMenuItem.getActionView();
        searchView.clearFocus();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }


            @Override
            public boolean onQueryTextChange(String newText) {
                Filter filter = adapter.getFilter();

                if (TextUtils.isEmpty(newText)) {
                    filter.filter("");
                } else {
                    filter.filter(newText);
                }
                return true;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_search) {
            return true;
        }
        if(id == R.id.action_info){
            return true;
        }
        if(id == R.id.action_share){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

}

这是logcat:

  

流程:com.curtrostudios.prodarchive,PID:7231       显示java.lang.NullPointerException           在com.curtrostudios.prodarchive.MainActivity $ 4.onResponse(MainActivity.java:149)           at com.curtrostudios.prodarchive.MainActivity $ 4.onResponse(MainActivity.java:140)           在com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)           在com.android.volley.ExecutorDelivery $ ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)           在android.os.Handler.handleCallback(Handler.java:733)           在android.os.Handler.dispatchMessage(Handler.java:95)           在android.os.Looper.loop(Looper.java:136)           在android.app.ActivityThread.main(ActivityThread.java:5072)           at java.lang.reflect.Method.invokeNative(Native Method)           在java.lang.reflect.Method.invoke(Method.java:515)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)           在dalvik.system.NativeStart.main(本地方法)

2 个答案:

答案 0 :(得分:3)

经过不断的研究和反复试验,我发现了问题所在。问题不在于有两个Volley请求,而是Volley请求将JSON响应返回到空视图。

最初,pagerview看起来像这样:

pageView = (ViewPager)findViewById(R.id.featuredView);

对于任何想要将viewpager包含为listview标题的人来说,这就是它应该如何完成的。

标题视图的声明如下:

View header = (RelativeLayout)getLayoutInflater().inflate(R.layout.feature_view, null);

因此,如果您想使用该布局中的任何视图,则必须声明

pageView = (ViewPager)header.findViewById(R.id.featuredView);

header.findViewById()确保您从声明的标头中找到视图。

然后为了确保标题正确显示,我必须添加以下内容:

    final DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    final int width = displayMetrics.widthPixels;

    AbsListView.LayoutParams headerViewParams = new AbsListView.LayoutParams(width, 400);
    header.setLayoutParams(headerViewParams);

这就是您的活动的onCreate()方法中的完整代码:

        //Use this to find the width of the device
    final DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    //This is where you declare the header layout
    View header = (RelativeLayout)getLayoutInflater().inflate(R.layout.feature_view, null);
    //This is where you find the view within the header layout
    //that you're going to need or use
    pageView = (ViewPager)header.findViewById(R.id.featuredView);

    //This is where you set the layout params if the header layout
    //isn't showing properly
    AbsListView.LayoutParams headerViewParams = new AbsListView.LayoutParams(width, 400);

    //Set the layout params for the header
    header.setLayoutParams(headerViewParams);

    list=(ListView)findViewById(R.id.listView1);

    //add the header to the listview.
    //in this case, ListView = list;
    list.addHeaderView(header);

答案 1 :(得分:1)

你得到NullPointerException,这不是同一Activity中两个凌空请求的原因。

检查您的JsonArray对象作为回复,可能为空白或 null []