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

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.

Related

I have a problem when I try to use a variable from a getStringArrayListExtra()

When I use getStringArrayListExtra() to transport a variable from SecondActivity to the MainActivity, and when I use the variable, my app always crash. This is the code where there is a problem :
in MainActivity :
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}
}
in SecondActivity :
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
ArrayList tag = new ArrayList();
EditText edit;
Button button;
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
tag.add(name);
Toast.makeText(getApplicationContext(), tag.toString(), Toast.LENGTH_SHORT).show();
}
});
Button button2;
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
Button button3;
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
startActivity(retourgameActivity);
}
});
}
}
Thank you so much for your help !
EDIT:
This is the error log (logcat):
021-06-24 15:43:16.734 11451-11451/fr.apprentissage.version2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.apprentissage.version2, PID: 11451
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.apprentissage.version2/fr.apprentissage.version2.MainActivity}: 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:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at fr.apprentissage.version2.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
You are starting MainActivity from SecondActivity without any extras.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
//add arraylist here in intent
retourgameActivity .putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
}
});
//in your second activity ,make sure you have extras in intent.
if(getIntent!=null && getIntent().getStringArrayListExtra("tag")!=null){
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}}
You are initiating an arraylist and before populating list you are sending it to your MainActivity.So you are passing null list to MainActivity. You should pass your list to other activity on button click.
Just do this inside your button3 listener:
Intent retourgameActivity = new Intent(MainActivity.this, SecondActivity.class);
retourgameActivity.putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
Remove
retourgameActivity.putStringArrayListExtra("tag", tag);
from here
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
Good Practices:
Always put null check before sending arraylist to other activity and also check null before using arraylist.size() or getting some indexes of arralist.

Trying to seperate OnClickListener() to another class

I'm trying to create an onClickListener for another class, but there's a NullPointerException. I already tried to pass the value of context, but still, it didn't work. I don't know what value is null.
This is the class for ExternalOnClickListener
public class ExternalOnClickListener implements View.OnClickListener{
private Context context;
public ExternalOnClickListener(Context c) {
context = c;
}
public void setRowCol(Intent hardLevelIntent) {
hardLevelIntent.putExtra("rowCount", 6);
hardLevelIntent.putExtra("colCount", 6);
hardLevelIntent.putExtra("difficulty", 3);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View v) {
//Hard levels intent
Intent hardLevelIntent = new Intent(context, GameActivity.class);
setRowCol(hardLevelIntent);
switch (v.getId()) {
case R.id.btnBack:
Intent intent = new Intent(context, Level_Selection.class);
context.startActivity(intent);
break;
case R.id.btnHard1:
hardLevelIntent.putExtra("hardStageCount", 1);
context.startActivity(hardLevelIntent);
break;
}
}
}
And the btnEndless.onClickListener() here is trying to create an object for the external onClick. But there's a null pointer exception
public class Level_Selection extends AppCompatActivity {
ImageButton btnBack, btnEasy, btnAverage, btnHard, btnEndless;
ImageButton btnHard1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level__selection);
this.btnBack = findViewById(R.id.btnBack);
this.btnEasy = findViewById(R.id.btnEasy);
this.btnAverage = findViewById(R.id.btnAverage);
this.btnHard = findViewById(R.id.btnHard);
this.btnEndless = findViewById(R.id.btnEndless);
this.btnHard1 = findViewById(R.id.btnHard1);
btnBack.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Menu.class);
startActivity(intent);
});
btnEasy.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Easy.class);
startActivity(intent);
});
btnAverage.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Average.class);
startActivity(intent);
});
btnHard.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Hard.class);
startActivity(intent);
});
btnEndless.setOnClickListener(v -> {
btnHard1.setOnClickListener(new ExternalOnClickListener(getApplicationContext()));
btnHard1.performClick();
});
}
This is the error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flip, PID: 10862
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.flip.Level_Selection.lambda$onCreate$4$Level_Selection(Level_Selection.java:59)
at com.flip.-$$Lambda$Level_Selection$EhORL8AmJ4WhZjndwpPfbUXg1uA.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:6312)
at android.view.View$PerformClick.run(View.java:24811)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
I hope someone answers my question. Thanks in advance!
Try check btnHard1 value, is it null?
Make sure there is ImageButton with id 'btnHard1' in your activity_level__selection layout.
Seems like your R.layout.activity_level__selection, doesn't containt of button which you set click listener or has different id

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.

TWO ways data binding between activities

I've 2 activities, and need the main Activity to send some data to the second Activity then the second activity analyze this data and send response back, so I've the below 2 codes:
Main Activity:
import static tk.zillion.mobile.SecondActivity.EXTRA_STUFF;
public class MainActivity extends Activity {
private static int PICK_CONTACT_REQUEST = 0;
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
finish();
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(EXTRA_STUFF);
// set text view with string
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
}
}
}
and the Second Activity is as below:
public class SecondActivity extends Activity {
static final String EXTRA_STUFF = "tk.zillion.mobile.EXTRA_STUFF";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
String s = getIntent().getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(this, "I'm the second activity " + s , Toast.LENGTH_SHORT).show();
Bundle basket =new Bundle();
basket.putString(EXTRA_STUFF, s);
intent.putExtras(basket);
setResult(RESULT_OK, intent);
finish();
}
}
The second activity is fired correctly, and receive the data from the main one, but once the data is sent back the onActivityResult is not fired!!
How can I solve it? thanks
Remove the finish() call that comes after startActivityForResult(). You prevent the oncoming activity to give a result back, because you remove your MainActivity with finish() from the back task.
Dont call finish() after startActivityForResult otherwise that instance of MainActivity that started the second one will be destroyed

Child Activity Not receiving data?

I am learning android, so I was practising with a program in which I start a new activity with a button and then what ever text was input by the user in the edittext of the previous activity has to displayed in textview of the new started activity but when I pass the user input to the new activity, it doesn't display anything. What can be the problem here is the code:
Lets say this parent activity:
case R.id.Sfr:
Intent data= new Intent(SendData.this, RecieveData.class);
Bundle check = new Bundle();
check.putString("UmerData", cheese);
medt.setText(cheese);
data.putExtras(check);
startActivityForResult(data, 5); // It is used to return data from child activity
break;
The child activity which should show the user input passed to it is:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recievedata);
Initialize();
Bundle got = getIntent().getExtras();
rt1.setText(got.getString("UmerData"));
}
Why is this child activity not showing userinput which has been passed to it?
Try this -
case R.id.Sfr:
Intent data= new Intent(SendData.this, RecieveData.class);
Bundle check = new Bundle();
check.putString("UmerData", cheese);
medt.setText(cheese);
data.putExtras(check);
startActivity(data);
break;
The child activity which should show the user input passed to it is:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recievedata);
InitializeFuck();
Bundle got = getIntent().getExtras();
rt1.setText(got.getString("UmerData"));
}
Have a look at these existing answers -
Passing Data between activities
How to pass the Data between Activities
write in first activity:-
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putStringExtra("keyForData", Value);
startActivity(intent);
write code in second Activity:-
Intent intent = Activity2.this.getIntent();
String data =intent.getStringExtra("KeyForData");
1. Use Intent along with putExtra() for sending data to the Another Activity.
Eg:
Intent i = new Intent(Your_Class.this, Desired_Class.class);
i.putExtra("NameKey","name");
startActivity(i);
2. Now use getIntent() on the receiving Activity to get the Starting Intent and then use
getExtras() and getString() to get the String value associated with the key. We have getInt() etc too..
Eg:
Intent intent = getIntent();
String name = intent.getExtras().getString("NameKey");

Categories

Resources