Error when trying to get a bundle from another activity [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
The part of the code where I try to retrieve and show the bundle is this:
Bundle bundlefrankrijk = getIntent().getExtras();
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");
TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);
SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);
if (scorefrankrijk > highScorefrankrijk) {
highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);
SharedPreferences.Editor editor = settingsfrankrijk.edit();
editor.putInt("HIGH_SCORE", scorefrankrijk);
editor.commit();
} else {
highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
}
This is how I'm sending the intent to the current activity:
Intent i = new Intent(QuizActivityFrankrijk.this,
QuizResultaatFrankrijk.class);
Bundle bundlefrankrijk = new Bundle(0);
bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
i.putExtras(bundlefrankrijk);
QuizActivityFrankrijk.this.finish();
startActivity(i);
Thanks in advance!

Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:
Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object
And when youre trying to:
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed
Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:
mIntent.putExtra("key", intValue)
and check that youre receiving it like this:
if (getIntent().getExtras() != null){
getIntent().getExtras().getInt("key");}
or just like this too:
if (getIntent().getExtras() != null){
getIntent().getExtras().get("key");}
Remember, if the key is just different in some character, it will return NULL.
Please read this for more info: https://developer.android.com/reference/android/content/Intent.html

Related

How to pass an integer from one activity to another in android application [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 2 years ago.
I am trying to learn android and i don't know how to pass data from one activity to another
public void onNextClick(View view){
Intent intent = new Intent(this,Expenses.class);
intent.putExtra(EXTRA_SUM, sum);
startActivity(intent);
editSalary = (EditText) findViewById(R.id.salayText);
editIncome = (EditText) findViewById(R.id.incomeText);
salary = Integer.parseInt(editSalary.getText().toString());
income = Integer.parseInt(editIncome.getText().toString());
sum = salary + income;
}
public void onNextClick2(View view){
Intent intent2 = new Intent(Expenses.this,Budget.class);
intent2.putExtra(EXTRA_EXPENSE, expense);
startActivity(intent2);
editRent = (EditText) findViewById(R.id.rentText);
editBills = (EditText) findViewById(R.id.billsText);
editEveryday = (EditText) findViewById(R.id.everydayText);
editOther = (EditText) findViewById(R.id.otherText);
rent = Integer.parseInt(editRent.getText().toString());
bills = Integer.parseInt(editRent.getText().toString());
everyday = Integer.parseInt(editEveryday.getText().toString());
other = Integer.parseInt(editOther.getText().toString());
expense = rent + bills + everyday + other;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budget);
Intent intent = getIntent();
summary = intent.getIntExtra(MainActivity.EXTRA_SUM ,0);
expenses = intent.getIntExtra(Expenses.EXTRA_EXPENSE, 0);
totalBudget = summary - expenses;
textBudget = (TextView) findViewById(R.id.budgetView);
textBudget.setText(String.valueOf(totalBudget));
}
I am trying to get "sum" from activity 1 and "expenses" from activity 2 and subtract them in activity 3 but i keep getting null
You can't pass a value from first activity to third activity directly.First you have to pass it to first-> second then second-> third.
Else there is a simple solution like you can store it on Shared Preferences
Store sum value on shared preferences while moving from first activity to second activity.Then store the expenses value on shared preferences when you move from second to third activity.After that in onCreate method of third activity you can get the both values and subtract.
There are many ways to do this.
View Model
Singleton
Pass it in the Intent that launched the new active

Android: NullPointerException: Attempt to invoke virtual method 'boolean [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am getting the following error:
*E/AndroidRuntime: FATAL EXCEPTION: main
Process: xxx.mxxxa.xxx, PID: 10610
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference*
on the following lines:
public void onLoadResource (WebView view, String url) {
if (datingView.getUrl().contains("messages.php") && datingView.getUrl().contains("messages.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("upgrade.php") && datingView.getUrl().contains("upgrade.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("index.php") && datingView.getUrl().contains("index.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("join.php") && datingView.getUrl().contains("join.php" +
"") ){
bannerReklam.setVisibility(View.GONE);
}else{
bannerReklam.setVisibility(View.VISIBLE);
}
// if url contains string androidexample
// Then show progress Dialog
if (progressDialog == null && url.contains("instasquare")
) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(arkadasBulMain.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
This problem causes the application to stop. This error occurs for versions below android 9.0.
In some cases datingView.getUrl() return null. First try to check null and then try to search item using contains. For Example:
String datingUrl = datingView.getUrl();
if(datingUrl != null && datingUrl.contains("messages.php"))

Problems trying to save data to SQlite [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Since this is my second app, and my first app was 99% designing, this could be a duplicate because i might not be using the proper keywords for my searches, but i'm searching for 3 hours now for the solution, which is probably very simple, and i can't seem to find it.
When I try to save information to my database with 2 TextViews, 1 Spinner, and a Button, i get this error message:
FATAL EXCEPTION: main
Process: nl.pluuk.gelduren, PID: 29876
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at nl.pluuk.gelduren.Add_client.saveData(Add_client.java:76)
at nl.pluuk.gelduren.Add_client$3.onClick(Add_client.java:67)
at android.view.View.performClick(View.java:5233)
at android.view.View$PerformClick.run(View.java:21209)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
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)
This is my code which i'm currently using to not save any data
public void save(){
save = (Button)findViewById(R.id.button_save_client);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Save Button Clicked");
Client_textView = (TextView)findViewById(R.id.inputform_client_name);
Rate_textView = (TextView)findViewById(R.id.inputform_rate);
Pay_Period_textView = (Spinner)findViewById(R.id.spinner_pay_period);
Client = "" + Client_textView.getText();
Rate = Integer.parseInt("" + Rate_textView.getText());
Pay_Period = "" + Pay_Period_textView.getSelectedItem();
saveData();
}
});
}
public void saveData(){
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CLIENT_NAME, Client);
System.out.println("Yes, i'm in your log");
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_RATE, Rate);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_PAY_PERIOD, Pay_Period);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
null,
values);
}
This code is all inside Add_client.
The error Add_client.java:76 is referring to the line: SQLiteDatabase db = mDbHelper.getWritableDatabase();
The error Add_client.java:67 is referring to the line: saveData();
Which is probably caused by line 76.
I made sure that there are columns inside the database, by executing System.out.println("Column count:" + c.getColumnCount());
This told me that there where 3 columns, which is what I was expecting.
I also checked if there was any data inside the columns with:
Boolean rowExists;
if (c.moveToFirst())
{
System.out.println(c.getColumnName(0));
rowExists = true;
} else
{
System.out.println("Nothing to see here");
rowExists = false;
}
This gave me the output: Nothing to see here, which is was also expecting because the database starts empty.
Where is the mistake in my code which keeps smashing me these errors?
Is there is any other information needed, I will be happily include it in an edit.
It seems like the context you passed into your SQliteOpenHelper, in this case, mDBHelper, is null.

