Transporting doubles from one into another activity - java

I am trying to transport variables that I get through an EditText into the next activity. At first, I tried it with just one variable and it worked fine. But once I added the second activity, the app started to crash
once I tried it out. The app crashes when I try to press the button to get to the second activity.
Maybe you can find the mistake?
Following is my code.
First Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button weiter = (Button) findViewById(R.id.weiter1);
weiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText inputHeight = (EditText) findViewById(R.id.inputheight);
EditText inputlenght = (EditText) findViewById(R.id.inputlenght);
Double height = Double.parseDouble(inputHeight.getText().toString());
String Höhe = new Double(height).toString();
Double lenght = Double.parseDouble(inputlenght.getText().toString());
String Länge = new Double(lenght).toString();
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("HöheName", Höhe);
i.putExtra( "LängeName", Länge);
startActivity(i);
}
});
}
Second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
String Länge = intent.getExtras().getString( "längeName");
double höhe = Double.valueOf(Höhe);
double länge = Double.valueOf(Länge);
double längemalhöhe = höhe + länge;
String ergebnis = new Double(längemalhöhe).toString();
TextView Test = (TextView) findViewById(R.id.Test);
Test.setText(ergebnis);
Button weiter = (Button) findViewById(R.id.weiter2);
weiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
Intent i = new Intent(getApplicationContext(), Main3Activity.class);
i.putExtra("HöheName", Höhe);
startActivity(i);
}
});
}
Third Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
TextView Test = (TextView) findViewById(R.id.Ergebnis2);
Test.setText(Höhe);
}
Here is the Logcat:
12-27 23:02:42.760 30997-30997/com.example.june.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.june.test, PID: 30997
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.june.test/com.example.june.test.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at java.lang.StringToReal.parseDouble(StringToReal.java:263)
at java.lang.Double.parseDouble(Double.java:301)
at java.lang.Double.valueOf(Double.java:338)
at com.example.june.test.Main2Activity.onCreate(Main2Activity.java:22)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) 
at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7331) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I don't know if it's just a typo, but you have the line: String Länge = intent.getExtras().getString( "längeName"); where "längeName" is not capital, however, you initially did this: i.putExtra( "LängeName", Länge); where "LängeName" is capital. So the problem might be that the two strings aren't the same. When you try to do the following:
String Länge = intent.getExtras().getString( "längeName");
The string is initialized to null because there is no value assign to "längeName", which can then lead to a NullPointerException if the string is attempted to be used.

From the logcat, I see it says java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim() so your app crashes because a you are trying to use a String that is null. You need to check if the Strings you are working with are not null it avoid these crashes.

Notice:
i.putExtra( "LängeName", Länge);
...
String Länge = intent.getExtras().getString( "längeName");
LängeName and längeName are different two keys.

To avoid the simple mistake pointed out by LAD, it is a good practice to store the string with a final modifier.
First Activity
final static String HOHE_NAME = "HöheName";
final static String LANGE_NAME = "LängeName";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//....
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra(HOHE_NAME, Höhe);
i.putExtra(LANGE_NAME, Länge);
startActivity(i);
}
Second Activity
Intent intent = getIntent();
String Höhe = intent.getExtras().getString(MainActivity.HOHE_NAME);
String Länge = intent.getExtras().getString(MainActivity.LANGE_NAME);

Related

Pass String (or Array) to ListView in another Activity (NPE error)

I would like to have the working ListView from the MainActivity in the ExpAct (2.Activity).
What I have: Edittext and a Button that creates a new entry to a Listview upon clicking.
The ListView on MainAct is just for checking and will be deleted if ExpAct works.
Upon clicking the "next"Btn I get to ExpAct.
I get a raw use parameter warning. -- And if I were to fix that, it gives me an NPE-crash for the ExpAct, or an empty ListView.
Is the issue that the getter Intent for the String/Array doesnt work? Or does it lie with the creation of the ArrayAdapter?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView LV1;
ArrayList < String > listExp;
Button button1, btnext;
EditText ETbc;
ArrayAdapter < String > arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LV1 = findViewById(R.id.LV1);
button1 = findViewById(R.id.button1);
ETbc = findViewById(R.id.ETbc);
listExp = new ArrayList < String > ();
arrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1, listExp);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String names = ETbc.getText().toString();
listExp.add(names);
LV1.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
Intent inter = new Intent(MainActivity.this, ExpAct.class);
inter.putExtra("key", listExp);
setResult(Activity.RESULT_OK, inter);
}
});
btnext = findViewById(R.id.btnext);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ExpAct.class);
startActivity(intent);
finish();
}
});
}
}
*ExpAct.java: *
public class ExpAct extends MainActivity {
ListView LV2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exp);
Intent i = getIntent();
listExp = i.getStringArrayListExtra("key");
LV2 = findViewById(R.id.LV2);
ArrayAdapter arrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1, R.id.LV2, listExp); // here without R.id.LV2
LV2.setAdapter(arrayAdapter);
}
}
Logs since it has become red.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testcheckbox, PID: 20358
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testcheckbox/com.example.testcheckbox.ExpAct}.
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6255)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:510)
at com.example.testcheckbox.ExpAct.onCreate(ExpAct.java:27)
at android.app.Activity.performCreate(Activity.java:6670)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6255) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
Disconnected from the target VM, address: 'localhost:57662', transport: 'socket'
It looks like you're trying to start the activity without putting the ArrayList as an extra.
btnext = findViewById(R.id.btnext);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ExpAct.class);
// You need to put the extra data here:
intent.putExtra("key", listExp);
startActivity(intent);
finish();
}
});
When you get a NullPointerException, you should first check why would the list be null:
Attempt to invoke interface method 'int java.util.List.size()' on a
null object reference
So after looking at your code, I saw that you're not passing the ArrayList with the intent.

