如何解决' void android.widget.ListView.setAdapter(android.widget.ListAdapter)'在android中的空对象引用?

时间:2017-08-19 05:35:27

标签: java android listview nullpointerexception

我正在实施" BaseActivity"包含所有其他活动的工具栏。此基本活动需要在其他活动中扩展以添加工具栏。现在问题是我正在进行一项名为" ElectronicsMainActivity"有listview在里面。此活动需要扩展" BaseActivity"喜欢

  

公共类ElectronicsMainActivity扩展了BaseActivity {

但是我的应用程序在启动此活动时会在运行时崩溃。

错误是:

  

java.lang.NullPointerException:尝试调用虚方法' void android.widget.ListView.setAdapter(android.widget.ListAdapter)'在空对象引用上

我的" ElectronicsMainActivity"代码是:

    public class  ElectronicsMainActivity extends BaseActivity{

    private ListView lvComments;

    private ModelWomen comment;
    private AdapterCommentList adpComment;

    private SparseArray<View> mapViewHolder;

    private ArrayList<ModelWomen> alComment;

    int i;

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

        lvComments = (ListView) findViewById(R.id.lvListview);

        alComment = new ArrayList<>();

        mapViewHolder = new SparseArray<View>();

        comment = new ModelWomen();

        comment = (ModelWomen) getIntent().getSerializableExtra("id");


        initUi();

        new AsyncGetWomencategories().execute();
    }

    public void initUi() {

        adpComment = new AdapterCommentList(getApplicationContext(), alComment);

        lvComments.setAdapter(adpComment);

        final String usr =getIntent().getStringExtra("userid");

        lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if(i==0) {
                    Intent intent = new Intent(getApplicationContext(), CellPhones.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }

                if(i==1) {
                    Intent intent = new Intent(getApplicationContext(), Cameres.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }

                if(i==2) {
                    Intent intent = new Intent(getApplicationContext(), MP3_Players.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }
                if(i==3) {
                    Intent intent = new Intent(getApplicationContext(), Car_Electronics.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }
                if(i==4) {
                    Intent intent = new Intent(getApplicationContext(), Tv_Video.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }
                if(i==5) {
                    Intent intent = new Intent(getApplicationContext(), Computers.class);
                    intent.putExtra("userid",usr);
                    startActivity(intent);
                }
            }
        });
    }

    private class AdapterCommentList extends BaseAdapter {
        private Context context;

        private List<ModelWomen> alComments;

        private LayoutInflater inflater;

        public AdapterCommentList(Context context, List<ModelWomen> alComments) {
            this.context = context;

            this.alComments = alComments;

            inflater = LayoutInflater.from(this.context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            AdapterCommentList.ViewHolder holder = null;

            if (mapViewHolder.get(position) == null) {
                convertView = inflater.inflate(R.layout.women_sub_categories, null);

                holder = initHolder(convertView, position);

                attachEvents(holder, position);

                convertView.setTag(holder);

                mapViewHolder.put(position, convertView);
            } else {
                holder = (AdapterCommentList.ViewHolder) mapViewHolder.get(position).getTag();
            }

            updateHolder(holder, position);

            return mapViewHolder.get(position);
        }

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

        @Override
        public ModelWomen getItem(int position) {
            return alComments.get(position);
        }

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

        private class ViewHolder {

            private TextView tvName;

        }

        private AdapterCommentList.ViewHolder initHolder(View convertView, int pos) {
            AdapterCommentList.ViewHolder holder = new AdapterCommentList.ViewHolder();


            holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
            return holder;
        }


        private void updateHolder(AdapterCommentList.ViewHolder holder, int pos) {

            holder.tvName.setText(alComment.get(pos).getCategory());


        }

        private void attachEvents(AdapterCommentList.ViewHolder holder, final int position) {

        }


    }

    public class AsyncGetWomencategories extends AsyncTask<Void, Void, AsyncTaskResult<Object>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            findViewById(R.id.rlProgress).setVisibility(View.VISIBLE);
        }

        @Override
        protected AsyncTaskResult<Object> doInBackground(Void... params) {
            BufferedReader in = null;

            try {
                HttpParams httpParameters = new BasicHttpParams();
                HttpConnectionParams
                        .setConnectionTimeout(httpParameters, 20000);
                HttpConnectionParams.setSoTimeout(httpParameters, 20000);
                HttpClient client = new DefaultHttpClient(httpParameters);

                String url = AppConstants.URL_GET_ELECTRONICS_CATEGORY_MAINLEVEL2;

                HttpGet request = new HttpGet(url);

                request.setHeader("Accept", "application/json");
                request.setHeader("Content-type", "application/json");
                request.setHeader("Authorization", "Basic " + "my_key");
                HttpResponse response = client.execute(request);

                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");

                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                String result = sb.toString();

                if (AppConstants.DEBUG)
                    Log.v(AppConstants.DEBUG_TAG, "REPLY COMMENTRESPONSE : " + result);

                return new AsyncTaskResult<Object>(result);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return new AsyncTaskResult<Object>("OK");
        }

        @Override
        protected void onPostExecute(AsyncTaskResult<Object> result) {
            super.onPostExecute(result);

            findViewById(R.id.rlProgress).setVisibility(View.GONE);

            if (result.getError() != null) {

            } else {
                String response = result.getResult().toString();

                try {
                    alComment.clear();

                    alComment.addAll(ParseJson.ParseWomen(response));

                    adpComment.notifyDataSetChanged();

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

    }
    }

这是我的&#34; BaseActivity&#34;代码:

   public abstract class BaseActivity extends AppCompatActivity {

    Toolbar toolbar;
    String toknlink;
    LibFile libFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initUi();

    }

    protected void initData() {
        libFile = LibFile.getInstance(getApplicationContext());
    }
    protected void initUi() {
        if (libFile.getToken() != null) {
            toknlink = libFile.getToken();
        }else {
        }
    }


    protected boolean useToolbar() {
        return true;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        configureToolbar(view);
        super.setContentView(view);
    }

    private void configureToolbar(View view) {
        toolbar = (Toolbar) view.findViewById(R.id.toolbartest);

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

    }


    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem login = menu.findItem(R.id.action_login);
        MenuItem logout = menu.findItem(R.id.action_logout);
        if (toknlink.length() == 0) {
            login.setVisible(true);
            logout.setVisible(false);
        } else {
            login.setVisible(false);
            logout.setVisible(true);
        }
        return true;
    }

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

        MenuItem item1 = menu.findItem(R.id.action_searchicon);


        MenuItem item = menu.findItem(R.id.action_cart);
        int ids = item.getItemId();

        ImageView imageView = (ImageView)findViewById(R.id.cartimage);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

       if (id == R.id.action_cart) {
            Intent i = new Intent(getApplicationContext(), Cart.class);

            startActivity(i);

            overridePendingTransition(R.anim.lefttoright, R.anim.right_to_left);

        }

        if (id == R.id.action_wishlist) {

            Intent i = new Intent(getApplicationContext(), MyWishList.class);
            i.putExtra("userid", toknlink);
            startActivity(i);
        }
        if (id == R.id.action_logout) {

            new AlertDialog.Builder(this)
                    .setMessage("Are you sure you want to logout?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            finishAffinity();
                            Intent i = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(i);
                            logout();
                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
            return true;
        }
        if (id == R.id.action_login) {

            finish();
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
        }
        if (id == R.id.action_home) {

            finish();
            Intent i = new Intent(getApplicationContext(), Main2Activity.class);
            startActivity(i);
        }
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);

    }
     public void logout() {
        libFile.clearCache();

        Toast.makeText(getApplicationContext(), " Logout  Successfully ", Toast.LENGTH_SHORT).show();
    }
}

请建议我哪里出错了。我已经使用另一个活动实现了这个baseactivity,但该活动没有listview。 &#34; ElectronicsMainActivity&#34;包含listview。请建议。

4 个答案:

答案 0 :(得分:1)

  

java.lang.NullPointerException:尝试调用虚方法'void   android.widget.ListView.setAdapter(android.widget.ListAdapter)'上的一个   null对象引用

首先声明ListView。

    lvComments = (ListView) findViewById(R.id.lvListview);       
    alComment = new ArrayList<>();
    mapViewHolder = new SparseArray<View>();
    comment = new ModelWomen();
    comment = (ModelWomen) getIntent().getSerializableExtra("id");

修改

@Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        configureToolbar(view);
        super.setContentView(view);
    }

为什么要两次调用 setContentView()

答案 1 :(得分:0)

上述代码的问题是,在您尝试从BaseActivity中查找列表视图后,您需要设置活动的contentView 因此,在调用super.onCreate()方法

之前设置contentView
 setContentView(R.layout.activity_electronics_main);
 super.onCreate(savedInstanceState);

这将解决问题

修改 从BaseActivity中删除setContentView覆盖方法,并在findViewById(R.id.toolbar_id)

中按onCreate()找到工具栏

答案 2 :(得分:0)

这是因为您正在调用BaseActivity oncreate并且它正在调用initUI(),但您的UI尚未初始化,因此会导致空指针。您可以在super.onCreate()初始化之后按照以下方式移动ListView,如下所示

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            setContentView(R.layout.activity_electronics_main);
            lvComments = (ListView) findViewById(R.id.lvListview);
            alComment = new ArrayList<>();
            mapViewHolder = new SparseArray<View>();
            comment = new ModelWomen();
            comment = (ModelWomen) getIntent().getSerializableExtra("id");
            super.onCreate(savedInstanceState);
            // initUi(); <-- Redundant method invocation as it is already invoked from base
            new AsyncGetWomencategories().execute();
        }

