Fatal exception while starting activity using intent (null pointer exception) - java

The following piece of code is throwing a null pointer exception in my application.Im trying to invoke an activity through an intent, (some background info on this is that the activity being opened is triggered through the click of a button, thus I have called the startActivity() function in the button's onclickListener itself.
Here's the code:
public class CategoryButtonOnClickListener extends Activity implements View.OnClickListener {
private final int position;
public CategoriesPage categoriesPage;
Context context;
public CategoryButtonOnClickListener(int position, Context contextPassed) {
this.position = position;
this.context = contextPassed;
categoriesPage = new CategoriesPage();
}
public void onClick(View v) {
callCategoryList(this.position);
}
public void callCategoryList(int position) {
String[] categories = categoriesPage.getCategories();
Intent categoriesList = new Intent(this.context,BooksWithCategories.class);
//I tried commenting this code to fix it as seen from another post, didnt work
//categoriesList.putExtra("Category:",categories[position]);
startActivity(categoriesList);
//Toast.makeText(context,categories[position],Toast.LENGTH_LONG).show();
}
}
The error thrown is as follows:
1-17 23:27:15.076 2614-2614/com.dogra.booker E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.dogra.booker, PID: 2614
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.callCategoryList(CategoryButtonOnClickListener.java:36)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.onClick(CategoryButtonOnClickListener.java:29)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any suggestions on what could be the problem are appreciated.

Place this method in your code :
Activity getAct() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
and then use it for starting the activity:
Intent categoriesList = new Intent(getAct(),BooksWithCategories.class);

can try this
Intent categoriesList = new Intent(CategoryButtonOnClickListener.this,BooksWithCategories.class);

Related

Android java.lang.NullPointerException error with BroadcastReceiver

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' 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:5256)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
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:5256) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

java.lang.NullPointerException: Attempt to invoke virtual method FloatingActionButton.setImageResource(int)' on a null object reference

I am trying to change the image of a floating action button when the app detects an in coming phone call. Here is the java class
public class PhoneCallReceiver extends BroadcastReceiver {
Main2Activity main2Activity;
#Override
public void onReceive(Context context, Intent intent) {
String state= intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
main2Activity=new Main2Activity();
main2Activity.pauseWorkout();
}
}
}
Inside the pauseWorkout method it contains a method call to another method that changes the image of the floating action button, and it is where the exception is pointing at. Here is the method:
public void showPlayButton() {
//CHANGING FLOATING ACTION BUTTON
startPauseFAB.setImageResource(R.drawable.play_white);
startPauseFAB.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.floating_action_button_color_play)));
startPauseFAB.setRippleColor(getResources().getColor(R.color.myGreen));
}
startPauseFAB.setImageResource(R.drawable.play_white); is where the problem is.
In the main2Activity the image changes from play to pause icons with no problem but when a call is ringing the app crushes. Here is how it is intitialized on onCreate:
startPauseFAB = (FloatingActionButton) findViewById(R.id.startAndPauseFAB);
And here is the xml for the floating action button:
<android.support.design.widget.FloatingActionButton
android:id="#+id/startAndPauseFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_margin="16dp"
android:src="#drawable/play_white"
app:backgroundTint="#color/floating_action_button_color_play"
app:borderWidth="0dp"
app:elevation="8dp"
app:fabSize="normal" />
I tried to use the debugging tool at startPauseFAB.setImageResource(R.drawable.play_white); it says there is no value.
here is the error message :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.leonk.workouttimerv1, PID: 13567
java.lang.RuntimeException: Unable to start receiver com.example.leonk.workouttimerv1.classes.PhoneCallReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setImageResource(int)' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2630)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1387)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
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:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setImageResource(int)' on a null object reference
at com.example.leonk.workouttimerv1.Main2Activity.setFABButton(Main2Activity.java:1308)
at com.example.leonk.workouttimerv1.classes.PhoneCallReceiver.onReceive(PhoneCallReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2623)
at android.app.ActivityThread.access$1700(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1387) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5268) 
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:902) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 
How can I solve this problem. I searched through similar questions but the solutions didn't help
In the phoneCallReceiver java class in the onReceive method I add the method call context.sendBroadCast with an intent as follows
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state= intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
context.sendBroadcast(new Intent("PHONE_RING"));
}
}
}
Then on the mainActivity create an object of the phoneCallReceiver class and override the onReceive method then call the activity method to change the image like :
PhoneCallReceiver phoneCallReceiver=new PhoneCallReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
pauseWorkout();
}
};
Then on onCreate register the receiver like so:
registerReceiver(phoneCallReceiver,new IntentFilter("PHONE_RING"));
Then destroy :
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(phoneCallReceiver);
}
Solution I got it here : Thanks everyone who commented you helped a lot
Blockquote