Arithmetic Android app crashes, no errors in the code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1388) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:10‌​4)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}

Failure delivering result ResultInfo{who=null, request=42, result=0, data=null} to activity

Please help! When I run my program everything works fine when I go to the second activity, but when I go back to the first it comes up with an error. Here is the full error message:
Process: com.example.android.lifeofcrime, PID: 2826
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=42, result=0, data=null} to activity {com.example.android.lifeofcrime/com.example.android.lifeofcrime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at com.example.android.lifeofcrime.MainActivity.onActivityResult(MainActivity.java:63)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Here is the code for the first activity:
public class MainActivity extends AppCompatActivity {
int test = 5;
TextView money;
int testReturn2 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
money = (TextView) findViewById (R.id.money);
setupWorkButton();
}
public void setupWorkButton() {
Button workButton = (Button) findViewById(R.id.workButton);
workButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, workScreen.class);
intent.putExtra("testing", test);
startActivityForResult(intent, 42);
}
});
}
// Gets called when the activity started finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-Generate method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 42:
testReturn2 = data.getIntExtra("the answer", 0);
money.setText("" + testReturn2);
break;
}
}
}
And here is the code for the second activity:
public class workScreen extends AppCompatActivity {
int test;
int testReturn = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_screen);
Intent intent = getIntent();
test = intent.getIntExtra("testing", 0);
TextView displayTest = (TextView) findViewById(R.id.intView);
displayTest.setText("" + test);
setupCharacterButton();
}
public void setupCharacterButton() {
Button characterButton = (Button) findViewById(R.id.characterButton);
characterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
testReturn = test * 2;
intent.putExtra("the answer", testReturn);
finish();
}
});
}
}
Your intent == null. Seems like you forgot to set the activity result in your second activity:
setResult(Activity.RESULT_OK, intent);
put this code before you finish the 2nd Activity

How to display passed intent data in a TextView - NullPointerException error

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)

App crashes on Button Press stating "Attempt to invoke virtual method"

I have an android application which should opens an activity on button press, but when i click on itm the app crashes stating "Attempt to invoke virtual method". Here is my Code.
MainClass.java
public class MainActivity extends ActionBarActivity {
Button Notify;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Notify = (Button)findViewById(R.id.notify);
Notify.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, DisplayPush.class);
startActivity(intent);
}
});
}
My another activity class
DisplayPush.java
public class DisplayPush extends Activity {
#Override
public void onBackPressed(){
Intent myIntent = new Intent(DisplayPush.this,MainActivity.class);
startActivity(myIntent);
// overridePendingTransition(R.anim.from_middle, R.anim.to_middle);
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
TextView notification_title = (TextView) findViewById(R.id.title);
TextView notification_message = (TextView) findViewById(R.id.message);
ParseAnalytics.trackAppOpened(getIntent());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String jsonData = extras.getString("com.parse.Data");
try{
JSONObject notification = new JSONObject(jsonData);
// String title = notification.getString("push_hash");
String message = notification.getString("alert");
// notification_title.setText(title);
notification_message.setText(message);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Something went wrong with the notification", Toast.LENGTH_SHORT).show();
}
}
I have defined the acitivities in my manifest.
Here is the logcat.
03-21 06:51:35.157: E/AndroidRuntime(3042): FATAL EXCEPTION: main
03-21 06:51:35.157: E/AndroidRuntime(3042): Process: hasan.parsereceiveandshow, PID: 3042
03-21 06:51:35.157: E/AndroidRuntime(3042): java.lang.RuntimeException: Unable to start activity ComponentInfo{hasan.parsereceiveandshow/hasan.parsereceiveandshow.DisplayPush}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
As in log:
Bundle.getString(java.lang.String)' on a null object reference
Because extras is null.
Not sending Bundle which contain com.parse.Data key with Intent which is used for starting DisplayPush Activity on Button Click.
What should i edit in code ?
Send data with com.parse.Data key in Intent on Notify Button click:
Intent intent = new Intent(MainActivity.this, DisplayPush.class);
intent.putExtra("com.parse.Data","String text");
startActivity(intent);
And also add null check before getting values from Bundle:
if(extras !=null)
if(extras.containsKey("com.parse.Data"))
String jsonData = extras.getString("com.parse.Data");
And define String jsonData; globally as said in comments.
The exception says that you're trying to call getString method on null reference. In DisplayPush you are getting Bundle object from intent which is null, because you didn't put any in your intent in onClick method in MainActivity class.

Categories

Resources