Why this null pointer error is comming? [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I was making a list of favorite activity in the android which uses arraylist
as a storing place,but when i was triggering the event by the button press,null pointer error is coming. Why is it so...???
Here is the code of my Kinematics activity where the button is being pressed.
public class Kinematics extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle phy_law_toggel;
private Toolbar toolbar;
private WebView webView;
private ScrollView scrollview;
private FloatingActionButton fab;
private ImageButton fav;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Favouritepage favr = new Favouritepage();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kinematics);
Toolbar toolbar = (Toolbar) findViewById(R.id.phy_lawtoolbar);
setSupportActionBar(toolbar);
setTitle(R.string.Kinematics);
drawerLayout = (DrawerLayout) findViewById(R.id.phy_draw);
navigationView = (NavigationView) findViewById(R.id.nav_view_phy);
phy_law_toggel = new ActionBarDrawerToggle(this,drawerLayout,R.string.open, R.string.Close);
drawerLayout.addDrawerListener(phy_law_toggel);
toolbar = (Toolbar) findViewById(R.id.phy_lawtoolbar);
setSupportActionBar(toolbar);
phy_law_toggel.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setItemIconTintList(null);
webView = (WebView) findViewById(R.id.phy_law_web);
fav = (ImageButton) findViewById(R.id.fav);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
final String kine = this.getClass().getSimpleName();
webView.getSettings().setDisplayZoomControls(true);
webView.loadUrl("file:///android_asset/mathscribe/Kinematics.html");
fab = (FloatingActionButton) findViewById(R.id.fab);
scrollview = (ScrollView) findViewById(R.id.scroll);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.scrollTo(0, 0);
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
favr.mfavlist.add(kine);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (phy_law_toggel.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
Here, i am making an object of my FavoritePage class and trying to store the element in the arrayList of FavoritePage.
Here is my FavoritePage class
public class Favouritepage extends AppCompatActivity {
public ArrayList<String> mfavlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favouritepage);
mfavlist = new ArrayList<String>();
}}
And here is the XML of kinematics,
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/phy_draw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.alpit.formula2.Kinematics">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/phy_lawtoolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar.PopupOverlay">
</android.support.v7.widget.Toolbar>
<WebView
android:id="#+id/phy_law_web"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/phy_lawtoolbar"></WebView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_alignBottom="#+id/phy_law_web"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_gravity="bottom|end"
android:layout_marginBottom="43dp"
android:layout_marginEnd="30dp"
android:src="#drawable/fabss"
app:backgroundTint="#F57F17">
</android.support.design.widget.FloatingActionButton>
<ImageButton
android:id="#+id/fav"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_above="#+id/phy_law_web"
android:layout_alignParentEnd="true"
android:background="#color/colorPrimary"
android:src="#drawable/fav" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view_phy"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFAB40"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationTheme" />
crashlog
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alpit.formula2, PID: 22744
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.alpit.formula2.Kinematics$2.onClick(Kinematics.java:64)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20102)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)

Add this line after setContentView in your Kinematic.
ArrayList<String> mfavlist = new ArrayList<String>();
edit this line of your code
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mfavlist.add(kine);
}
});

