java.lang.NullPointerException long baba1 - java

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.

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 : How to use same AlarmManager in loop?

I write bellow method for alarm.
public void alarm(int time){
Intent intent = new Intent(MainActivity.this, Alarm.class);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0 , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
This method working perfectly. But the problem when I call the method more than one time. Like,
alarm(10);
alarm(50);
This time it only invoke alarm(10); But don't invoke alarm(50);
Anyone please help why it show this problem!
Your PendingIntent has the same properties both times you call your method. When you call PendingIntent.getBroadcast() the second time it will return the PendingIntent that was already created the first time.
If you want the alarm to trigger twice you need to do something like this:
public void alarm(int time, int requestCode){
Intent intent = new Intent(MainActivity.this, Alarm.class);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), requestCode , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
And then call it like this:
alarm(10, 0);
alarm(50, 1);
You are giving the same ID (0)
You need to use different unique id. use different pending intent id like this. you can use millisecond as id.
public void alarm(int time, int requestCode){
Intent intent = new Intent(MainActivity.this, Alarm.class);
Long timeToMilliSeconds = timeToMilliSeconds(hour, minute);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), timeToMilliSeconds , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
You are giving the same ID 0 (the second parameter in PendingIntent::getBroadcast) to more than onePendingIntent. This is your mistake.
Depending on the FLAG you set, the behavior may vary.
Consider either using a different ID for each PE or one of the standard flags.
Also see:
Wrong pending intent is being triggered
How does android compare pending intents
Adding flags to PendingIntent
// context variable contains your `Context`
AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
for(i = 0; i < 10; ++i)
{
Intent intent = new Intent(context, OnAlarmReceiver.class);
// Loop counter `i` is used as a `requestCode`
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
// Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000 * i,
pendingIntent);
intentArray.add(pendingIntent);
}
Call it like this
alarm(10, 0);
alarm(50, 1);
For more than one Pendingintent it needs different id so in the caller method pass
different id.

Error when trying to get a bundle from another activity [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 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

How to know if a value in firebase has increased or decreased?

I'm developing an android app in which there is this option to Follow/Unfollow a user. Whenever someone follows him, the counter in FirebaseDatabase gets increased by 1 and when someone unfollows him, the counter gets decreased by 1.
I'm trying to notify user every time someone follows him by starting a service as soon as he leave the app and writing the code in the Service.
Here's the code in onCreate() of the Service:
firebaseDatabaseFollowers.child("***").child("***").child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
b = sharedPref2.getBoolean(SettingsActivity.KEY_PREF_NOTIF_FOLLOW, true);
Toast.makeText(getBaseContext(), "b: " + String.valueOf(b), Toast.LENGTH_SHORT).show();
if (dataSnapshot.getValue() != null) {
if (String.valueOf(b).equals("true")) {
final int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationService());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);
}
} else {
Toast.makeText(getBaseContext(), "database is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The notification part is working fine. The only problem is that the notification is delivered even when someone unfollows the user and I don't want this to happen.
So, is there any way to know that if the counter in FirebaseDatabase increased or decreased so that I can notify accordingly?
Please let me know.
I would store a global variable in your app that holds the number of followers that the user currently has. When the database sends down new info, you can compare it to the number you have saved by using if new number > or < than saved number. This could be problematic, however, in case the user goes offline and comes back online after, say 1 user unfollowed and 2 others followed. In this case, the user would just get a +1 follower notification. What I might recommend is sending down the username of the user that followed, just like Instagram does. For example, "John Smith followed you!" or "James Smith unfollowed you!".

Developing simple Quiz application with Local Sqlite databese but score not incress

I am using local SQlite database to get data. It correctly displays in the view, but the score is not increased. Can you see the problem?
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
//problem is here score not incress ...
if (currentQ.getANSWER().equals(answer.getText())) {
score++;
Log.d("score", "Your score" + score);
}
if(qid<5){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
Here is log output:
04-20 17:32:50.448 19972-19972/com.example.zeenat.quizappsqlite D/yourans: C HP 04-20 17:32:51.648 19972-19972/com.example.zeenat.quizappsqlite D/yourans: B SuSe 04-20 17:32:52.178 19972-19972/com.example.zeenat.quizappsqlite D/yourans: C RAM 04-20 17:32:52.688 19972-19972/com.example.zeenat.quizappsqlite D/yourans: A Router 04-20 17:32:53.218 19972-19972/com.example.zeenat.quizappsqlite D/yourans: C Ruby
You are checking if the given answer (Letter A, B, C) is equal to the correct answers text. Your code increasing the score will never get called. answer.getText() does not return a single letter, it will give you the answers text. currentQ.getANSWER() instead will just give you the single letter the user selected.

Categories