I am displaying task objects in my listview.There are 2 layout file one is activty_main layout which has a listview textviews a button and inputs.other is for listview elements row.xml.What i am trying to do is refresh list after adding new task. MainActivity:
public class MainActivity extends AppCompatActivity {
private EditText name, date, desc;
List<Task> tasklist = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.addtask);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNewTask();
}
});
name = (EditText) findViewById(R.id.name);
date = (EditText) findViewById(R.id.date);
desc = (EditText) findViewById(R.id.desc);
ListView tasklistview = (ListView)findViewById(R.id.tasks);
TaskAdapter adapter = new TaskAdapter(this, R.layout.row, tasklist);
tasklistview.setAdapter(adapter);
Task sometask = new Task("CS412-Lecture", "","Apr6,2016");
tasklist.add(sometask);
}
public void addNewTask(){
Toast.makeText(MainActivity.this,
"TEST", Toast.LENGTH_LONG).show();
Task task = new Task(name.getText().toString(),desc.getText().toString(),date.getText().toString());
tasklist.add(task);
}
}
Task Class:
public class Task {
String name;
String desc;
String date;
public Task(String name,String desc,String date){
this.name = name;
this.desc = desc;
this.date = date;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
public String getDate() {
return date;
}
public void setName(String name) {
this.name = name;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setDate(String date) {
this.date = date;
}
}
TaskAdapter:
public class TaskAdapter extends ArrayAdapter<Task> {
private int layoutResource;
public TaskAdapter(Context context, int layoutResource, List<Task> tasks) {
super(context, layoutResource, tasks);
this.layoutResource = layoutResource;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(layoutResource, null);
}
Task tasks = getItem(position);
if (tasks != null) {
TextView name = (TextView) view.findViewById(R.id.name);
TextView date = (TextView) view.findViewById(R.id.date);
if (name != null) {
name.setText(tasks.getName());
}
if (date != null) {
date.setText(tasks.getDate());
}
}
return view;
}
}