Here is my FavoritePage class
public class Favouritepage extends AppCompatActivity {
... Meanwhile in your other class...
final Favouritepage favr = new Favouritepage();
Never ever new an Activity class (because onCreate is never called, therefore the list is null)
Basically, I do not think FavouritePage should extend Activity at all.
Learn more about POJO classes
public class Favouritepage {
public ArrayList<String> mfavlist = new ArrayList<String>();
public Favouritepage() {
// Empty constructor
}
}
Or, if it needs does need to be an Activity class, you will have to find a different way to "share" that list between activities.

Related

MenuItem throwing NullPointerException when using Firebase Remote Config

I want to hide and unhide a MenuItem ((R.id.bored)) using Firebase remote config. But it is showing NullPointerException. Please help! and is there any alternative way I could remote hide and unhide that menu item (R.id.bored)?
Here is HomeActivity.java
public class HomeActivity
extends Activity
implements NavigationView.OnNavigationItemSelectedListener, PowerfulActionModeSupport {
public static final int REQUEST_PERMISSION_ALL = 1;
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private PowerfulActionMode mActionMode;
private HomeFragment mHomeFragment;
private MenuItem mTrustZoneToggle;
private IntentFilter mFilter = new IntentFilter();
private BroadcastReceiver mReceiver = null;
private long mExitPressTime;
private int mChosenMenuItemId;
private RewardedVideoAd mRewardedVideoAd;
private InterstitialAd mInterstitialAd;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(3600)
.build();
mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHomeFragment = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.activitiy_home_fragment);
mActionMode = findViewById(R.id.content_powerful_action_mode);
mNavigationView = findViewById(R.id.nav_view);
mDrawerLayout = findViewById(R.id.drawer_layout);
mTrustZoneToggle = mNavigationView.getMenu().findItem(R.id.menu_activity_trustzone);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.text_navigationDrawerOpen, R.string.text_navigationDrawerClose);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
mFilter.addAction(CommunicationService.ACTION_TRUSTZONE_STATUS);
mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
applyAwaitingDrawerAction();
}
});
mNavigationView.setNavigationItemSelectedListener(this);
mActionMode.setOnSelectionTaskListener(new PowerfulActionMode.OnSelectionTaskListener() {
#Override
public void onSelectionTask(boolean started, PowerfulActionMode actionMode) {
toolbar.setVisibility(!started ? View.VISIBLE : View.GONE);
}
});
mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
mFirebaseRemoteConfig.activate();
boolean updated = task.getResult();
View headerView = mNavigationView.getHeaderView(0);
MenuItem boredItem = mNavigationView.getMenu().findItem(R.id.bored);
Configuration configuration = getApplication().getResources().getConfiguration();
boredItem.setVisible(mFirebaseRemoteConfig.getBoolean("remote_bored"));
Toast.makeText(HomeActivity.this, "Fetch and activate succeeded",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HomeActivity.this, "Fetch failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
Here is remote.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- START xml_defaults -->
<defaultsMap>
<entry>
<key>remote_bored</key>
<value>false</value>
</entry>
</defaultsMap>
<!-- END xml_defaults -->
Here is drawer_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="#+id/bored_button"
android:orderInCategory="19"
android:title="#string/bored"
android:icon="#drawable/ic_bored"
android:actionLayout="#layout/layout_main_navigationview_footer"/>
</group>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/toolbar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
style="?navigationViewStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header_default_device"
app:menu="#menu/drawer_main" />
</androidx.drawerlayout.widget.DrawerLayout>
Logcat:
2020-07-25 21:47:07.228 20224-20224/go.dodo.GETit E/AndroidRuntime: FATAL EXCEPTION: main
Process: go.dodo.GETit, PID: 20224
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible(boolean)' on a null object reference
at go.dodo.GETit.activity.HomeActivity$3.onComplete(HomeActivity.java:203)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##17.0.2:4)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at com.google.android.gms.internal.tasks.zzb.dispatchMessage(com.google.android.gms:play-services-tasks##17.0.2:6)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
This code is returning null:
MenuItem boredItem = mNavigationView.getMenu().findItem(R.id.bored);
This means that your inflated menu XML doesn't have an item called "bored". Perhaps you meant bored_button?

Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am developing new android app using navigation drawer and extending
baseactivity and following this link
Same Navigation Drawer in different Activities
but I am getting following exception
Process: edgar.yodgorbek.sportnews, PID: 7608
java.lang.RuntimeException: Unable to start activity ComponentInfo{edgar.yodgorbek.sportnews/edgar.yodgorbek.sportnews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3102)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
at edgar.yodgorbek.sportnews.BaseActivity.onCreate(BaseActivity.java:44)
at edgar.yodgorbek.sportnews.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7650)
at android.app.Activity.performCreate(Activity.java:7639)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1295)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3077)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:209) 
at android.app.ActivityThread.main(ActivityThread.java:7021) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872) 
below my BaseActivity class
public class BaseActivity extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
public String[] layers;
Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private Map map;
protected void onCreate(Bundle savedInstanceState) {
// R.id.drawer_layout should be in every activity with exactly the same id.
super.onCreate(savedInstanceState);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle( this, drawerLayout,toolbar,0, 0) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.base_activity, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.base_activity, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.base_activity, null, false);
drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// map.drawerClickEvent(pos);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
below base_activity.xml
android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
below my MainActivity
public class MainActivity extends BaseActivity {
public List<Article> articleList = new ArrayList<Article>();
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
private SportNews sportNews;
private ArticleAdapter articleAdapter;
private DrawerLayout drawerLayout;
private ListView drawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
SportInterface sportInterface = SportClient.getApiService();
Call<SportNews> call = sportInterface.getArticles();
call.enqueue(new Callback<SportNews>() {
#Override
public void onResponse(Call<SportNews> call, Response<SportNews> response) {
sportNews = response.body();
if (sportNews != null && sportNews.getArticles() != null) {
articleList.addAll(sportNews.getArticles());
}
articleAdapter = new ArticleAdapter(articleList, sportNews);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(articleAdapter);
}
#Override
public void onFailure(Call<SportNews> call, Throwable t) {
}
});
}
}
below activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
Actually, your BaseActivity has not Layout Set(setContentView) so indeed the DrawerLayout will be null, you should Not declare View/findViewById in your BaseActivity, also, the super.onCreate() in your MainActivity trigger before everything the onCreate() in the BaseActivity and thus causing the crash
Write the below line After super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

