Trying to set up the Navigation Drawer of an app right now, and every time I try to run the app on my Android device, I get a NullPointerException. The error is caused by getActionBar.setDisplayHomeUpAsEnabled(true) and getActionBar.setHomeButtonEnabled(true)
Even if I remove these two lines of code, I still get an error.
How do I fix this quickly?
Code:
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private String[] navDrawerTitles;
private DrawerLayout navDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
Fragment fragment = new Fragment();
private Fragment blankFrag = new Fragment();
private final int POSITION = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navDrawerTitles = getResources().getStringArray(R.array.nav_array);
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, navDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
navDrawerLayout, /* DrawerLayout object */
//R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
// super.onDrawerClosed(view);
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
};
// Set the drawer toggle as the DrawerListener
navDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = navDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
/**
* Starts an Activity when item is clicked
*/
private void selectItem(int position) {
// }
Bundle args = new Bundle();
args.putInt(StartingFragment.TEA_TYPE_POS, position);
fragment.setArguments(args);
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
// setTitle(navDrawerTitles[position]);
navDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
01-31 14:11:11.298: E/AndroidRuntime(20904): FATAL EXCEPTION: main
01-31 14:11:11.298: E/AndroidRuntime(20904): Process:
appathon.bu.com.appathon, PID: 20904 01-31 14:11:11.298:
E/AndroidRuntime(20904): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{appathon.bu.com.appathon/appathon.bu.com.appathon.MainActivity}:
java.lang.NullPointerException 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.access$800(ActivityThread.java:144) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.os.Handler.dispatchMessage(Handler.java:102) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.os.Looper.loop(Looper.java:136) 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
android.app.ActivityThread.main(ActivityThread.java:5146) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
java.lang.reflect.Method.invokeNative(Native Method) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
java.lang.reflect.Method.invoke(Method.java:515) 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
dalvik.system.NativeStart.main(Native Method) 01-31 14:11:11.298:
E/AndroidRuntime(20904): Caused by: java.lang.NullPointerException
01-31 14:11:11.298: E/AndroidRuntime(20904): at
appathon.bu.com.appathon.MainActivity.onCreate(MainActivity.java:45)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.Activity.performCreate(Activity.java:5231) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-31 14:11:11.298: E/AndroidRuntime(20904): ... 11 more
First, if getActionBar() in an Activity is returning null, then you do not have a native action bar in your activity.
Second, android.support.v7.app.ActionBarDrawerToggle does not work with the native action bar. It works with the appcompat-v7 action bar backport. If you are going to use android.support.v7.app.ActionBarDrawerToggle, then you have to move your app over to use appcompat-v7:
Add appcompat-v7 as a dependency
Inherit from ActionBarActivity instead of Activity
Call getSupportActionBar() rather than getActionBar()
Use Theme.AppCompat (or something that inherits from it) as your activity's theme
I had the same error as you. My solution was to set theme with ThemeAppCompat, make your activity extend AppCompatActivity and use the method of getSupportActionBar instead of using the method of getActionBar. In short, you should make sure the actionBar of theme and the method which to get actionBar have the same support library.
Related
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">
I'm making an app that by now should save and then get the value of a numeric Edit Text. When i put to load data from string.xml it went fine, but when i switched to SharedPreferences it didn't even start. Any help finding the problem would be appreciated. BTW .java is below and i'm sure layout .xml is fine.
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
final EditText mEditText1=(EditText)findViewById(R.id.editText1), mEditText2=(EditText)findViewById(R.id.editText2), mEditText3=(EditText)findViewById(R.id.editText3), mEditText4=(EditText)findViewById(R.id.editText4), mEditText5=(EditText)findViewById(R.id.editText5);
Button mButton1=(Button)findViewById(R.id.button1), mButton2=(Button)findViewById(R.id.button2), mButton3=(Button)findViewById(R.id.button3), mButton4=(Button)findViewById(R.id.button4), mButton5=(Button)findViewById(R.id.button5);
SharedPreferences storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE), storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE), storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE), storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE), storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I believe this is the applications crash log. I'm new to Android so if it is not just say it, no need to get angry :P
05-01 13:24:53.061 1624-1624/programmingandroidapps.brightnesscustomizationapp D/dalvikvm: Not late-enabling CheckJNI (already on)
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp D/AndroidRuntime: Shutting down VM
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb3d11b20)
05-01 13:24:56.471 1624-1624/programmingandroidapps.brightnesscustomizationapp E/AndroidRuntime:
FATAL EXCEPTION: main
Process: programmingandroidapps.brightnesscustomizationapp, PID: 1624
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{programmingandroidapps.brightnesscustomizationapp/programmingandroidapps.brightnesscustomizationapp.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at programmingandroidapps.brightnesscustomizationapp.MainActivity.<init>(MainActivity.java:21)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you are calling findViewById and getSharedPreferences before layout has been applied and the activity (this) was initialized. You should put those method calls in onCreate after setContentView(R.layout.activity_main);.
Dejan is right about moving part of the code into the onCreate lifecycle method, specifically, your code should change to something like this:
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
private EditText mEditText1, mEditText2, mEditText3, mEditText4, mEditText5;
private Button mButton1,mButton2, mButton3, mButton4, mButton5;
private SharedPreferences storedBrightness1, storedBrightness2, storedBrightness3,storedBrightness4,storedBrightness5;
private SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 =(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
mButton3=(Button)findViewById(R.id.button3);
mButton4=(Button)findViewById(R.id.button4);
mButton5=(Button)findViewById(R.id.button5);
mEditText1 =(EditText)findViewById(R.id.editText1);
mEditText2=(EditText)findViewById(R.id.editText2);
mEditText3=(EditText)findViewById(R.id.editText3);
mEditText4=(EditText)findViewById(R.id.editText4);
mEditText5=(EditText)findViewById(R.id.editText5);
//instead of doing this, I'd rather use "named" SharedPreferences - call it "brightness" and will carry the five values
//something like SharedPreferences brightnessPreferences = this.getSharedPreferences("brightness", Context.MODE_PRIVATE);
//I ma just adding this here because that's the way you have it
storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE),
storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE),
storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE),
storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE),
storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I have created a drawer menu in android studio and changed items of drawer. I want to start another activity or view another layout on item click. but i get the following error and application is stopped.
03-24 21:38:28.202 2227-10289/? D/GassUtils: Found app info for package com.example.imran.myapp:1. Hash: 6b9333e031907d7a6a6c12cd9fdfa0d23bd13ee0f40c9617ddd005dc358321b0
03-24 21:38:28.202 2227-10289/? D/k: Found info for package com.example.imran.myapp in db.
03-24 21:38:38.722 1035-1167/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:38.782 9789-9789/? I/Timeline: Timeline: Activity_launch_request id:com.example.imran.myapp time:121627337
03-24 21:38:38.802 1035-1853/? W/ActivityManager: NORMAL SET : srcAppInfo.processName = com.example.imran.myapp, destAppInfo.processName = com.example.imran.myapp
03-24 21:38:38.802 1035-1853/? W/ActivityManager: startActivity called from finishing ActivityRecord{28b176ac u0 com.example.imran.myapp/.MainActivity t2394 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.example.imran.myapp/.Home (has extras) }
03-24 21:38:38.802 1035-1853/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:39.402 1035-1532/? I/WindowManager: Switching to real app window: Window{11c67d3b u0 com.example.imran.myapp/com.example.imran.myapp.Home}
03-24 21:38:39.622 1035-1069/? I/Timeline: Timeline: Activity_windows_visible id: ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396} time:121628177
03-24 21:38:58.462 9789-9789/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.imran.myapp, PID: 9789
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
at com.example.imran.myapp.Home.onNavigationItemSelected(Home.java:120)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:146)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:84)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.design.internal.NavigationMenuPresenter.onItemClick(NavigationMenuPresenter.java:196)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1536)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3683)
at android.widget.AbsListView$3.run(AbsListView.java:5604)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.462 1035-1514/? W/ActivityManager: Force finishing activity com.example.imran.myapp/.Home
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: processName: com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: broadcastEvent : com.example.imran.myapp data_app_crash
03-24 21:38:58.992 1035-1062/? W/ActivityManager: Activity pause timeout for ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396 f}
Java files:
Home.java
package com.example.imran.myapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class Home 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);
Button logout = (Button) findViewById(R.id.logout_button);
TextView text1 = (TextView) findViewById(R.id.result_sms);
final UserLocalStore loginuser = new UserLocalStore(getApplicationContext());
SharedPreferences mPrefs = getSharedPreferences("userDetails",0);
String str1=(mPrefs.getString("fullname","Default_Value"));
String email = loginuser.getLoggedInUser().email;
text1.setText("Welcome "+str1+"- Your email: "+email);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginuser.clearUserData();
//startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
//setContentView(R.layout.activity_main);
}
});
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() {
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_photos) {
// Handle the camera action
//setContentView(R.layout.myaccount);
} else if (id == R.id.nav_myaccount) {
setContentView(R.layout.activity_myaccount2);
//
} else if (id == R.id.nav_logout) {
UserLocalStore loginuser = new UserLocalStore(this);
loginuser.clearUserData();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
In the last part of home.java when i add setContentView(R.layout.activity_myaccount2);
then the app crashes.
The problem here is a Null Pointer Exception when calling drawer.closeDrawer(); and as you've stated this happens after setContentView(R.layout.activity_myaccount2); is called.
By using setContentView, you're replacing your whole layout with another one, and it seems in this case like you're replacing your layout that contains R.id.drawer_layout with another one that doesn't contain it. The null pointer exception then happens when you try to use findViewById and closeDrawer, when the layout containing the drawer isn't there anymore, it's been replaced with another using setContentView.
To fix this you may need to rethink how you are structuring your app and displaying different content. As a starting point, I'd suggest looking up examples using an Activity which contains your drawer and Fragments to show the different pieces of content. The Activity and drawer are always there, only the fragments change, like this tutorial.
I have a list of Claim objects, each claim object is initialized with a name and an expense list.
i made an adapter for the listview for the claims. what I am trying to do now is create an adaptor for the expenses. Since each claim has its own expense list, i cannot just make a general adapter. i need to make an adapter for a specific Claim, or am thinking of this wrong? here is what I did..
JUST TO BE CLEAR< MY QUESTION IS: How do I make an adaptor for the list initializd with the expenses, and open that list-view to see the expenses of a specific claim when I click on it?
package app.zioueche_travelexpense;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
//figure out how to add claim in different page. so we can add date range.
public class AddClaim extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_claim);
//adapter for claim view this one works. it is the expenses one that i do not know how to implement
ListView listView = (ListView) findViewById(R.id.claimListView);
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
final ArrayList<Claim> list = new ArrayList<Claim>(claims);
final ArrayAdapter<Claim> claimAdapter = new ArrayAdapter<Claim>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(claimAdapter);
//Added observer pattern
ClaimListController.getClaimList().addListener(new Listener(){
#Override
public void update(){
list.clear();
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
list.addAll(claims);
claimAdapter.notifyDataSetChanged();
}
});
//SINGLE TAP FUNCTION
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//adapter expenses I DO NOT KNOW HOW TO IMPLEMENT THIS
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap); //THIS IS MY LINE 64
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_claim, menu);
return true;
}
protected void onDeleteClick(final int position, final ArrayList<Claim> list){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(position).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(position);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addClaimView(MenuItem item){
Toast.makeText(this, "going to claim creation page", Toast.LENGTH_SHORT).show();
setContentView(R.layout.claim_add_page);
}
public void addClaims(View v){
ClaimListController ct = new ClaimListController();
EditText textView = (EditText) findViewById(R.id.add_claim_field);
String added = textView.getText().toString();
if (!TextUtils.isEmpty(added)){
final String t = format("added",added);
ct.addClaim(new Claim(added));
Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
textView.setText("");
setContentView(R.layout.claim_list);
//Intent intent = new Intent(MainActivity.this, AddClaim.class);
//startActivity(intent);
}else{
Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
}
}
private String format(String string, String added) {
String formats = string +" "+ added;
return formats;
}
}
As you can see, i made my listview adapter for the expenses inside the onclick method, since i need the position to get the expense list out of the specific claim.
How can I do this/ when I run this code I get null pointer exceptions on line 64.
here is the log cat.
01-24 02:01:15.434: E/AndroidRuntime(1099): FATAL EXCEPTION: main
01-24 02:01:15.434: E/AndroidRuntime(1099): java.lang.NullPointerException
01-24 02:01:15.434: E/AndroidRuntime(1099): at app.zioueche_travelexpense.AddClaim$2.onItemClick(AddClaim.java:64)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.handleCallback(Handler.java:725)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Looper.loop(Looper.java:137)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-24 02:01:15.434: E/AndroidRuntime(1099): at dalvik.system.NativeStart.main(Native Method)
01-24 02:01:17.814: E/Trace(1117): error opening trace file: No such file or directory (2)
I know that this is question had been asked several time, but I saw that the answer always change in relation to the code.
So, I have GameActivity that retrieve informations from a database in the global "info" variable, that is a String[].
Next I need to replace the current fragment with another fragment in relation to the button pressed (see methods "trueAnswer" and "falseAnswer"), and set two TextViews of that new fragment with the informations retrieved in the "info" string array.
The problem is that I'm able to set the informations the first time, in the first fragment in the method onStart() when the activity is created, but then seems like the "info" array is empty, because the "if" in the methods "trueAnswer" and "falseAnswer" doesn't works, and when I try to set the TextViews in the new fragment with the method "changeText(String, String)", the app crashes and return a NullPointerExeption.
I can't really see where is the error in the code, so I post here my methods and the logCat, hoping that may help you too.
GameActivity:
import java.io.IOException;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class GameActivity extends ActionBarActivity {
public long n = 0;
public String[] info = new String[3];
DataBase myDbHelper = new DataBase(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new PlaceholderFragment()).commit();
}
}
public void randomize(){
n = Math.round((Math.random()*3)+1);
}
public String[] getDatabaseInfo(){
myDbHelper.refresh();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("NON HO CARICATO IL DATABASE TI PREGO SCUSAMI");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
return info = myDbHelper.getQuestion(n);
}
#Override
public void onStart(){
super.onStart();
randomize();
getDatabaseInfo();
TextView d = (TextView)findViewById(R.id.question);
d.setText(info[1]);
}
#Override
public void onResume(){
super.onResume();
// Controlla qual e il colore di sfondo nei settings e lo applica
FrameLayout ll = (FrameLayout)findViewById(R.id.container);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int bgc = Color.parseColor(sharedPref.getString("background_color", "#000000"));
if(bgc == Color.BLACK){
TextView myTextView = (TextView)findViewById(R.id.question);
TextView r = (TextView)findViewById(R.id.answer);
myTextView.setTextColor(Color.WHITE);
r.setTextColor(Color.GRAY);
}
ll.setBackgroundColor(bgc);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void trueAnswer(View view){
if(info[2] == "1"){
// Create new fragment and transaction
FragmentCorrect newFragment = new FragmentCorrect();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.container, newFragment);
// Commit the transaction
transaction.commit();
newFragment.changeText(info[1], info[0]);
}else{
// Create new fragment and transaction
FragmentWrong newFragment = new FragmentWrong();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.container, newFragment);
// Commit the transaction
transaction.commit();
newFragment.changeText(info[1], info[0]);
}
}
public void falseAnswer(View view){
if(info[2] == "1"){
// Create new fragment and transaction
FragmentCorrect newFragment = new FragmentCorrect();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.container, newFragment);
// Commit the transaction
transaction.commit();
newFragment.changeText(info[1], info[0]);
}else{
// Create new fragment and transaction
FragmentWrong newFragment = new FragmentWrong();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.container, newFragment);
// Commit the transaction
transaction.commit();
newFragment.changeText(info[1], info[0]);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_game, container,
false);
return rootView;
}
}
}
FragmentCorrect:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentCorrect extends Fragment {
TextView questionTv, answerTv;
public FragmentCorrect() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_corretto, container,
false);
questionTv = (TextView)rootView.findViewById(R.id.question);
answerTv = (TextView)rootView.findViewById(R.id.answer);
return rootView;
}
public void changeText(String question, String answer){
questionTv.setText(question);
answerTv.setText(answer);
}
}
FragmentWrong:(same code as FragmentCorrect, but with a different fragment layout).
LogCat:
05-19 12:13:04.278: E/AndroidRuntime(16694): FATAL EXCEPTION: main
05-19 12:13:04.278: E/AndroidRuntime(16694): java.lang.IllegalStateException: Could not execute method of the activity
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.view.View$1.onClick(View.java:3704)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.view.View.performClick(View.java:4232)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.view.View$PerformClick.run(View.java:17298)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.os.Handler.handleCallback(Handler.java:615)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.os.Handler.dispatchMessage(Handler.java:92)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.os.Looper.loop(Looper.java:137)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.app.ActivityThread.main(ActivityThread.java:4921)
05-19 12:13:04.278: E/AndroidRuntime(16694): at java.lang.reflect.Method.invokeNative(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694): at java.lang.reflect.Method.invoke(Method.java:511)
05-19 12:13:04.278: E/AndroidRuntime(16694): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
05-19 12:13:04.278: E/AndroidRuntime(16694): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
05-19 12:13:04.278: E/AndroidRuntime(16694): at dalvik.system.NativeStart.main(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694): Caused by: java.lang.reflect.InvocationTargetException
05-19 12:13:04.278: E/AndroidRuntime(16694): at java.lang.reflect.Method.invokeNative(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694): at java.lang.reflect.Method.invoke(Method.java:511)
05-19 12:13:04.278: E/AndroidRuntime(16694): at android.view.View$1.onClick(View.java:3699)
05-19 12:13:04.278: E/AndroidRuntime(16694): ... 11 more
05-19 12:13:04.278: E/AndroidRuntime(16694): Caused by: java.lang.NullPointerException
05-19 12:13:04.278: E/AndroidRuntime(16694): at com.example.quizone_2.FragmentWrong.changeText(FragmentWrong.java:29)
05-19 12:13:04.278: E/AndroidRuntime(16694): at com.example.quizone_2.GameActivity.trueAnswer(GameActivity.java:151)
05-19 12:13:04.278: E/AndroidRuntime(16694): ... 14 more
05-19 12:13:06.403: I/Process(16694): Sending signal. PID: 16694 SIG: 9
Thank you very much in advance
You're creating a new fragment and immediately calling changeText() on it. The fragment transaction that creates the fragment view, calling the lifecycle callbacks such as onCreateView(), has not yet been run.
Consider passing arguments to your fragmens using a bundle and not call fragment methods directly outside fragment lifecycle.
You are calling
newFragment.changeText(info[1], info[0]);
too soon. You need to wait till the Fragment is attached to the Activity. Your views are null.
Also use .equalsto compare strings instead of == .
if(info[2].equals("1"))
Get to know Fragment lifecycle
http://developer.android.com/guide/components/fragments.html
Adding further to what laalto posted
Send data from activity to fragment in android