Activity 中的 NullPointerException

NullPointerException in the Activity

我在使用 的 activity 中得到 NullPointerException adapter.notifyDataSetChanged();

基本上,在 activity 中,我正在解析数据,并且我正在使用需要在 ListItems 中设置数据的适配器。

MainActivity的代码-

public class SearchResultActivityOne extends AppCompatActivity {

    private static final String url = "http://sikkimexpress.itstunner.com/api/newssearch/a";

    private boolean enableBackNavigation;
    String TAG = "";
    private ProgressDialog pDialog;
    private CustomListSearchAdapter adapter;
    public static final String KEY_HEADURL = "news_url";
    public static final String KEY_DETAILS = "news_details";
    public static final String KEY_TITLE = "news_title";
    String imageURL = "", title = "", description = "";
    private List<Movie> movieList = new ArrayList<Movie>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        adapter.notifyDataSetChanged();

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        if (enableBackNavigation) {
//            toolbar.setNavigationIcon(R.drawable.ic_back);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }

//        pDialog = new ProgressDialog(SearchResultActivityOne.this);
//        pDialog.setMessage("Loading...Please Wait...");
//        pDialog.setCancelable(false);
//        pDialog.show();

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                hidePDialog();
                try {
                    JSONArray jsonArray = response.getJSONArray("HomeNews");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject homenews = jsonArray.getJSONObject(i);
                        Movie movie = new Movie();
                        movie.setNewsId(homenews.getString("NewsId"));
                        movie.setDateTime(homenews.getString("DateTime"));
                        movie.setNewsType(homenews.getString("NewsType"));
                        movie.setTitle(homenews.getString("Title"));
                        movie.setDescription(homenews.getString("Description"));
                        movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));

                        movieList.add(movie);
                }
            } catch (JSONException exception){
                exception.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                hidePDialog();
            }
        });
        AppController.getInstance().addToRequestQueue(request);
    }

    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about_us:
                Intent intent = new Intent(SearchResultActivityOne.this, AboutUs.class);
                startActivity(intent);
                return true;

            case R.id.action_terms_of_use:
                Intent intent_two = new Intent(SearchResultActivityOne.this, TermsUse.class);
                startActivity(intent_two);
                return true;

            case R.id.action_privacy_policy:
                Intent intent_three = new Intent(SearchResultActivityOne.this, PrivacyPolicy.class);
                startActivity(intent_three);
                return true;

            case R.id.action_contact_us:
                Intent intent_four = new Intent(SearchResultActivityOne.this, ContactUs.class);
                startActivity(intent_four);

            case R.id.action_search:

            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

CustomListViewAdapter

public class CustomListSearchAdapter extends BaseAdapter{

    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();


    public CustomListSearchAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

    @Override
    public int getCount() {
        return movieItems.size();
    }

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView desciption = (TextView) convertView.findViewById(R.id.desciption);

        Movie m = movieItems.get(position);
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
        String text = Html.fromHtml(m.getTitle()).toString();
        title.setText(text);
        String text_two = Html.fromHtml(m.getDescription()).toString();
        desciption.setText(text_two);

        return convertView;
    }
}

您的 适配器 对象尚未初始化,因此 notifyDatasetChanged() 将引发 NullPointerException。 你需要一些类似

的东西
adapter = new CustomListSearchAdapter(SearchResultActivityOne.this, movieList);
//Set the adapter to your ListView

onCreate() 方法中调用 adapter.notifyDatasetChanged() 之前。

但我怀疑当您的 movieList 实际上有项目时,您会想在 onResponse() 中调用 notifyDatasetChanged()。另外,没有 ListView 的适配器有什么意义?

我认为您缺少一些代码。首先初始化您的 ListView 和适配器。像这样

ListView listView = (ListView) findById(R.id.list);
adapter = new CustomListSearchAdapter(SearchResultActivityOne.this, movieList);
listView.setAdapter(adapter);

您必须初始化您的适配器:

adapter = new CustomListSearchAdapter();

然后在列表视图中设置

listview.setAdapter(adapter);

更新 1

在 onCreate 方法中:

ListView myListView = (ListView) findViewById(R.id.myListView);
CustomListSearchAdapter adapter = new CustomListSearchAdapter(... arguments ...);
myListView.setAdapter(adapter);

然后使用此列表视图设置您的适配器