Android Studio Bluetooth :- attempt to invoke a virtual method on a null object reference

I am building a simple app which switches on the Bluetooth of a device and sets it to visible.
I have a separate java class file which has the Bluetooth functions I need, and these are called from another java class which is linked to my activity, through an object of the said class.
This is my code:
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
/**
* Created by mark on 11/11/2016.
*/
public class Bluetooth_API extends AppCompatActivity{
BluetoothAdapter blueAdp;
public Bluetooth_API() {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}
protected int bluetooth_ON() {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
//blueAdp.enable(); //instead of above line - without alert dialog for permission
return 0;
}
protected int bluetooth_OFF() {
blueAdp.disable(); //
return 0;
}
protected int bluetooth_setVisible() {
if(!blueAdp.isDiscovering()) {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);
}
return 0;
}
}
And this is the part of the code from the other activity which is calling my functions:
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent nextLayout = new Intent(getApplicationContext(), com.ai.mark.robot_dancing.Scanning_Devices.class);
startActivity(nextLayout);
blue.bluetooth_ON();
//blue.bluetooth_setVisible();
}
});
I am getting the error below once I run my code, I believe it has to do with the activity not being the right one since my Bluetooth functions are in another file (I also tried copying the methods to my activity class and they worked beautifully).
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ai.mark.robot_dancing, PID: 21314
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:3951)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77)
at android.app.Activity.startActivityForResult(Activity.java:3912)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.ai.mark.robot_dancing.Bluetooth_API.bluetooth_ON(Bluetooth_API.java:20)
at com.ai.mark.robot_dancing.Bluetooth_Panel$6.onClick(Bluetooth_Panel.java:146)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Any ideas on what is causing this?
Thanks.
Don't invoke such code in Activity constructor:
blueAdp = BluetoothAdapter.getDefaultAdapter();
Use onCreate(android.os.Bundle) for that:
#Override
protected void onCreate(Bundle savedInstanceState) {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}

Trying to reference a null-object reference?