How can I extend AppCompatActivity to centralize codes, e.g. DrawerLayout?

I would like to extend AppCompatActivity to centralize codes in order to share codes, e.g. DrawerLayout, etc.
However, I encounter NullPointerException. Here is my code:
MasterActivity
public class MasterActivity extends AppCompatActivity {
public static final String TAG = "MasterActivity";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setupDrawer() {
// Drawer
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
}
}
ChildActivity
public class ChildActivity extends MasterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
setupDrawer();
}
}
activity_child.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ChildActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Main Content -->
</LinearLayout>
<LinearLayout android:id="#+id/llv_left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:background="#888" >
<!-- Drawer Content -->
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
The NPE appears at:
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
the error message is:
Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int, int)' on a null object reference
Obviously the variable mDrawerLayout is null, as findViewById() cannot locate it from layout XML. The R.id.drawer_layout is located at R.layout.activity_child. If the ChildActivity extends AppCompatActivity, the NPE does not appear.
How can I resolve it?
How about
protected void setupDrawer(View v) {
mDrawerLayout = (DrawerLayout)v.findViewById(R.id.drawer_layout);
...
and then in ChildActivity
setContentView(R.layout.activity_child);
setupDrawer(findViewById(android.R.id.content));//use root view

Why is my Intent starting an empty Activity instead of the right one?

Hopefully i can find some help here, because I'm looking for weeks already for a solution. I am using android studio for programming the app.
When I'm pressig the Button to start the new Activity it's opening an empty Activty instead of that one which was supposed to be opened.
The new Activity is coded in the Manifest, and there aren't any error notifications. Maybe its not getting the intent?
Here the MainActivity:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
FloatingActionButton fabtn1;
FloatingActionButton fabtn2;
FloatingActionButton fabtn3;
FloatingActionButton fabtn4;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter1 viewPagerAdapter1 = new ViewPagerAdapter1(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter1);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
fabtn1 = (FloatingActionButton) findViewById(R.id.fab1);
fabtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
if ((counter % 2) == 1) {
fabtn2.animate().translationY(-200).setDuration(300).alpha(1);
fabtn3.animate().translationY(-400).setDuration(320).alpha(1);
fabtn4.animate().translationY(-600).setDuration(340).alpha(1);
}
if ((counter % 2) == 0) {
fabtn2.animate().translationY(0).setDuration(300).alpha(0);
fabtn3.animate().translationY(0).setDuration(320).alpha(0);
fabtn4.animate().translationY(0).setDuration(340).alpha(0);
}
}
});
//That's the Button, which should open the new Activity:
fabtn2 = (FloatingActionButton) findViewById(R.id.fab2);
fabtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Startmessageqp = new Intent(MainActivity.this, MessagesQP.class);
startActivity(Startmessageqp);
}
});
fabtn3 = (FloatingActionButton) findViewById(R.id.fab3);
fabtn4 = (FloatingActionButton) findViewById(R.id.fab4);
}
};
That's the new Activity which is supposed to be opened after pressing the button:
public class MessagesQP extends Activity {
EditText editText1;
EditText editText2;
FloatingActionButton fabMQ1;
FloatingActionButton fabQM2;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.message_quickpost);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
fabMQ1 = (FloatingActionButton) findViewById(R.id.fabmq1);
fabQM2 = (FloatingActionButton) findViewById(R.id.fabmq2);
}
}
Please inform if you need some more informations to help and I'm thankful for every answer!
NEW: Here The messages_quickpost.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:text="Type Message"
android:layout_marginTop="100dp"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="240dp"
android:layout_height="60dp"
android:inputType="textPersonName"
android:text="Contact Name"
android:id="#+id/editText2"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_marginTop="60dp" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fabmq1"
android:src="#drawable/send"
android:layout_alignBottom="#+id/editText"
android:layout_toRightOf="#+id/editText"
android:layout_toEndOf="#+id/editText" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fabmq2"
android:src="#drawable/account_plus"
android:layout_alignTop="#+id/editText2"
android:layout_toLeftOf="#+id/editText2"
android:layout_toStartOf="#+id/editText2" />
</RelativeLayout>
Thanks for helping!!
Thanks for all your helps finally I found the solution. The on create part is wrong! I switched it now from:
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.message_quickpost);
to:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_quickpost);
That was the Problem.. Now its working! Still thanks to all of you!
it's opening an empty Activty instead of that one which was supposed
to be opened.
Make a review for your message_quickpost layout, i can see that contain this elements editText1 , editText2 , fabMQ1 , fabMQ1 but you are not changing their properties like text, visibility etc.
setContentView(R.layout.message_quickpost);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
fabMQ1 = (FloatingActionButton) findViewById(R.id.fabmq1);
fabQM2 = (FloatingActionButton) findViewById(R.id.fabmq2);
Probably some of your elements has visibility property defined as INVISIBLE

