This is the standard code generated by the Android Studio, with my method initAccount(), where I get the user model and write it in myAccount variable. When I do a Snackbar or something, the data is present, but when I want to write the user data into the navigation header, an error appears:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.vegevgsdsfa/com.sgsgsgdbsdg.activities.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.nfjg;lahjg;glsg.models.User.getNickName()' on a
null object reference
It's line nick.setText(myAccount.getNickName());
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ApiCaller userInfo;
User myAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initAccount();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
TextView nick = (TextView)headerView.findViewById(R.id.txt_nickname);
nick.setText(myAccount.getNickName());
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void initAccount() {
userInfo = Core.buildInterceptCaller();
Call<User> call = userInfo.showAccount();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
myAccount = response.body();
} else
Snackbar.make(getCurrentFocus(), response.code(), Snackbar.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
}
I'm new to this and I can not understand what the problem is. Thank you for attention.
You should set nickname after response has arrived after the onResponse of retrofit is called. But now you are setting nick name in onCreate means retrofit hasnot completed its work but you are trying to set nickname.So its returning null in setnickname.
private void initAccount() {
userInfo = Core.buildInterceptCaller();
Call<User> call = userInfo.showAccount();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
myAccount = response.body();
nickname.setText(myAccount.getNickName); //Nickname global
} else
Snackbar.make(getCurrentFocus(), response.code(), Snackbar.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
Related
After starting the application for the first time I have a problem with NavigationView. Namely, when I expand navigation view and click on Conventional you can see that the fragment with the red background appears, but NavigationView does not disappear automatically, I have to hide it manually. How can I fix it?
This is my code:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.activity_main);
navigationView = findViewById(R.id.navigation_view);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int itemId = menuItem.getItemId();
switch(itemId) {
case R.id.conventional:
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.activity_main, new fragment_conventional()).commit();
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
Below is working code for me
Please update your actionBarDrawerToggle accordingly
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//drawer.setDrawerListener(toggle);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to send data from MainActivity to TimeActivity but the bundle received in TimeActivity is null. And a Null Pointer Exception is thrown when I do not put
s = extras.getString("key");
in the
if (extras != null) {
}
and a message saying "The App has unfortunately stopped".
but after pressing OK to the message, the TimeActivity starts and the value 125 is received in
String s;
This is MainActivity.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = name.getText().toString();
String e = "1";
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
if(n.length()==3){
Intent intent = new Intent(MainActivity.this, TimeActivity.class);
startActivity(intent);}else{
Toast.makeText(MainActivity.this,"The Roll Number Must be a 3 Digit number",Toast.LENGTH_LONG).show();
}
}
}
);
sharedpreferences=
getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name))
{
String s = sharedpreferences.getString(Name, "");
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
i.putExtra("key", s);
startActivity(i);
}
else
{
}
}
}
This is TimeActivity
public class TimeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Timely");setSupportActionBar(toolbar);
String s="0";
Bundle extras = getIntent().getExtras();
if (extras != null) {
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
startActivity(i);s = extras.getString("key");
}else{Toast.makeText(TimeActivity.this,"Bundle received Null. ",Toast.LENGTH_LONG).show();}
int r = Integer.parseInt(s);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.time, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.nav_home) {
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_about) {
startActivity(new Intent(TimeActivity.this, About.class));
} else if (id == R.id.nav_Develop) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Any kind of help will be appreciated.
I can see two possible problems here.
First, you don't pass the Bundle here in the MainActivity:
Intent intent = new Intent(MainActivity.this, TimeActivity.class);
startActivity(intent);
Second, you start the TimeActivity again in its onCreate() method.
if (extras != null) {
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
startActivity(i);
s = extras.getString("key");
}
I'm not able to build the corresponding code.. its showing red line under manager.beginTransaction().replace(R.id.relativelayout_for_fragment, attendanceFragment).commit(); What can I do?
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.nav_attendance) {
Toast.makeText(HomeActivity.this, "Attendance", Toast.LENGTH_SHORT).show();
AttendanceFragment attendanceFragment = new AttendanceFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relativelayout_for_fragment, attendanceFragment).commit();
} else if (id == R.id.nav_marklist) {
Toast.makeText(HomeActivity.this, "Mark List", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_studentdetails) {
Toast.makeText(HomeActivity.this, "Student Details", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_settings) {
Toast.makeText(HomeActivity.this, "Settings", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_sendsms) {
Toast.makeText(HomeActivity.this, "Send SMS", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_about) {
Toast.makeText(HomeActivity.this, "About", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
replace method has following signature
replace(int containerViewId, Fragment fragment)
So the second argument expects instanceof Fragment. So your AttendanceFragment should extend Fragment class
I am trying to load two frame layouts for different activities. the problem is both the frames showing data at the same. I used setVisibilty method in the main java file. I want, when one frame is showing data the other frame hides automatically. Could anyone tell me the java codes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setFrameVisibility (boolean frameOneVisible){
if (frameOneVisible){
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.homepage) {
Intent homepage = new Intent (MainActivity.this, MainActivity.class);
startActivity(homepage);
// Handle the camera action
} else if (id == R.id.foodpage) {
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.schedulepage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
} else if (id == R.id.emotionspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
} else if (id == R.id.basicneedspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frametwo
, new BasicneedsFragment())
.commit();
} else if (id == R.id.exit) {
askBeforeExit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onBackPressed() {
askBeforeExit();
}
private void askBeforeExit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Confirm Exit");
builder.setMessage("Are you sure you want to quit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}
Add a method call to the setFrameVisibility in your onCreate and other methods that you want to do the toggling between two layouts:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setFrameVisibility(true); //or false
}
I want to select an item in the navigation but I can't; why? Can any one help me?
public class Add_Disease extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Databasehelp myDb;
EditText editName;
Button btnAddData;
private DrawerLayout mDrawer ,dlDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__disease);
myDb =new Databasehelp(this);
editName =(EditText)findViewById(R.id.editText_Add_disease);
btnAddData=(Button)findViewById(R.id.button5_Disease);
AddData();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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_layout1);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view1);
navigationView.setNavigationItemSelectedListener(this);
}
public void AddData(){
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData_Desaese(editName.getText().toString());
if (isInserted = true)
Toast.makeText(Add_Disease.this, "data inserted", Toast.LENGTH_LONG);
else
Toast.makeText(Add_Disease.this, "data not inserted", Toast.LENGTH_LONG);
}
}
);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout1);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.nav_camara) {
// Handle the camera action
}
else if (id == R.id.nav_gallery) {
Intent intent3 = new Intent(this,Show_Disease_Medicines.class);
startActivity(intent3);
}
else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout1);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Can you add some log into the navigation Listener ?
Log.e("Debug","case one") ;
And check with the log cat
In the navigation listener I recommend a switch case like :
Switch(view. GetId()) {
Case id1:
Break;
Case id2:
Break
}
Sorry for the code example, I'm on my phone