3

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.)

INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
Bharathi V
  • 127
  • 10
  • New et1 field not exist in view because this is created dynamically, so can directly use et1 field without get from findViewById. – Sushil Mittal Mar 10 '19 at 07:35
  • can you please suggest a code for that @SushilMittal – Bharathi V Mar 11 '19 at 13:47
  • when both are EditText then why are you casting using this line, EditText item_name = (EditText) findViewById(et1.getId()); – Aniruddh Parihar Mar 13 '19 at 08:32
  • first the edittext is used for getting the data from user and it will be stored in db , and for later updation the user opening the same activity and doing the changes in the edittext (where the edittext view is dynamically created one) , so i'm casting like that. – Bharathi V Mar 13 '19 at 08:36

4 Answers4

4

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

class RootActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_root)

        val layout = findViewById<LinearLayout>(R.id.root)

        val ed = EditText(this).apply {
            hint = "Type here"
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            id = View.generateViewId()
        }
        layout.addView(ed)

        val ed2 = findViewById<EditText>(ed.id)
        Log.e("MEEEEEE", ed2.toString())
    }
}

Here is xml layout

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
Yamko
  • 535
  • 1
  • 3
  • 13
  • Do you add a view into layout hierarchy? When you do call findViewById(et1.getId()) it tries to find the view in activity's view hierarchy. But if you didn't add it you will get null pointer – Yamko Mar 13 '19 at 16:12
  • I couldn't understand this , can you explain or perhaps show a sample code @Yamko – karthik Mar 14 '19 at 15:57
  • When you create an activity you call it's method `setContentView(R.layout.activity_layout)`. Then, when you searching views with `findViewById()`, method looks for view in hierarchy which was inflated from R.layout.activity_layout. In your case you create view dynamically, but you don't add it to inflated hierarchy. So when you do `findViewById(dynamicViewId)` it can't find view with that id in hierarchy. – Yamko Mar 15 '19 at 08:24
  • @Yamko as you can see , i updated the question , actually im creating dynamic views inside a linearlayout and displaying the views using the reference id by the statically created linearlayout. – Bharathi V Mar 15 '19 at 14:41
  • updated answer -> added code which works for me. it Kotlin but I think it's clear enough. Let me know if you need help – Yamko Mar 15 '19 at 17:53
  • when i tried to access the value in different method outside the oncreate method and tried to update in the database same problem remains.(you have tried everything inside the oncreate method itself) . im using like this `protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.task_add_new); if (isUpdate) { init_update(); }` and call then call `val ed2 = findViewById(ed.id)` in init_update() – Bharathi V Mar 16 '19 at 09:29
  • Plz provide whole code and where exactly you face an issue – Yamko Mar 17 '19 at 07:03
0

first the edittext is used for getting the data from user and it will be stored in db , and for later updation the user opening the same activity and doing the changes in the edittext (where the edittext view is dynamically created one) , so i'm casting like that.

As per my understanding the EditText (et1) is being used to get input from user initially for saving the data. Later for viewing the EditText (et1) is used to display the data.

Here you don't need to findViewById() when you already have reference for EditText (et1).

Just declare the EditText in Activity level and use the same for getting input or displaying data on the view!

Sample Code:

EditText et1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);
}

@Override
protected void onResume() {
    super.onResume();
    setView();
    updateView();
}

private void setView() {
    et1 = new EditText(this);
    et1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    et1.setHint("Enter Item Name");
}

private void updateView() {
    if (dbHasValues) {
        et1.setText("From DB!!");
    }
}
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • here the user is the one creating the dynamic edittext views and they can create any number of them as per their need , so in order to identify which edittext field they want to update/modify, i need an reference id for that ,(without any id , how can i directly setText that from DB) can you understand the problem here! – Bharathi V Mar 13 '19 at 08:58
0

You can define that edittext in layout xml page and do visiblity gone for that field and when you want to show that edittext then you can make it visiblity visible after button click. A simple solution i guess. Then the element will be there it will not throw null pointer exception.

0

Ref : https://developer.android.com/reference/android/view/View.html

first you need to set id with the use of View.generateViewId()

public static int generateViewId ()

Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.

Ex.

et1.setId(View.generateViewId())

please check before use or et1 EditText Object is Null or Not.....

Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65