NullPointerException in IabHelper.queryPurchases

Today I discovered an application crash report for my Android app involving the following stack trace:
java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getPurchases(int, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.myapp.utils.IabHelper.queryPurchases(IabHelper.java:878)
at com.myapp.utils.IabHelper.queryInventory(IabHelper.java:572)
at com.myapp.utils.IabHelper.queryInventory(IabHelper.java:545)
at com.myapp.utils.IabHelper$2.run(IabHelper.java:645)
at java.lang.Thread.run(Thread.java:818)
(line numbers are changed from the original -or what looks like to be the original, because of custom reformatting)
Normally, one would modify his own code to check for unassigned class members. The problem is that this code is copied&pasted right from Android SDK, because IabHelper is a class that Android SDK provides as a good starting point for implementing In-app Billing v3
The guilty line is the second
logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
It seems that the service is not connected at the time the method is invoked. This error occurred on a Nexus 5 device (as per Developer Console)
Is this a known problem with Android 5?
Is there an up-to-date version of the IAB Helper?
What can I do rather than manually editing the code to handle NPE someway?
I modified this code ...
do {
logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
// ...
}
To be this ...
do {
logDebug("Calling getPurchases with continuation token: " + continueToken);
if (mService == null || mContext == null) {
logError("Our service and/or our context are null. Exiting.");
return IABHELPER_UNKNOWN_ERROR;
}
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
// ...
}
This is almost certainly because the process is being run asynchronously and the activity/app has (or is being) closed when the result returns.

java.lang.NullPointerException long baba1

I am sending long value and String value as extras from list activity to agenmin activity.But get java.lang.NullPointerException at line 120
long baba1 = intent1.getExtras().getLong("baba",0); //line number 120
Sending from list activity
// long id from from listview
Intent i = new Intent(list.this, agenmin.class);
i.putExtra("baba", id);
startActivity(i);
//int position from listview
String c= Integer.toString(position);
Intent i1 = new Intent(list.this, agenmin.class);
i1.putExtra("abc", c);
startActivity(i1);
At receiving side agenmin
Intent i1 = getIntent();
String easyPuzzle;
easyPuzzle=i1.getStringExtra("abc");
textView2.setText(easyPuzzle);
Toast.makeText(getApplicationContext(), "Position " + (mess)+" ROWID " +(easyPuzzle), Toast.LENGTH_LONG).show();
Intent intent1 = getIntent();
long baba1 = intent1.getExtras().getLong("baba",0);
String strLong1 = Long.toString(baba1);
textView3.setText(strLong1);
Logcat:
05-27 20:43:45.169: E/AndroidRuntime(593): FATAL EXCEPTION: main
05-27 20:43:45.169: E/AndroidRuntime(593): java.lang.NullPointerException
05-27 20:43:45.169: E/AndroidRuntime(593): at com.indianic.demo.calendark.agenmin$1.onClick(agenmin.java:120)
I started the agenmin activity twice thats the reason for 'java.lang.NullPointerException at line 120
try this:
PendingIntent intent1 = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Why do you have two intents starting the agenmin activity?
This way you're starting the agenmin activity twice, but giving only one extra to each of the starts. Then the second extra can't be obtained and it crashes when you try to use its value.
Just do this:
Intent i = new Intent(list.this, agenmin.class);
i.putExtra("baba", id);
i.putExtra("abc", c);
startActivity(i);
And I suggest you read more about what intents are and how they work. For example here. For starting a different activity, you only need one intent. And you can put as many extras in it as you wish.

Categories