Reputation: 1113
public class MyActivity extends Activity {
Context context;
List<String> tasks;
ArrayAdapter<String> adapter;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
tasks = new ArrayList<String>();
Button add = (Button) findViewById(R.id.button);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
editText.setVisibility(1);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);
String value = editText.getText().toString();
tasks.add(value);
adapter = new ArrayAdapter<String>(context,R.id.listView,tasks);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
});
}
}
Here, i am getting value from the user. and i am trying to add it to list view dynamically. But, it is showing an error called "Unfortunatly app is closed". it is failing in adding string value to the tasks variable. tasks is a list of string.
tasks.add(value);
if i try to add something else also it is failing. like,
tasks.add("something");
i don't know what is the problem. but i am sure that it is failing in this line, because if i remove this line, my app is working fine. if someone knows why it is failing please let me know. thanks in advance.
Upvotes: 0
Views: 14952
Reputation: 1423
There are too many wrong in your source code. Try the following code and, understand what you are writing rather than copy pasting blindly.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
tasks = new ArrayList<String>();
// instances all your variables on initial only
Button add = (Button) findViewById(R.id.button);
final EditText editText = (EditText) findViewById(R.id.editText);
// second parameter is row layout,
adapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item1,tasks);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editText.setVisibility(1);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);
String value = editText.getText().toString();
tasks.add(value);
// this method will refresh your listview manually
adapter.notifyDataSetChanged();
}
});
}
Upvotes: 5