-1

I am implementing "BaseActivity" that contain toolbar for all other activities. this base activity need to be extends in other activity to add toolbar. Now problem is I am having one activity named "ElectronicsMainActivity" having listview in it. This activity need to extends "BaseActivity" like

public class ElectronicsMainActivity extends BaseActivity{

But my app is getting crashed at runtime when starting this activity.

error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

My "ElectronicsMainActivity" code is:

    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();
                }
            }
        }

    }
    }

This is my "BaseActivity" code:

   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();
    }
}

Please suggest me where am i getting wrong. I have already implemented this baseactivity with another activity but that activity doesn't have listview. "ElectronicsMainActivity" contains listview. please suggest.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

4 Answers4

1

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Declare ListView First .

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

EDIT

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

Why you calling setContentView() twice ??

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

The problem with above code is that you're setting the contentView of the activity after you're trying to find the list view from the BaseActivity So set the contentView before you call the super.onCreate() method

 setContentView(R.layout.activity_electronics_main);
 super.onCreate(savedInstanceState);

This will solve the problem

EDIT Remove the setContentView override method from BaseActivity and find the toolbar by findViewById(R.id.toolbar_id) in the onCreate()

Samuel Robert
  • 10,106
  • 7
  • 39
  • 60
0

It's because you are calling BaseActivity oncreate and it is invoking initUI() but you're UI is not yet intialized hence causing null pointer. you can do below way move super.onCreate() after init of ListView as in below

        @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();
        }
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
0

Try this one: Replace your BaseActivity with this one

 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;
    }}

Use this dependencies to envoke BindView

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

Create new 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>

Use this toolbar in your activity

 <include
    android:id="@+id/toolbar"
    layout="@layout/toolbar.xml" />
Harshal Deshmukh
  • 1,787
  • 3
  • 14
  • 25