答案 3 :(得分:0)

试试这个:用这个替换你的BaseActivity

 public class BaseActivity extends AppCompatActivity {

    @Nullable
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Nullable
    @BindView(R.id.ivLogo)
    ImageView ivLogo;

    private MenuItem inboxMenuItem;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        bindViews();
    }

    protected void bindViews() {
        ButterKnife.bind(this);
        setupToolbar();
    }

    public void setContentViewWithoutInject(int layoutResId) {
        super.setContentView(layoutResId);
    }

    protected void setupToolbar() {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            toolbar.setNavigationIcon(R.drawable.ic_menu_white);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        inboxMenuItem = menu.findItem(R.id.action_inbox);
        inboxMenuItem.setActionView(R.layout.menu_item_view);
        return true;
    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    public MenuItem getInboxMenuItem() {
        return inboxMenuItem;
    }

    public ImageView getIvLogo() {
        return ivLogo;
    }}

使用此依赖项来调用BindView

 compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

创建新的Toolbar.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:elevation="@dimen/default_elevation"
    app:layout_scrollFlags="scroll|enterAlways"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <TextView
        android:id="@+id/ivLogo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:scaleType="center"
      />
</android.support.v7.widget.Toolbar>

在您的活动中使用此工具栏

 <include
    android:id="@+id/toolbar"
    layout="@layout/toolbar.xml" />