I am getting null reference exception in the childActivity intent.I am newbie to the android development.Please help me to resolve this problem.What i am doing to sending data from ParentActivity to ChildActivity.
ParentActivity :I have 3 EditText fields in the ParentActivity.I want to display these 3 fields into ChildActivity.There is a button control so when i click on it,It has to switch from ParentActivity to ChildActivity.
public class ParentActivity extends Activity {
private EditText EmpId;
private EditText EmpName;
private EditText Gender;
private Button btnShowInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent);
InitializeControls();
}
private void InitializeControls() {
EmpId = (EditText) findViewById(R.id.editText1);
EmpName = (EditText) findViewById(R.id.editText2);
Gender = (EditText) findViewById(R.id.editText3);
btnShowInfo = (Button) findViewById(R.id.button1);
final Context context = this;
btnShowInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent ParentIntent = new Intent(context, ChildActivity.class);
ParentIntent.putExtra("Eid", EmpId.getText().toString());
ParentIntent.putExtra("EName", EmpName.getText().toString());
ParentIntent.putExtra("EGender", Gender.getText().toString());
startActivity(ParentIntent);
}
});
}
}
ChildActivity :: It has to show the values which i entered in the ParentActivity.
public class ChildActivity extends Activity {
private TextView txtView1;
private TextView txtView2;
private TextView txtView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
InitializeControls();
}
private void InitializeControls() {
txtView1 = (TextView) findViewById(R.id.editText1);
txtView2 = (TextView) findViewById(R.id.editText2);
txtView3 = (TextView) findViewById(R.id.editText3);
GetDataFromIntent();
}
private void GetDataFromIntent() {
Bundle extras = getIntent().getExtras();
if (extras == null) {
txtView1.setText("No data is received.");
} else {
txtView1.setText(extras.getString("Eid"));
txtView2.setText(extras.getString("EName"));
txtView3.setText(extras.getString("EGender"));
}
}
}
Exception :: This is what i am getting in the Console window.
01-05 15:04:46.210: E/AndroidRuntime(1658): Caused by: java.lang.NullPointerException
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.GetDataFromIntent(ChildActivity.java:36)
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.InitializeControls(ChildActivity.java:26)
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.onCreate(ChildActivity.java:19)
I am newbie to the android world.Please help on this.
So the line of code that is causing the issue is:
txtView1.setText(extras.getString("Eid"));
A null pointer exception essentially means that you are trying to call a function on something that's null. In this case, it could be either txtView1 or extras. As you check to see if extra is null, it must in fact be the txtView1 that is null. Per Android documents, findViewById returns:
Returns
The view that has the given id in the hierarchy or null
Thus, if you misspelled your text labels, it could cause this problem. A good way to check is by adding this right before your error.
Log.v("Child","txtView1="+txtView1);
Related
I'm trying to keep what users typed in my login dialog window when orientation changing, but i always receive this error message:
Attempt to invoke virtual method 'android.view.View
android.widget.RelativeLayout.findViewById(int)' on a null object
reference.
There's the code:
public class ReservationActivity extends AppCompatActivity {
ImageView uDeM_Logo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
uDeM_Logo = (ImageView)findViewById(R.id.UdeM_Logo);
dimensions();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
RelativeLayout login = (RelativeLayout)findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = userField.getText().toString();
String pass = passField.getText().toString();
outState.putString("User", user);
outState.putString("Pass", pass);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
}
public void onConfigurationChanged(Configuration nouvOrient) {
if(nouvOrient.orientation == Configuration.ORIENTATION_LANDSCAPE ||
nouvOrient.orientation == Configuration.ORIENTATION_PORTRAIT)
dimensions();
}
public void dimensions() {
Display display = getWindowManager().getDefaultDisplay();
Point grandeur = new Point();
display.getSize(grandeur);
double hauteur = grandeur.y, dim = hauteur * 0.2492;
int dimsInt = (int) dim;
ViewGroup.LayoutParams parametres = uDeM_Logo.getLayoutParams();
parametres.width = dimsInt;
parametres.height = dimsInt;
uDeM_Logo.setLayoutParams(parametres);
}
public void loginDialog(View log){
final Dialog login = new Dialog(this);
login.setContentView(R.layout.login_dialog);
Button btnLogin = (Button)login.findViewById(R.id.dialogLoginBtn);
Button btnCancel = (Button)login.findViewById(R.id.dialogCancelBtn);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ReservationActivity.this,
"Login Sucessfull", Toast.LENGTH_SHORT).show();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login.dismiss();
}
});
login.show();
}
}
It seems that you do not need to recreate the activity on orientation change. You can just set this configuration for your activity in your manifest.
android:configChanges="keyboardHidden|orientation
don't do that in onRestoreInstanceState()
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
But instead make these login, userField, passField a field variables in your Activity class as follows:
private RelativeLayout login;
private EditText userField, passField;
Also move the above 3 code lines from onSaveInstanceState() to onCreate() but modify them to work with your field variables as follows:
login = (RelativeLayout) findViewById(R.id.loginLayout);
userField = (EditText) login.findViewById(R.id.userEditText);
passField = (EditText) login.findViewById(R.id.passEditText);
And I recommend you to restore state at onCreate() instead of onRestoreInstanceState() as follows:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
} else {
// Probably initialize members with default values for a new instance
}
The reason is because onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart()
I'm trying to do a Contact Manager but I have one problem: My app crashes when I touch save button for saving my new contact, and I don't know why because Eclipse don't says anything is wrong in my code. I touch the button and the app crashes, but it creates a new database.
public class Insertarcontactes extends Activity {
private TextView mTextView;
private EditText mNom;
private EditText mCognoms;
private EditText mAdressa;
private EditText mFixe;
private EditText mMobil;
private EditText mEmail;
private DatabaseManager mDBM;
protected Cursor mCursor;
private SimpleCursorAdapter mAdapter;
private Button mguardar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insertarcontactes);
mDBM = new DatabaseManager();
mDBM.openDB(this);
mTextView = (TextView) findViewById(R.id.textView1);
mNom = (EditText) findViewById(R.id.nom);
mCognoms = (EditText) findViewById(R.id.cognoms);
mAdressa = (EditText) findViewById(R.id.adressa);
mFixe = (EditText) findViewById(R.id.telefonfix);
mMobil = (EditText) findViewById(R.id.telefonmobil);
mEmail = (EditText) findViewById(R.id.email);
mguardar = (Button)findViewById(R.id.guardar);
}
public void guardalo(View v) {
if(!mNom.getText().toString().equals("")) {
mDBM.insertarContacto(
mNom.getText().toString(),
mCognoms.getText().toString(),
mAdressa.getText().toString(),
mFixe.getText().toString(),
mMobil.getText().toString(),
mEmail.getText().toString()
);
mNom.setText("");
mCognoms.setText("");
mAdressa.setText("");
mFixe.setText("");
mMobil.setText("");
mEmail.setText("");
mCursor.requery();
mAdapter.notifyDataSetChanged();
Intent vesalallista = new Intent(this, Llistacontactes.class);
startActivity(vesalallista);
}
}
public void tornaenrere(View v){
Intent tornaenrere = new Intent(this, Menuprincipal.class);
startActivity(tornaenrere);
}
#Override
protected void onDestroy() {
mDBM.closeDB();
super.onDestroy();
}
Go to your android manifest file and add write contacts permission
Your mCursor is un-initialized, and you are calling its requery() method mCursor.requery(); in guardalo() method. Hence it should be giving you NullPointerException
You need to initialize this mCursor object in onCreate() method.
I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}
You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.
I have this error nullpointerexception, when i do getText().toString() from EditTex:
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_mess_layout);
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String textEmail = tEmail.getText().toString(); //nullpointerexception
Editable textEmail1Editable = tEmail.getText(); //nullpointerexception
String textEmail = textEmail1Editable.toString()
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
Please, tell me how to do it
UPDATE Q
David, thank you, for your surmise,the problem was really in the my tangled Layouts
I had all 4 levels of nesting LinearLayouts.
After I left the simplified scheme and only 2 levels I have, all began to work
You need to call setContentView(your_layout.xml) so it knows what layout to use. Without setting the layout, all of your calls to findViewById(...) that try to find the views in your layout will return null.
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(your_layout.xml); //set your activity layout here.
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String textEmail = tEmail.getText().toString(); //nullpointerexception
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
If you have no assigned text then I would assume that the EditText retrieval of the text would be a null entry and you are attempting to make a string of that null entry.
I'm a beginner in application development. My problem is, that when I run my app and I click on the Calculate button, the program stops. The code:
public class screen1 extends Activity {
private EditText name;
private CheckBox box1;
private Spinner spinner;
private TextView text1, text2, text3, text4, text5, text6;
private Button calcbutton, closebutton;
String strength;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.military_ranks , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hubSpinner.setAdapter(adapter);
name = (EditText)findViewById(R.id.editText1);
strength = name.getText().toString();
box1 = (CheckBox)findViewById(R.id.checkBox1);
text1 = (TextView)findViewById(R.id.textView4);
text2 = (TextView)findViewById(R.id.textView6);
text3 = (TextView)findViewById(R.id.textView8);
text4 = (TextView)findViewById(R.id.textView10);
text5 = (TextView)findViewById(R.id.textView12);
text6 = (TextView)findViewById(R.id.textView14);
final Button calcbutton = (Button) findViewById(R.id.button1);
calcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
double sebzes;
if(box1.isChecked()){
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100);
text1.setText(Double.toString(sebzes));
}
else{
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1;
text1.setText(Double.toString(sebzes));
}
}
});
final Button closebutton = (Button) findViewById(R.id.button2);
closebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
In the edittext component you should be able to write numbers only. I don't know why it's not working.
The problem are these two lines:
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
The first won't fail if you use only numbers in your EditText but it would be better to ensure that or at least catch the exception that is thrown when you try to convert a character to a numberical value. Additionally you could also use Integer.valueOf(strength).intValue(); even so it is normally not really necessary.
The real problem is the second line. You declared the variable spinner but you never instantiate it. That's why you will get a NullPointerException there.
On an unrelated note: You also should start your class name with a capital letter to follow the Java naming conventions.
You're not instantiating spinner anywhere, but you're referencing it in the second line of your button click method. Probably a null reference problem.