Am not able figure out the solution for this problem Please help me.
Am trying to change the color of the toolbar by extracting the color in an image inside the collapseToolbarLayout here is my java code
public class ToolbarColorDynamic extends AppCompatActivity {
private CollapsingToolbarLayout collapsingToolbarLayout;
ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toolbar_color_dynamic);
setupToolbar();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar4);
collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));//to set the title
mImageView = (ImageView) findViewById(R.id.profile_id1);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.leodicaprio);
mImageView.setImageBitmap(bm);
setToolbarColor(bm);
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar4);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
// Show menu icon
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
}
/* This method is to set the color and to set the image*/
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
private Palette createPaletteSync(Bitmap bitmap) {
Palette p = Palette.from(bitmap).generate();
return p;
}
private Palette.Swatch checkVibrantSwatch(Palette p){
Palette.Swatch vibrant = p.getVibrantSwatch();
if (vibrant != null){
return vibrant;
}
return null;
}
}
I tried several steps like assert the value to not equal to null
assert vibrantSwatch != null;
and this step too--
if(vibrantSwatch != null){
tb.setBackgroundColor(vibrantSwatch.getRgb());
}
But Nothing seems to work!... I tried googling and check here too but couldn't find a solution for this.
Below is my logcat log
04-21 12:06:32.420 20288-20288/basavaraj.com.librarytools E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
04-21 12:06:37.974 20288-20288/basavaraj.com.librarytools E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{basavaraj.com.librarytools/basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.setToolbarColor(ToolbarColorDynamic.java:64)
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.onCreate(ToolbarColorDynamic.java:42)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Please help solve this issue.
Thank you!..
Your Toolbar is null. At the beginning in your setupToolbar() Method you reference the toolbar with the ID R.id.toolbar4 but inside of setToolbarColor() you reference it by R.id.toolbar
I found the solution.
In setToolbarColor() method i was referencing to a wrong toolbar id
so i just changed the code:-
From----
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);//This is the line i did silly mistake
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
To---
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar4);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
Related
My app is crashing...
I'm not able to understand why iS it is giving this error and how can i remove this error so the app starts working.
in the logcat it states:
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
2020-08-19 02:44:21.603 25163-25282/com. E/Parcel: Reading a NULL string not supported here.
My activity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;
private Toolbar mToolbar;
private CircleImageView NavProfileImage;
private TextView NavProfileUserName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
CurrentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_closed);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef.child(CurrentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
if (snapshot.hasChild("fullname")) {
String fullname = snapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}
if (snapshot.hasChild("profileimage")) {
String image = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.ic_profile_pic_grey).into(NavProfileImage);
}
else {
Toast.makeText(MainActivity.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
}
my logcat:
2020-08-19 02:44:21.603 25163-25282/com.app E/Parcel: Reading a NULL string not supported here.
2020-08-19 02:44:21.666 25163-25280/com.app V/FA: onActivityCreated
2020-08-19 02:44:21.828 25163-25336/com.appi V/FA: Connecting to remote service
2020-08-19 02:44:21.887 25163-25336/com.app V/FA: Connection attempt already in progress
2020-08-19 02:44:21.949 25163-25336/? V/FA: Connection attempt already in progress
2020-08-19 02:44:21.953 25163-25163/? W/ActionBarDrawerToggle: DrawerToggle may not show up because NavigationIcon is not visible. You may need to call actionbar.setDisplayHomeAsUpEnabled(true);
2020-08-19 02:44:21.969 25163-25163/? D/OpenGLRenderer: Skia GL Pipeline
2020-08-19 02:44:21.969 25163-25163/? D/MMListParser: onlineVersion -1 defaultVersion 20191101
2020-08-19 02:44:21.970 25163-25163/? D/mmscene: open server config failed /data/oppo/multimedia/oppo_display_perf_list.xml
2020-08-19 02:44:21.971 25163-25163/? D/mmscene: getHint applicationScene=com.appinion,idx=0 none
2020-08-19 02:44:21.981 25163-25163/? D/AndroidRuntime: Shutting down VM
2020-08-19 02:44:21.985 25163-25163/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app, PID: 25163
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.MainActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3146)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3296)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:114)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:74)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:500)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:913)
Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(DatabaseReference.java:96)
at com.appinion.MainActivity.onCreate(MainActivity.java:72)
at android.app.Activity.performCreate(Activity.java:7337)
at android.app.Activity.performCreate(Activity.java:7328)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3126)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3296)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:114)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:74)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:500)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:913)
2020-08-19 02:44:21.999 25163-25163/? I/Process: Sending signal. PID: 25163 SIG: 9
TELL ME WHERE I'M GOING WRONG...
please help me.....
thanks...
The error message is telling you that you passed null in a call to child(). You have only one place in your code where a null value is possible:
UsersRef.child(CurrentUserID).addValueEventListener(new ValueEventListener() {
This means CurrentUserID is null at the time you used it here. This means that mAuth.getCurrentUser().getUid() is null at the time you called it. Which means a user was not signed in at that time. You should check for null before using it like this.
I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
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 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
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)
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
I am working on adding Shared Preferences to my Note taking Android App and I am running into a peculiar null pointer exception. I am currently testing settings for font size and typeface in my app and have been able to successfully save the shared preferences for both but am having trouble with the retrieval part. When the settings are changed, they successfully change the font and font size on a Fragment for the remainder of time the app is opened but I cannot restore them if the app is restarted.
First weird Null Pointer is in the onCreate.
OnCreate:
//create a new note fragment if one has not been created yet
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.container);
if (mNoteFragment == null) {
mNoteFragment = new NoteFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container, mNoteFragment).commit();
}
//restore SharedPreferences
SharedPreferences sharedPrefs = getPreferences(0);
int stylePref = sharedPrefs.getInt(SharedPreferanceConstants.PREF_FONT_SIZE, 2);
String fontPref = sharedPrefs.getString(SharedPreferanceConstants.PREF_TYPEFACE, "");
Log.e("STYLEID", String.valueOf(stylePref));
Log.e("FONTTYPE", fontPref);
onStyleChange(null , stylePref); //NULL POINTER EXCEPTION HERE
onFontChange(null, fontPref);
The logs output "3" and "Impact" which are the correct values for size and font which indicates that stylePref and fontPref are not null.
The next Null Pointer is below.:
#Override
public void onStyleChange(CustomStyleDialogFragment dialog, int styleId) {
Log.d("NOTEFRAGMENT", String.valueOf(mNoteFragment));
mNoteFragment.setCustomStyle(styleId); //NULL POINTER EXCEPTION HERE
}
#Override
public void onFontChange(CustomStyleDialogFragment dialog, String fontName) {
mNoteFragment.setCustomFont(fontName);
}
I have tested logging the value of styleId and got "3" so that doesn't seem to be the issue. mNoteFragment isnt null either based on the log.
Here is the third NP Exception in the NoteFragment.java. This is where I ultimately set the EditText view to the desired settings. I had no trouble changing font and size without shared preferences so I am not sure the issue here.
public void setCustomFont(String fontName) {
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
public void setCustomStyle(int styleId) {
if(styleId == 1) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
}
else if(styleId == 2) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
}
else if(styleId == 3) {
//NULL POINTER EXCEPTION HERE
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
}
}
And of course, here is the logcat. Thanks in advance!
11-18 10:31:53.030 18966-18966/com.richluick.blocnotes I/Process﹕ Sending signal. PID: 18966 SIG: 9
11-18 10:35:32.838 19248-19248/com.richluick.blocnotes D/STYLEID﹕ 3
11-18 10:35:32.838 19248-19248/com.richluick.blocnotes D/FONTTYPE﹕ Impact
11-18 10:35:32.839 19248-19248/com.richluick.blocnotes D/ERROR﹕ NoteFragment{422972f8 id=0x7f090001}
11-18 10:35:32.840 19248-19248/com.richluick.blocnotes D/AndroidRuntime﹕ Shutting down VM
11-18 10:35:32.840 19248-19248/com.richluick.blocnotes W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4197dd40)
11-18 10:35:32.842 19248-19248/com.richluick.blocnotes E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.richluick.blocnotes, PID: 19248
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.richluick.blocnotes/com.richluick.blocnotes.BlocNotes}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5097)
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 com.richluick.blocnotes.NoteFragment.setCustomStyle(NoteFragment.java:86)
at com.richluick.blocnotes.BlocNotes.onStyleChange(BlocNotes.java:139)
at com.richluick.blocnotes.BlocNotes.onCreate(BlocNotes.java:61)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5097)
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)
NoteFragment.java
public class NoteFragment extends Fragment {
public EditText mEditText;
private Typeface mHelvetica;
private Typeface mHelveticaNeue;
private Typeface mImpact;
private static final String TEXT = "text";
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(TEXT, mEditText.getText().toString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_note, container, false);
setHasOptionsMenu(true);
//restore state of app when activity is destroyed and restarted
mEditText = (EditText) rootView.findViewById(R.id.editText);
if (savedInstanceState != null) {
mEditText.setText(savedInstanceState.getString(TEXT));
}
//Store the font assets as variables
mHelvetica = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Helvetica_Reg.ttf");
mHelveticaNeue = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeue_Lt.ttf");
mImpact = Typeface.createFromAsset(getActivity().getAssets(), "fonts/impact.ttf");
return rootView;
}
/**
* This is a setter method for setting the font the user has selected from the spinner
*
* param fontName the name of the font the user selected
* #return void
* */
public void setCustomFont(String fontName) {
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
/**
* This is a setter method for setting the font style the user has selected from custom menu
*
* param styleId the integer id of the font stlye selected (SMALL, MEDIUM, LARGE)
* #return void
* */
public void setCustomStyle(int styleId) {
if(styleId == 1) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
}
else if(styleId == 2) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
}
else if(styleId == 3) {
Log.d("EDITTEXT", String.valueOf(mEditText));
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.bloc_notes, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_erase) {
mEditText.setText("");
}
return super.onOptionsItemSelected(item);
}
}
In your SomeActivity.onCreate() you are creating an instance of NoteFragment, but even if you commit it via a transaction, it won't be inflated and created right away. Which basically means, the NoteFragment.onCreateView() was not executed and the fragments UI is not yet created. However, your Activity.onCreate() assumes, that mFragment.mEditText is already set, which is not the case, so you run into a NullPointerException.
Take a look at the FragmentTransation.commit method: http://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#commit()
Schedules a commit of this transaction. The commit does not happen immediately; it will
be scheduled as work on the main thread to be done the next time that thread is ready.
Your mEditText in your NoteFragment is null at this time, hence the NPE.
Just init your member mEditText in onCreate() or onActivityCreated() of the fragment, not onCreateView(). That should ensure that mEditText is not null when you call your setters.
Whatever happens, you should be protecting against a null mEditText in your setter functions.
EDIT this is what I meant:
public void setCustomFont(String fontName) {
if(mEditText != null){
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
}
EDIT 2: Oncreate will not be a good place. Basically you want to call your setter after the fragmentmanager has committed your change, so that mEditText has been initialized.
EDIT 3 - Try this with your initial code:
getFragmentManager().beginTransaction().replace(R.id.container, mNoteFragment).commit();
getFragmentManager().executePendingTransactions();
Okay so I am not sure why this works but I was able to figure out the anwer based on this question:
onCreateView() in Fragment is not called immediately, even after FragmentManager.executePendingTransactions()
I added the following line
getFragmentManager().executePendingTransactions();
and then moved everthing to the onStart method
#Override
protected void onStart() {
super.onStart();
//create a new note fragment if one has not been created yet
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.container);
if (mNoteFragment == null) {
mNoteFragment = new NoteFragment();
getFragmentManager().beginTransaction().replace(R.id.container, mNoteFragment).commit();
getFragmentManager().executePendingTransactions();
}
//restore SharedPreferences
SharedPreferences sharedPrefs = getPreferences(0);
int stylePref = sharedPrefs.getInt(SharedPreferanceConstants.PREF_FONT_SIZE, 2);
String fontPref = sharedPrefs.getString(SharedPreferanceConstants.PREF_TYPEFACE, "");
Log.d("STYLEID", String.valueOf(stylePref));
Log.d("FONTTYPE", fontPref);
onStyleChange(null , stylePref);
onFontChange(null, fontPref);
}
and for some reason it works fine now. If anyone could explain why that would be great
Try use 'apply' instead of 'commit' , the justification is here -> What's the difference between commit() and apply() in Shared Preference by Lukas Knuth.
But basically, apply() will commits its changes to the in-memory SharedPreferences immediately.
It's strong recommended use a class to manager your preferences, like 'MyPreferencesManager'.
I want to know why my application is throwing a runtime exception when I run it? I used to the code in the following link for my application,
dynamically add and remove view to viewpager.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab=getActionBar();
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById (R.id.pager);
pager.setAdapter (pagerAdapter);
inflater = (LayoutInflater)getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
pagerAdapter.addView (v0, 0);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
{
pagerAdapter.addView (v0);
pagerAdapter.notifyDataSetChanged();
}
}
LogCat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
the object on line 43 of your code within your onCreate method is null. Most likely the target of one of your findViewById calls is not returning what you expect it to.
See this for more info.
How to interpret Logcat
I am getting a NullPointerException when my code tries to access the value in a key/value pair created by onSaveInstanceState method of Activity class.
I set break points and I know for fact my Bundle is not null and it contains references to my key/values. I dont understand why I am getting this runtime error. Here are my codes for onSaveInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
int mPoints = winCount;
int hPoints = loseCount;
String reTextView = resultsTextView.getText().toString();
String pTextView = pointsTextView.getText().toString();
String roTextView = rollTextView.getText().toString();
outState.putInt("MY_POINTS", mPoints);
outState.putInt("HOUSE_POINTS", hPoints);
outState.putString("RESULTS", reTextView);
outState.putString("POINTS", pTextView);
outState.putString("ROLL", roTextView);
super.onSaveInstanceState(outState);
}
and here is my code to restore the state on the onCreate method
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(String.valueOf(savedInstanceState.getString("RESULTS")));
pointsTextView.setText(String.valueOf(savedInstanceState.getString("POINTS")));
rollTextView.setText(String.valueOf(savedInstanceState.getString("ROLL")));
}
I get the runtime error on line that starts with resultsTextView.setText... and here is contents of the savedInstanceState Bundle retrieved from break points in debug mode
Bundle[{RESULTS=Roll Again, MY_POINTS=2, POINTS=Your Point is 8,
HOUSE_POINTS=2,
android:viewHierarchyState=Bundle[{android:Panels=android.util.SparseArray#421c5560,
android:views=android.util.SparseArray#421c5358,
android:ActionBar=android.util.SparseArray#421c57f8}], ROLL=You Rolled
Easy Four}]
as you can see all my strings have a value, the interesting thing is that I dont get the NullPointerException runtime error on int variables (winCount and loseCount) but I am getting it at string values. I appreciate any help.
Update: here is the whole error log from log cat, I have resultsTextView.setText... at line 68 (within the else block on onCreat())
W/dalvikvm(27797): threadid=1: thread exiting with uncaught exception (group=0x418b6700)
E/AndroidRuntime(27797): FATAL EXCEPTION: main
E/AndroidRuntime(27797): java.lang.RuntimeException: Unable to start activity ComponentInfo{…}: java.lang.NullPointerException
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
E/AndroidRuntime(27797): at android.app.ActivityThread.access$700(ActivityThread.java:141)
E/AndroidRuntime(27797): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
E/AndroidRuntime(27797): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27797): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27797): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27797): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27797): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27797): at app.package.onCreate(AppName.java:68)
E/AndroidRuntime(27797): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime(27797): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime(27797): ... 12 more
here is my whole onCreate method, since many commentators requested to see the whole method. Hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
dealButton.setOnClickListener(dealButtonListener);
resetButton.setOnClickListener(resetButtonLinstener);
//on shake event
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
game(rollDice());
}
});
resultsTextView.setTextColor(Color.BLACK);
myPointsTextView.setText(String.format("%s", winCount));
housePointsTextView.setText(String.format("%s", loseCount));
}
You should initialize your TextViews before calling setText method. So onCreate should be like this:
setContentView(R.layout.activity);
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
...