NullPointerException while calling an Activity - android

My program is crashing when I click on a button to bring me to another page. My OnClickListener seems correct but I know I've missed something. Can anyone see where I have went wrong?
error:
08-20 13:40:30.622: E/AndroidRuntime(1026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.LoginScr.Example/com.LoginScr.Example.CredentialsActivity}: java.lang.NullPointerException
from main activity used to call 2nd activity:
lsRegstr.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(LoginScrExample.this, CredentialsActivity.class);
startActivity(i);
}
credentials Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
rName = (EditText)findViewById(R.id.reg_uname);
rCode= (EditText)findViewById(R.id.reg_pswd);
bReg = (Button) findViewById(R.id.reg_button);
bReg.setOnClickListener(this);
bRtn = (Button) findViewById(R.id.rtn_button);
bRtn.setOnClickListener(this);
Bundle RegBundle = getIntent().getExtras();
bundleRegName = RegBundle.getString(rUsername);
bundleRegCode = RegBundle.getString(rPasscode);
rName.setText(bundleRegName);
rCode.setText(bundleRegCode);
}
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setlName(bundleRegName);
regDetails.setlCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
String[] whereClauseArgument = new String[1];
whereClauseArgument[0] = regDetails.getlName();
System.out.println(" Credentials Saved!" + whereClauseArgument[0]);
sqliteDB.close();
finish();
}
}

There is very limited information(as stack trace) and too many possibilities of errors. You are getting NullPointerException it means some where in your code you are trying to access a null object. One genuine possibility is at this part of the code in the 2nd activity where you are trying to get extra data from the intent. As you have not added any extra data in the 1st activity you will be receiving null and then you are trying to get string out of the bundle. Try to put a check for string to be null at this point of the code.
Bundle RegBundle = getIntent().getExtras();
if(RegBundle != null) {
bundleRegName = RegBundle.getString(rUsername);
bundleRegCode = RegBundle.getString(rPasscode);
}

With that limited info, it could be a number of things. One of the most likely causes is not declaring the new activity in your androidmanifest.xml. Have you declared the activity you're trying to launch in your androidmanifest.xml?

Related

Passing inputs to a new intent

