Search code examples
javaandroidandroid-listviewandroid-edittextsettext

Android: setText() doesn't work on device, but on emulator with keyboard input


I'm making a simple app on android studio. MainActivity has a ListView which have items from string-array, and if I click an item, a AlterDialog is shown. The dialog has an EdixText. I write text on it, and if I click the positive button, the TextView of item I clicked is changed to what I just write. Sorry for my bad English... Anyway, here is my source code for MainActivity.

package com.softdept.sangkyu.swex01;

import ...

public class SWEX01 extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swex01);
    ListAdapter myAdapter = new MyAdapter(this, getResources().getStringArray(R.array.tvshow));
    ListView tvShowList = (ListView)findViewById(R.id.listView);
    tvShowList.setAdapter(myAdapter);
    tvShowList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
            final TextView textView = (TextView)view.findViewById(R.id.textView);
            String showName = textView.getText().toString();
            Toast.makeText(parent.getContext(), showName, Toast.LENGTH_SHORT).show();
            AlertDialog.Builder dialog = new AlertDialog.Builder(parent.getContext());
            dialog.setTitle("Modify TV show");
            dialog.setMessage(showName);
            final EditText editText = new EditText(getApplicationContext());
            dialog.setView(editText);
            dialog.setNegativeButton("Cancel", null);
            dialog.setPositiveButton("Modify", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String editShowName = editText.getText().toString();
                    textView.setText(editShowName);
                    Toast.makeText(parent.getContext(), "Modified!", Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show();
        }
    });
}
}

I ran this app and on emulator with my keyboard input worked well. However, I also ran on my android device and when I clicked the button, the text is unchanged... What's wrong with my code??


Solution

  • This is how it is worked for me after changing few lines of code.

    final String[] items=getResources().getStringArray(R.array.tvshow);

    //you can carry on with ListAdapter.

    final ArrayAdapter myAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,items);

    //Inside onClick method of PositiveButton

    items[position]=editShowName; myAdapter.notifyDataSetChanged();

    You need to call Adapter.notifyDataSetChanged() whenever the adapter's data changes.