This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Everything works fine in my app but when I press the back button (I mean exit app) the app is crashing. And I don't know why? I tried a couple of solutions but nothing works. It's a sounds/ringtones application.
I am a newbie at Android and I need some advice like "delete this" / "add this"
Here my code
package com.app.trying;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.app.trying.tabs.Tab3;
import com.app.trying.tabs.Tab1;
import com.app.trying.tabs.Tab2;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public MediaPlayer mp;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Banner Ad
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbarTabs();
sidebar();
externalStorageAccess();
}
// Creates sidebar and sets onClickListeners
public void sidebar(){
mNavigationView = (NavigationView) findViewById(R.id.navigationView);
mNavigationView.setItemIconTintList(null);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()){
case R.id.sounds:
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name));
shareIntent.putExtra(Intent.EXTRA_TEXT, getText(R.string.share_text) + " " + getText(R.string.app_name) + "\n\n" + getText(R.string.playstore_link));
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_via)));
break;
}
return false;
}
});
}
// Is listening which sound on Tab1 has been clicked
public void TabOneItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab1.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab2 has been clicked
public void TabTwoItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab2.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab3 has been clicked
public void TabThreeItemClicked ( int position){
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab3.soundfiles[position]);
mp.start();
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
// Access external storage
public void externalStorageAccess(){
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/"+ getText(R.string.package_name) +"/files");
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
}
// Creates toolbar Tabs
public void toolbarTabs(){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}
}
And this is my error logs.
2019-05-09 19:13:22.296 704-704/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2019-05-09 19:13:32.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
2019-05-09 19:13:39.537 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:40.333 24095-24175/? E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2019-05-09 19:13:43.035 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:43.116 24095-24095/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.trying, PID: 24095
java.lang.RuntimeException: Unable to pause activity {com.app.trying/com.app.trying.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3735)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at com.app.trying.MainActivity.stopMediaPlayer(MainActivity.java:155)
at com.app.trying.MainActivity.onPause(MainActivity.java:150)
at android.app.Activity.performPause(Activity.java:6917)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3724)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapAllocatedSize18887424
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapSize35651584
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, getNativeHeapFreeSize16764160
2019-05-09 19:13:51.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
How should I resolve this error? Any help would be great. Thanks.
Your MediaPlayer instance is null as shown in the stacktrace, so:
public void stopMediaPlayer()
{
if (mp != null) {
mp.stop();
}
}
It can happen that your MediaPlayer instance is never initialization. So you have to handle it.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm studying Android java, and I have this error and can't run it.
Could you help me fixing this error? What is the problem?
Is it related to the error that I can't make a onClickListener() lambda expression? It gives me error and I can't import. So I tried making new View.OnclickListener() and its color is grey.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 9974
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
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:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
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:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I/Process: Sending signal. PID: 9974 SIG: 9
And this is my mainActivity.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setLogo(R.mipmap.ic_launcher_weight_round);
actionBar.setTitle(R.string.txtTitle);
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1){
Toast.makeText(MainActivity.this, "Please select conversion type", Toast.LENGTH_SHORT).show();
} else if (editTextInputWt.getText().toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please select baggage weight", Toast.LENGTH_SHORT).show();
} else {
double inputWt, outputWt;
try{
inputWt = Double.parseDouble(editTextInputWt.getText().toString());
if (inputWt<0){
Toast.makeText(MainActivity.this, "Baggage weight can't be negative.", Toast.LENGTH_SHORT).show();
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnKgsToLbs){
if (inputWt > 500){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 500Kilos", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt*2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Lbs", outputWt));
}
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnLbsToKgs){
if (inputWt > 1000){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 1000 pounds", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt/2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Kgs", outputWt));
}
}
} catch (Exception ex){
ex.printStackTrace();
}
}
}
});
}
}
This is due to you haven't initialised your views and as of this stage they are null and you can't invoke method on null object in java which you can see in your error.
so for this you have to initalise your variable you can do like following
findViewById()
View Binding
Data Binding
Creating view programmatically
as you have used layout file you can do findViewById() as following
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
radioGroup = findViewById(R.id.my_radio_group);
btnConvertWt = findViewById(R.id.my_button); // the id's are same as defined in your layout file
....
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
}
});
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I just got done one part of my code and went to launch the app and everything went fine. The build was successful and no issues were found. I then go to the emulator and the app doesn't launch and the log shows a lot of error.
Anyone know where I messed up and how I can fix it.Below is the errors from the log that I receive and I also pasted in the code that I was working on.
2019-05-07 13:06:14.358 22792-22792/com.example.drunktankfix E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drunktankfix, PID: 22792
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.drunktankfix/com.example.drunktankfix.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(int)' on a null object reference
at com.example.drunktankfix.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-05-07 13:06:16.368 22792-22792/com.example.drunktankfix I/Process: Sending signal. PID: 22792 SIG: 9
Also here is the code:
package com.example.drunktankfix;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.drunktankfix.AppFragment;
import com.example.drunktankfix.BlacklistFragment;
import com.example.drunktankfix.HelpFragment;
import com.example.drunktankfix.HomeFragment;
//implement the interface OnNavigationItemSelectedListener in your activity class
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
Button Save;
EditText edt1, edt2, edt3;
int in;
Float fl;
String st;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
Save = (Button) findViewById(R.id.BtnSave);
edt1 = (EditText) findViewById(R.id.editText1);
edt2 = (EditText) findViewById(R.id.editText2);
edt3 = (EditText) findViewById(R.id.editText3);
// to Retrieve the Data from the SharedPref
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int in1= prefs.getInt("in",0);
edt1.setText(in1);
float fl1 = prefs.getFloat("fl", 0);
edt2.setText(""+fl1);
String st1 = prefs.getString("st","");
edt3.setText(st1);
Save.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
in = Integer.parseInt(edt1.getText().toString());
fl = Float.parseFloat(edt2.getText().toString());
st = edt3.getText().toString();
// To save the data that is entered
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("in", in);
editor.putFloat("fl", fl);
editor.putString("st", st);
editor.apply();
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_Apps:
fragment = new AppFragment();
break;
case R.id.navigation_Blacklist:
fragment = new BlacklistFragment();
break;
case R.id.navigation_Help:
fragment = new HelpFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
You can not enter int value inside the edit text . Try to make it string.
edt1.setText(in1+"");
To set the integer propertly do the following:
edt1.setText("" + integer);
or better solution:
edt1.setText(String.valueOf(integer));
I am not sure how are you getting Nullpointer Exception But from the I code, I see any issue with your here.
editText.setText(Integer Value)
You are setting integer value to Edit text, So that in turn tries to get String resource based on the integer which you set to EditText.That should throw Resource not found Exception not NPE.
I'm just trying this library out to see if it fits my needs and so far I have not been able to get it to work. Here is the code
package com.example.user.bottomnavigationbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
PieChart pc;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
// case R.id.navigation_overview:
// Intent intentOverview = new Intent(MainActivity.this, activity_test.class);
// intentOverview.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// MainActivity.this.finish();
// startActivity(intentOverview);
// return true;
case R.id.navigation_expenses:
return true;
case R.id.navigation_reminder:
return true;
case R.id.navigation_income:
return true;
case R.id.navigation_login:
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
intentLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.finish();
startActivity(intentLogin);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
pc = findViewById(R.id.chart);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
And here is the error I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.bottomnavigationbar, PID: 4172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.bottomnavigationbar/com.example.user.bottomnavigationbar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at com.example.user.bottomnavigationbar.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I've searched for a bit and all I've found was that for others, they did not initialize the object hence it throws this error. Now someone did mention that it is possible to create the chart in code and then add it to the activity as the documentation's Getting Started page suggests but I have been unable to get it working. So what gives?
P.S Left in the code for navigation as I'm not sure if it might be the cause of the issue
You are first finding the view and then providing the content view to your activity replace with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pc = findViewById(R.id.chart);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Hello my question is about my app is crash after I am trying to hit next fragment.
Code is compiling but i don't know how to solve this problem.
Something with onclicklistner.
I tried some solutions but didn't succeed.
This is my code:
ProfileFragment.java
package com.statusionew.statusio.fragments;
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.statusionew.statusio.ForgetchangePasswordActivity; import com.statusionew.statusio.LoginActivity; import com.statusionew.statusio.R; import com.statusionew.statusio.MainActivity;
import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
public class ProfileFragment extends BaseFragment implements View.OnClickListener{
FirebaseAuth auth;
FirebaseUser user;
ProgressDialog PD;
#BindView(R.id.sign_out_button) Button btnSignOut;
#BindView(R.id.change_password_button) Button btnChangePass;
#BindView(R.id.change_email_button) Button btnChangeEmail;
#BindView(R.id.delete_user_button) Button btnDeleteUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_setting, container, false);
ButterKnife.bind(getActivity(), view);
((MainActivity) getActivity()).updateToolbarTitle("Profile");
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
PD = new ProgressDialog(getActivity());
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.sign_out_button)
public void onClick(View view) {
auth.signOut();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
}
};
}
});
btnChangePass.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_password_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 1));
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_email_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 2));
}
});
btnDeleteUser.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.delete_user_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 3));
}
});
}
#Override
public void onClick(View v) {
if (auth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
super.onResume();
} }
this the log that say 'Attempt to invoke virtual method'-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.statusionew.statusio, PID: 9206
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.statusionew.statusio.fragments.ProfileFragment.onCreate(ProfileFragment.java:65)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:781)
at com.statusionew.statusio.views.FragNavController.executePendingTransactions(FragNavController.java:631)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:142)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:158)
at com.statusionew.statusio.MainActivity.switchTab(MainActivity.java:149)
at com.statusionew.statusio.MainActivity.access$100(MainActivity.java:30)
at com.statusionew.statusio.MainActivity$1.onTabSelected(MainActivity.java:87)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Connected to process 10580 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.statusionew.statusio-1/lib/x86
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
V/FA: Registered activity lifecycle callback
I/FirebaseInitProvider: FirebaseApp initialization successful
I/InstantRun: starting instant run server: is main process
E/InstantRun: IO Error creating local socket at com.statusionew.statusio
java.io.IOException: Address already in use
at android.net.LocalSocketImpl.bindLocal(Native Method)
at android.net.LocalSocketImpl.bind(LocalSocketImpl.java:308)
at android.net.LocalServerSocket.<init>(LocalServerSocket.java:48)
at com.android.tools.ir.server.Server.<init>(Server.java:91)
at com.android.tools.ir.server.Server.create(Server.java:85)
at com.android.tools.ir.server.InstantRunContentProvider.onCreate(InstantRunContentProvider.java:49)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
It seems like you've got some misunderstandings about how Fragments and ButterKnife work.
OnCreate is called BEFORE onCreateView in a Fragment. So all your views are null when you're trying to access them in onCreate.
See Fragment Lifecycle:
https://www.tutorialspoint.com/android/images/fragment.jpg
OnCreate is not used that much in Fragments, onCreateView is used more.
Your ButterKnife bind code is also wrong. You're trying to bind the Activity to the views in the Fragment.
See ButterKnife documentation for correct usage: http://jakewharton.github.io/butterknife/
This question already has answers here:
This Activity already has an action bar supplied by the window decor
(25 answers)
Closed 6 years ago.
while I test my app, I get the follow error in the Android-Studio-Consol:
10-09 20:44:56.685 21573-21573/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 21573
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-09 20:49:57.180 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.795 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.905 26089-26089/com.example.android.buyhatke W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke D/AndroidRuntime: Shutting down VM
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 26089
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My codes are
MainActivity.java
package com.example.android.buyhatke;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
facebookSDKInitialize();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
getLoginDetails(loginButton);
}
/*
Initialize the facebook sdk.
And then callback manager will handle the login responses.<br />
*/
protected void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
/*
Register a callback function with LoginButton to respond to the login result.
On successful login,login result has new access token and recently granted permissions.
*/
protected void getLoginDetails(LoginButton login_button){
// Callback registration<br />
login_button.registerCallback(callbackManager, new FacebookCallback <LoginResult> (){
#Override
public void onSuccess(LoginResult login_result) {
getUserInfo(login_result);
}
#Override
public void onCancel() {
// code for cancellation
}
#Override
public void onError(FacebookException error) {
// code for error handling.
}
});
}
/*To get the facebook user's own profile information via creating a new request.
When the request is completed, a callback is called to handle the success condition. */
protected void getUserInfo(LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted( JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this,HomeActivity.class);
intent.putExtra("jsondata",json_object.toString());
startActivity(intent);
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Log.e("data",data.toString());
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
HomeActivity.java
package com.example.android.buyhatke;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email;
ImageView user_picture;
NavigationView navigation_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home Page"); // may produce null pointer exception
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata); // call setUserProfile Method
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.openDrawer, R.string.closeDrawer);
try {
drawer.setDrawerListener(toggle);
}catch(NullPointerException e)
{
Context context = getApplicationContext();
CharSequence text = "Error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
toggle.syncState();
navigation_view.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*
Set Navigation header by using Layout Inflater.<br />
*/
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
/*
Set User Profile Information in Navigation Bar.<br />
*/
public void setUserProfile(String jsondata){
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.<br />
// getMenuInflater().inflate(R.menu.home, menu);<br />
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {/** check if error*/
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id ==R.id.inbox) {
// Handle the camera action
} else if (id ==R.id.starred) {
}
else if (id ==R.id.sent_mail) {
}
else if (id ==R.id.drafts) {
}
else if (id ==R.id.allmail ) {
}
else if (id ==R.id.trash ) {
}
else if (id ==R.id.spam ) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
can anyone help?
In your styles.xml file, change your theme parent to NoActionBar if you are using Toolbar.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">