hello there i'm a new beginner in android development. I tried several times to figure out my issue but i couldn't please help me.I created a simple login screen once the user enters the username and password I simply want to display it in the next activity. I used putExtra and getExtra but the values are null all the time.
This is my code
Intent i = new Intent(Data1.this , Data2.class);
i.putExtra("uname",username.getText().toString());
i.putExtra("pass",password.getText().toString());
Log.d("username",username.getText().toString());
Log.d("password",password.getText().toString());
startActivity(i);
data = (TextView)findViewById(R.id.txt);
Intent i = this.getIntent();
u = i.getStringExtra("username");
p = i.getStringExtra("password");
data.setText(u+" Successfully logged in User Name - "+ u + " Password - "+ p);
You've Passed the Data to the next Intent Correctly using PutExtra but in the new intent when you've used getStringExtra you've used another String variable which is completely different from what you've passed.Try this example it should work.You should use i.getStringExtra("uname"); and i.getStringExtra("pass"); instead of what you have passed.
public class Data1 extends AppCompatActivity {
EditText username;
EditText password;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data1);
username = (EditText)findViewById(R.id.edusername);
password = (EditText)findViewById(R.id.edpassword);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Data1.this , Data2.class);
i.putExtra("uname",username.getText().toString());
i.putExtra("pass",password.getText().toString());
Log.d("username",username.getText().toString());
Log.d("password",password.getText().toString());
startActivity(i);
}
});
}
}
public class Data2 extends AppCompatActivity {
TextView data;
String u;
String p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data2);
data = (TextView)findViewById(R.id.txt);
// Intent i = getIntent();
Intent i = this.getIntent();
u = i.getStringExtra("uname");
p = i.getStringExtra("pass");
data.setText(u+" Successfully logged in User Name - "+ u + " Password - "+ p);
}
}
You a passing the value using
i.putExtra("uname",username.getText().toString());
i.putExtra("pass",password.getText().toString());
and getting value using
u = i.getStringExtra("username");
p = i.getStringExtra("password");
here you must be use same key as you passed in intent so you have to use "uname" instead of "username" and "pass" instead of "password"..
example :
FirstActivity.java
i.putExtra("key", "value");
secondActivity.java
i.getStringExtra("key");
You are getting null values because strings are not same in put and get method.And values are always stored in same key.So change your code in get method like as-
Intent i = this.getIntent();
u = i.getStringExtra("uname");
p = i.getStringExtra("pass");`

Don't understand why I'm getting NullPointerException

I don't understand why I my app keeps on crashing. According to LogCat, it is caused by a NullPointerExeption on a line, however, I cannot find why it is occurring. What's supposed to happen is an image resource for an ImageView is changed in MainActivity by pressing a button on another activity. I have followed multiple guides, but get the recurring error. From what I can see it occurs when extra information is passed through an Intent, something is null but I cannot find it.
LogCat
05-03 22:33:03.158: E/AndroidRuntime(31629): Caused by: java.lang.NullPointerException
05-03 22:33:03.158: E/AndroidRuntime(31629): at com.crackedporcelain.crackedcalibration.MainActivity.onCreate(MainActivity.java:21)
Line 21 (offender in MainActivity)
String gridPressed = content.getString("gridPressed");
Main Activity (receiver)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle content = getIntent().getExtras();
// Set image based on which button was pressed
String gridPressed = content.getString("gridPressed");
ImageView spotlightOne = (ImageView) findViewById(R.id.variousOne);
if (gridPressed.equals("one")) {
spotlightOne.setImageResource(R.drawable.one);
} else if (gridPressed.equals("two")) {
spotlightOne.setImageResource(R.drawable.two);
} else {
spotlightOne.setImageResource(R.drawable.one);
}
ImageView buttonGrid = (ImageView) findViewById(R.id.phoneReference);
buttonGrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
"com.crackedporcelain.crackedcalibration.IDENTIFICATION"));
}
});
}
Other Activity (sender)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.identification);
ImageView gridButton1 = (ImageView) findViewById(R.id.buttonImage1);
ImageView gridButton2 = (ImageView) findViewById(R.id.buttonImage2);
gridButton1.setOnClickListener(this);
gridButton2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonImage1:
Intent oneA = new Intent(IdentificationActivity.this, MainActivity.class);
oneA.putExtra("gridPressed", "one");
startActivity(oneA);
break;
case R.id.buttonImage2:
Intent oneB = new Intent(IdentificationActivity.this, MainActivity.class);
oneB.putExtra("gridPressed", "two");
startActivity(oneB);
break;
}
}
Additional Info
Layouts for these classes are setup correctly, they work fine. It only force closes when I try to use Intents.
All help is appreciated! Thanks!
The received intent did not contain any extra values. Make sure the code sending the intent had added to the intent an extra String value with the name "gridPressed". You can use Intent.putExtra(String, String) for this purpose.
Intent.getExtras() will return null if there are no extra values. In addition, Bundle.getString(String key) will return null if the Bundle does not contain the key.
Finally, be sure to check that MainActivity is not invocable in any other way (like when the app icon is clicked). If that is possible, then this version of onCreate() will work better:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView spotlightOne = (ImageView) findViewById(R.id.variousOne);
// Set image based on which button was pressed, if any
String gridPressed = getIntent().getStringExtra("gridPressed");
if ("one".equals(gridPressed)) {
spotlightOne.setImageResource(R.drawable.one);
} else if ("two".equals(gridPressed)) {
spotlightOne.setImageResource(R.drawable.two);
} else {
spotlightOne.setImageResource(R.drawable.one);
}
ImageView buttonGrid = (ImageView) findViewById(R.id.phoneReference);
buttonGrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
"com.crackedporcelain.crackedcalibration.IDENTIFICATION"));
}
});
}
You're getting a NPE because you are not sending a bundle from the sender activity rather just a string extra. So, to access the String extra in the receiver activity, use :
getIntent().getStringExtra("gridPressed");
To send bundles, you need to first create a bundle, then add extras to that bundle and then pass the bundle with the intent :
Bundle bundle = new Bundle();
bundle.putString("KEY", "VALUE");
intent.putExtras(bundle);
If you send a bundle as mentioned in 2, your existing code in the receiving activity will work, otherwise you can change the code in the receiving activity as mentioned in 1.

Intent - Put and Get Extras - Android - NullPointer

I have nullpointer exception.
Function in MainActivity.
public void intentLoginUser(){
Intent aux = new Intent(MainActivity.this, LoginUserSplashScreen.class);
aux.putExtra("user", username);
aux.putStringArrayListExtra("notificationList", MainActivity.this.notificationsList);
aux.putStringArrayListExtra("friendList", MainActivity.this.friendList);
aux.putStringArrayListExtra("localizationList", MainActivity.this.localizationList);
MainActivity.this.startActivity(aux);
}
Function in another Activity, named LoginUserSplashScreen
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
notificationList = getIntent().getStringArrayListExtra("notificationList");
friendList = getIntent().getStringArrayListExtra("friendList");
localizationList = getIntent().getStringArrayListExtra("localizationList");
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
setContentView(R.layout.activity_loginuser);}
What's wrong?
I have nullpointer in function onCreate, in Log.e(); ... I'm trying debugging that, but I can't.
EDIT - Nullpointer in function onCreate in line Log.e()
Because all lists are null (can't get anything from last activity).
Try
getIntent().getStringExtra("user");
instead of
getIntent().getStringArrayListExtra("user");
"user" was not ArrayList.
You have a mismatch in your put and get calls.
aux.putExtra("user", username);
myUsername = getIntent().getStringArrayListExtra("user");
Use aux.putStringArrayListExtra("user", username) with getIntent().getStringArrayListExtra("user") (assuming username is an ArrayList< String >) and use aux.putExtra("user", username) with getIntent().getStringExtra("user") (assuming username is a String).
In main activity you have assigned object with putExtra
aux.putExtra("user", username);
But in receiving point your getStringArrayListExtra
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
This is error code
aux.putExtra("user", username);
myUsername = getIntent().getStringArrayListExtra("user");
you can use bundle,this code is work for you
getIntent().getStringExtra("user");
or
Bundle bundle = new Bundle();
bundle.putString("user", username);
aux.putExtras(bundle);
getIntent().getExtras().getString("user");
I think the issue is that when you assign myUsername, you are saying that the variable with key "user" is a StringArrayList, but instead it is a String when you put it in the intent. The putExtra() method takes String types, not StringArrayLists.
My solution,
In MainActivity:
public ArrayList<String> usernameList = new ArrayList<String>();
public Queue<String> serverMessages = new LinkedList<String>();
public ArrayList<String> notificationsList = new ArrayList<String>();
public ArrayList<String> friendList = new ArrayList<String>();
public ArrayList<String> localizationList = new ArrayList<String>();
public void intentLoginUser(){
Intent aux = new Intent(MainActivity.this, LoginUserSplashScreen.class);
usernameList.add(username);
aux.putStringArrayListExtra("user", MainActivity.this.usernameList);
aux.putStringArrayListExtra("notificationList", MainActivity.this.notificationsList);
aux.putStringArrayListExtra("friendList", MainActivity.this.friendList);
aux.putStringArrayListExtra("localizationList", MainActivity.this.localizationList);
MainActivity.this.startActivity(aux);
}
In LoginUserSplashScreen
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
notificationList = getIntent().getStringArrayListExtra("notificationList");
friendList = getIntent().getStringArrayListExtra("friendList");
localizationList = getIntent().getStringArrayListExtra("localizationList");
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
setContentView(R.layout.activity_loginuser);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
And Log.e(); works and pass all data.

Activity That has Several Extras from Other Activities?

I have an Activity that uses the following code to retrieve information from another activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int tok = extras.getInt("Token");
tempToken += tok;
}
This is the Code inside the first other class that sends this information:
final Button mainMen = (Button) findViewById(R.id.toMainMenu);
mainMen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Menu.class);
i.putExtra("Token", tok + teTok);
startActivity(i);
}
});
Now i have another Activity that also wants to sen information to the Main Activity like so:
maMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Campaign.this, Menu.class);
intent.putExtra("Token", player.tokens);
intent.putExtra("Round", player.round);
intent.putExtra("Rank", player.rank);
intent.putExtra("Score", player.score);
intent.putExtra("Sec", player.secondsTapped);
intent.putExtra("Min", player.minutesTapped);
intent.putExtra("Hour", player.hoursTapped);
intent.putExtra("Day", player.daysTapped);
intent.putExtra("LifeTap", player.tapsInLife);
intent.putExtra("SecTap", player.tapsPerSec);
intent.putExtra("TapRo", player.tapps);
startActivity(intent);
}
});
Now my question is, how do i handle these different extras from multiple Activities inside the one Main Activity?
Thank You for your time :)
There are two ways to solve your problem..
1)
You can pass one boolean value to or and int variable with some value.. And retrieve this in your new Activity and check with boolean value or int value and get correct data correspond to Activity.
2) You can save your all Data in Shared Preference. And get your all Data in any Activity.
you can send one boolean value that data is in first class or second class and in MainActivity check the value and get the correct data

can anyone see why I'm getting a Null Pointer exception on exit

Here is a short List activity that calls a custom adapter to show class room attendance.
I set up the data using the classroom rowid that was clicked to get here and then query my
DB to get all students in the class. I use a custom adapter because I have a list of checkboxes
along with student names. No matter if I use my adapter or simply substitute in simplecursoradapter (and lose my checkbox functionality) upon exit I get a null pointer exception. This happens whether
I click the "done" button or click the back arrow. I can't seem to see anything. Can you?
public class ShowStudentAttendance extends ListActivity {
private gradeBookDbAdapter mDbHelper;
private Long mRowId;
private TextView mNameText;
private String classname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor stud;
mDbHelper = new gradeBookDbAdapter(this);
mDbHelper.open();
mRowId = (savedInstanceState == null) ? null
: (Long) savedInstanceState
.getSerializable(gradeBookDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras
.getLong(gradeBookDbAdapter.KEY_ROWID) : null;
}
if (mRowId != null) {
stud = mDbHelper.fetchClass(mRowId);
startManagingCursor(stud);
classname = stud.getString(
stud.getColumnIndexOrThrow(gradeBookDbAdapter.KEY_CLASSNAME));
String title = "Attendance for " + classname;
setTitle(title);
}
stud = mDbHelper.fetchAllStudentsClass(mRowId);
startManagingCursor(stud);
setContentView(R.layout.attendance_list);
Button doneButton = (Button) findViewById(R.id.Done);
doneButton.setOnClickListener(mAttendanceActivity);
// Create an array to specify the fields we want to display in the list (only name)
String[] from = new String[]{gradeBookDbAdapter.KEY_NAME,
gradeBookDbAdapter.KEY_ROWID};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.stuname};
// Now create a simple cursor adapter and set it to display
MyDataAdapter studs =
new MyDataAdapter(this, R.layout.show_attendance, stud, from, to);
setListAdapter(studs);
}
private OnClickListener mAttendanceActivity = new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
};
}
It seems you are not closing cursor or database befe exit activity.
Oops. Nevermind. I was looking in the wrong place. Nothing wrong with this code. I was just calling the activity with startActivityForResult and didn't need to and never had an onActivityResult(). I changed it to a simple startActivity and all is well again. Thanks for looking, though. –

Categories

Resources