so I've been working on a simple app that mutes and un-mutes the camera and yes, I know this app would be illegal in many countries, but! I'm willing to try. And anyway, disclaimers are there if things get rough.
While developing, I ran into this issue when trying to call out SharedPreferences. This is how my code is formulated right now.
MainActivity.java, initializes everything, and calls...
LegalProsecution.java, which tries to warn the user if the first_run is set..
AppPreferences.java handles giving first_run status to LP.java.
So, I've been having problems with AppPreferences.java. Here is the code:
package ideaman924.camerasilencer;
import android.content.Context;
import android.content.SharedPreferences;
public class AppPreference
{
SharedPreferences prefs;
public AppPreference(String buffer, Context context)
{
prefs = context.getSharedPreferences("ideaman924.camerasilencer.first_run", Context.MODE_PRIVATE);
}
public void storeSettings(String buffer, int num)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(buffer, num);
editor.apply();
}
public int loadSettings(String buffer)
{
return prefs.getInt(buffer,0);
}
}
This is the line that is giving me the ultimatum:
prefs = context.getSharedPreferences("ideaman924.camerasilencer.first_run", Context.MODE_PRIVATE);
Here is a crash log from logcat:
05-05 10:10:33.233 9099-9099/ideaman924.camerasilencer E/AndroidRuntime: FATAL EXCEPTION: main
Process: ideaman924.camerasilencer, PID: 9099
Theme: themes:{}
java.lang.RuntimeException: Unable to start activity ComponentInfo{ideaman924.camerasilencer/ideaman924.camerasilencer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
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.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at ideaman924.camerasilencer.AppPreference.<init>(AppPreference.java:12)
at ideaman924.camerasilencer.LegalProsecution.<init>(LegalProsecution.java:11)
at ideaman924.camerasilencer.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5458) 
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) 
From my guesses, SharedPreferences prefs churns out a null object, and I'm trying to reference that. But why? Why would it be a null object? And also, I'm trying to initialize the prefs, not reference it!
Any help would be appreciated.
EDIT1: Seems like error is in LegalProsecution.java, as mentioned by cricket_007:
package ideaman924.camerasilencer;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
public class LegalProsecution
{
private Context context;
public LegalProsecution(Context context)
{
this.context = context;
}
AppPreference appprefs = new AppPreference("settings",this.context);
public void warningShow()
{
if(appprefs.loadSettings("first_run") != 1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(context.getResources().getString(R.string.warning));
builder1.setMessage(context.getResources().getString(R.string.warning_description));
builder1.setCancelable(true);
builder1.setPositiveButton(
context.getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Got promise from user, now setting first_run to 1
appprefs.storeSettings("first_run", 1);
dialog.cancel();
}
}
);
builder1.setNegativeButton(
context.getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Okay, cool, bye! No CS for you!
dialog.cancel();
((Activity) context).finish();
System.exit(0);
}
}
);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
Any problems?
Rewrite like so
AppPreference appprefs;
public LegalProsecution(Context context)
{
this.context = context;
this.appprefs = new AppPreference("settings", context);
}
Because this.context will be null until the constructor is called.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am trying to save player's name in shared preference and make it display in another activity by getting it again in shared preference but my app crash.
FATAL EXCEPTION: main
Process: plp.cs4b.thesis.drawitapp, PID: 1970
java.lang.RuntimeException: Unable to start activity ComponentInfo{plp.cs4b.thesis.drawitapp/plp.cs4b.thesis.drawitapp.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at plp.cs4b.thesis.drawitapp.PlayGame.onCreate(PlayGame.java:20)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Codes:
Player.java
public class Player {
private Context context;
private SharedPreferences prefSettingsU;
private SharedPreferences.Editor prefEditorU;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String MY_UNIQUE_PREF_FILE = "DrawItApp";
public Player(Context context, String name) {
this.context = context;
saveName(name);
}
public void saveName(String n) {
prefSettingsU = context.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
prefEditorU = prefSettingsU.edit();
prefEditorU.putString("keyName", n);
prefEditorU.commit();
}
public String getName(Context ctx) {
prefSettingsU = ctx.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
String name = prefSettingsU.getString("keyName", "ANONYMOUS");
return name;
}
PlayGame.java
public class PlayGame extends Activity {
private TextView welcomePlayer;
private ListView createdGames;
private Player mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
welcomePlayer = (TextView) findViewById (R.id.tvPlayerName);
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
createdGames = (ListView) findViewById (R.id.listCreatedGames);
// adapter etc
createdGames.setEmptyView(findViewById (R.id.tvNoGames));
}
PlayerName.java
public class PlayerName extends Activity {
private EditText playerName;
private Player mPlayer;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
context = this;
playerName = (EditText) findViewById (R.id.etName);
}
public void onC_Confirm(View btnclick) {
mPlayer = new Player(context, String.valueOf(playerName.getText()));
//mPlayer.saveName();
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}
public void onC_testShPref(View btnclick) {
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}
Your app is crashing at:
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
because mPlayer=null.
You forgot to initialize Player mPlayer in your PlayGame Activity.
mPlayer = new Player(context,"");

Categories

Resources