I added a String to the MainActivity.java file and now my app crashes as soon as I launch it (at the moment the debugger reaches the line of code with the String).
This is the line of code that creates the problem :
CharSequence Total = "Total:"; // getString(R.string.total);
it also creates the problem if I use String instead of CharSequence.
When I delete that line the app works perfectly.
This is the error I get in the Gradle console :
Note : /Users/ishayfrenkel1/AndroidStudioProjects/JustJava/app/src/main/java/com/howtoevery/justjava/MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
What does it mean that the app uses or overrides a deprecated API?
And how can I Recompile with -Xlint:deprecation in Android Studio? What does it even mean?
The MainActivity.java code:
package com.howtoevery.justjava;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends ActionBarActivity {
CharSequence totalString = "Total:"; // getString(R.string.total);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
CharSequence toastText;
// String total = getString(R.string.total);
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number, CharSequence message) { // Used to be , String message
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(message + " " + NumberFormat.getCurrencyInstance().format(number)); // was message before Number Format
}
public void addOne(View view) {
num++;
display(num);
displayPrice(num*5, totalString); //used to have total
}
public void removeOne(View view) {
if (num > 0) {
num--;
display(num);
displayPrice(num * 5, totalString); //used to have total
}
else {
Context context = getApplicationContext();
toastText = getString(R.string.negativeCups);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
public void reset(View view) {
if (num > 0) {
num = 0;
display(num);
displayPrice(num, totalString); //used to have total
}
else {
toastText = getString(R.string.resetted);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
public void submitOrder(View view) {
displayToast(num);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayToast(int number) {
Context context = getApplicationContext();
if (number > 0) {
toastText = getString(R.string.ordering) + num + getString(R.string.ordering_cups_price) + NumberFormat.getCurrencyInstance().format(num*5);
}
else
toastText = getString(R.string.empty_order);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
This is what I get from the logcat:
06-07 13:39:06.275 22308-22308/com.howtoevery.justjava I/art﹕ Late-enabling -Xcheck:jni
06-07 13:39:06.391 22308-22308/com.howtoevery.justjava D/AndroidRuntime﹕ Shutting down VM
06-07 13:39:06.392 22308-22308/com.howtoevery.justjava E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.howtoevery.justjava, PID: 22308
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.howtoevery.justjava/com.howtoevery.justjava.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5274)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.howtoevery.justjava.MainActivity.<init>(MainActivity.java:16)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5274)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
06-07 13:39:08.374 22308-22318/com.howtoevery.justjava W/art﹕ Suspending all threads took: 8.600ms
You have a problem with your context. getApplicationContext() should be moved inside the onCreate() method. Do this
public class MainActivity extends ActionBarActivity {
CharSequence totalString = "Total:"; // getString(R.string.total);
Context context;
int duration = Toast.LENGTH_SHORT;
CharSequence toastText;
// String total = getString(R.string.total);
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
}
...
Class members initialization that takes place outside constructors/instance methods cannot use non static methods that require functional object instances, because at that point your object instance is not yet fully created. You have to move such initializations inside constructor, or instance method that you will either call from constructor or from your object reference.
You have to move initialization calls to getString(R.string.total), and getApplicationContext() to OnCreate method.
public class MainActivity extends ActionBarActivity {
String totalString;
Context context;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalString = getString(R.string.total);
context = getApplicationContext();
}
In your code, you actually don't have to grab application context at all, because you can use activity context to show your toast messages. Just refer to current activity reference with this
Toast toast = Toast.makeText(this, toastText, duration);
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to enter details from EnterDetails class and view saved details in MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameBox ;
EditText sclBox;
Spinner genderMenu;
EditText ageBox;
SharedPreferences sharedPref;
TextView label ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameBox = findViewById(R.id.editText);
sclBox = findViewById(R.id.editText3);
ageBox = findViewById(R.id.editText2);
genderMenu = findViewById(R.id.spinner);
sharedPref = getSharedPreferences("mypref",Context.MODE_PRIVATE);
label = findViewById(R.id.textView);
if(isDetailsEmpty(0)){
label.setText("Enter new Details");
}else{
setDetails();
}
}
public boolean isDetailsEmpty(int i){
if(i ==0) {
if (sharedPref.getString("txtName", "").isEmpty() || sharedPref.getString("txtAge", "").isEmpty() || sharedPref.getString("txtScl", "").isEmpty()) {
return true;
} else {
return false;
}
}{
if(nameBox.getText().toString().isEmpty() || ageBox.getText().toString().isEmpty() || sclBox.getText().toString().isEmpty()){
return true;
}else{
return false;
}
}
}
public void setDetails(){
label.setText("Name : " +sharedPref.getString("txtName","Default")+"\n"+
"Age : " +sharedPref.getString("txtAge","Default")+"\n"+
"Gender : " +sharedPref.getString("optGender","Default")+"\n"+
"School : " +sharedPref.getString("txtScl","Default")+"\n");
}
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
startActivity(enterDet);
}
}
`public class EnterDetails extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
}
public void onClickSave(View v){
if(isDetailsEmpty(1)) {
Toast.makeText(EnterDetails.this,"Empty Details!", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("txtName", nameBox.getText().toString());
editor.putString("txtAge", ageBox.getText().toString());
editor.putString("optGender", genderMenu.getSelectedItem().toString());
editor.putString("txtScl", sclBox.getText().toString());
editor.commit();
Toast.makeText(EnterDetails.this,"Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this,MainActivity.class));
}
}
}
`
I want to enter details from EnterDetails class and view saved details in MainActivity. But I get the folloing error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.userdetails, PID: 31945
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.userdetails.MainActivity.isDetailsEmpty(MainActivity.java:64)
at com.example.userdetails.EnterDetails.onClickSave(EnterDetails.java:20)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
How to fix this? I have already extended EnterDetails to MainActivity.
Similar Question : What is a NullPointerException, and how do I fix it?
What you are doing is wrong. EnterDetails has its own layout called R.layout. enter_details, so when you set setContentView(R.layout.enter_details);, it will override the whole content so all views and layouts in MainActivity is no longer accessible. What you need to do is implement EnterDetails normally and use Intent to send data between activities.
public class EnterDetails extends AppCompatActivity {
private boolean isDetailsEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
isDetailsEmpty = getIntent().getBooleanExtra("test1", false)
}
public void onClickSave(View v){
if(isDetailsEmpty) {
...
}
}
And pass data from your MainActivity
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
enterDet.putExtra("test1", isDetailsEmpty(1))
startActivity(enterDet);
}
Finally, please do more research on how Activity works https://medium.com/#peterekeneeze/passing-data-between-activities-2d0ef122f19d
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();
}
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.
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)
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,"");