I am building an app, in which I have a edit text field and getting data from user and storing it in database it is working fine , now I used a button to dynamically create another edit text field (this field is created only if the users want by using button click) , now the id of the dynamically created field is always null and shows error. I will share my code.
for dynamic edit text:
//update start
final LinearLayout ll = (LinearLayout) findViewById(R.id.li1);
mContext = getApplicationContext();
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//update end
et1 = new EditText(AddTask.this);
et1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
et1.setHint("Enter Item Name");
et1.setId(View.generateViewId());
//updates
layout.addView(et1, params1);
ll.addView(layout);
for accessing it:
EditText item_name = (EditText) findViewById(et1.getId());
when running the app , im getting error in this line , like this.
logcat:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'int android.widget.EditText.getId()' on a null object reference
updates :
i also tried this way , still no use guys ,
EditText item_name = (EditText) findViewById(getResources().getIdentifier(String.valueOf(et1.getId()), "id", getPackageName()));
(here the data was inserting into the database using this code , but when trying to view the data , the app crashes.)
Firstly you need to set id, when you create view. Then you can try to get view's id. How to set id programmatically
It's for sure that you doing something wrong. I just tried to do what you are trying and it works. Here is my activity
Here is xml layout