Navigation drawer implementation with activities using inheritance

In my app I have to use navigation drawer with all activities. So I have created a base activity called DrawerActivity. I wrote the code for navigation drawer in DrawerActivity and then extended the UserDashBoardActivity from DrawerActivity.
The problem is that DrawerActivity properties aren't executed in UserDashBoardActivity. I can't interact with DrawerActivity in UserDashBoardActivity. Here that drawer menu is in ActionBar in all the activities.
This is my DrawerActivity
public class DrawerActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerItems = getResources().getStringArray(R.array.navigation_drawer_items_array);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(
this, R.layout.drawer_list_items, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View view) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
for (int index = 0; index < menu.size(); index++) {
MenuItem menuItem = menu.getItem(index);
if (menuItem != null) {
// hide the menu items if the drawer is open
menuItem.setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(DrawerActivity.this, UserDashBoardActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(DrawerActivity.this, AdmissionActivity.class);
startActivity(intent);
break;
}
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
This is my UseDashBoardActivity
public class UserDashBoardActivity extends DrawerActivity {
private Context context;
private ImageButton searchBtn;
private ImageButton favBtn;
private ImageButton profileBtn;
private ImageButton reminderBtn;
private ImageButton logoutBtn;
private ImageButton notificationBtn;
private ImageView seatchIcon;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onResume();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#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_user_dash_boad, menu);
return true;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notify:
return true;
case R.id.action_favourite:
return true;
case R.id.action_navigation:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setCustomView(R.layout.action_bar_layout);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
searchBtn = (ImageButton) findViewById(R.id.search_btn);
favBtn = (ImageButton) findViewById(R.id.fav_btn);
profileBtn = (ImageButton) findViewById(R.id.profile_btn);
reminderBtn = (ImageButton) findViewById(R.id.reminder_btn);
notificationBtn = (ImageButton) findViewById(R.id.notification_btn);
logoutBtn = (ImageButton) findViewById((R.id.logout_btn));
final EditText Search = (EditText)findViewById(R.id.emailAddress);
mDrawerList = (ListView)findViewById(R.id.drawer_layout);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent regAct = new Intent(getApplicationContext(), SearchActivity.class);
// Clears History of Activity
regAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(regAct);
}
});
favBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
Intent tabAct = new Intent(getApplicationContext(),TabHostActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
profileBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent tabAct = new Intent(getApplicationContext(),AboutCollegeActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
}
}
This is my actionbar xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appmunu="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.after2.svirtzone.after2_gradle.UserDashBoardActivity">
<item
android:id="#+id/action_notify"
android:icon="#drawable/mail_icon"
appmunu:showAsAction="always"
android:title="Notification" />
<item
android:id="#+id/action_favourite"
android:icon="#drawable/favourite_icon"
appmunu:showAsAction="always"
android:title="Favourite" />
<item
//this is the menu button for navigation drawer
android:id ="#+id/action_navigation"
android:icon="#drawable/ic_menu"
appmunu:showAsAction = "always"
android:title="navigation"
android:layout_gravity="left"/>
</menu>
This is the xml layout for navigationdrawer listview
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" ></FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
This layout is UserDashboard layout
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#color/appblue"
android:orientation="vertical">
<EditText
android:id="#+id/emailAddress"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#drawable/edit_text_style"
android:gravity="center|start"
android:hint="#string/edittext_hint"
android:inputType="textEmailAddress"
android:maxLength="40"
android:textSize="18sp"
android:visibility="gone" />
<ImageView
android:id="#+id/search_icon_btn"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="580dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-90dp"
android:padding="5dp"
android:src="#drawable/search_icon" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginRight="210dp"
android:layout_marginTop="30dp"
android:background="#drawable/search_blue"
android:gravity="center" />
<TextView
android:id="#+id/searchCollege"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="100dp"
android:layout_marginTop="20dp"
android:text="#string/search_college"
android:textColor="#color/green"
android:textSize="30sp" />
<ImageButton
android:id="#+id/fav_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="200dp"
android:layout_marginRight="5dp"
android:layout_marginTop="-305dp"
android:background="#drawable/fav_blue"
android:gravity="center" />
<TextView
android:id="#+id/myFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="500dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:text="#string/my_favourites"
android:textColor="#color/green"
android:textSize="30sp" />
</LinearLayout>
The UserDashboard activity is executed as it is but I need the property of DrawerActivity to be executed along with this activity. How to do it?
Let the parent Activity add the required ViewGroup as child of the FrameLayout. To achieve this, use the following method for DrawerActivity:
protected void addToContentView(int layoutResID)
{
// as part of onCreate() we had already
// setContentView(R.layout.activity_drawer);
if (layoutResID >= 0)
{
Toast.makeText(this, "activity content found", Toast.LENGTH_LONG).show();
FrameLayout fl = (FrameLayout)findViewById(R.id.activity_frame);
View.inflate(this, layoutResID, fl);
}
else
{
Toast.makeText(this, "activity content missing", Toast.LENGTH_LONG).show();
}
}
Then, in the onCreate() method of the child Activity:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// call this instead of setContentView()
addToContentView(R.layout.activity_user_dashboard);
// put here your code as before...
}
Drawer's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<!--you need to add everything to this frameLayout then only you will be able to access Navigation DrawerLayout-->
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/navigation_list"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:background="#color/white"
/>
</android.support.v4.widget.DrawerLayout>
The Activity with Drawer:(Only important code is shown)
public abstract class BaseDrawerLayoutActivity extends AppCompatActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout_activity);
//rest of the things
//NOTE: loadNavMenu is abstract so that you can implement it in other activities as per you need, otherwise remove this and load it here itself
loadNavMenu();
}
protected abstract void loadNavMenu();
// call this method whenever you enter new activity and load the fragment here.
public void showFragment(Fragment object, String title) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, object);
transaction.commit();
}}
Those activities which need the drawer menu can inherit above class. Not inflate all the layout's inside FrameLayout only.
public class MainActivity extends BaseDrawerLayoutActivity {
public static final String TAG = OLMSActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the method below will call the BaseDrawerLayoutActivity method and change the fragment for you to see.
showFragment(new MyProfileFragment(), "My Profile");
}
#Override
protected void loadNavMenu() {
NavItems.clear();
//load your menu items
}
private void loadNavFavourites(){
//todo
}}
MyProfileFragment is just a class with fragment and this one call inflate a layout in its OnCreateView method.

Categories

Resources