How to use custom adapter while adding and editing

2019-08-23 06:28发布

I want to implement a to-do list application. I have three activities: one main activity, one adding activity and one editing activity. In my main activity there is a add button and a listview that shows the to-do items. When I click add button, adding activity is executed. In this activity,there is an edittext for the task, a datepicker and a spinner for priority level. When ok button is clicked, all these entred values are sent to main activity's listview as a line. And, when click an item on this list, editing activity is executed and user can change the values. However, in my code, when user enters the values, I can reach them in my custom adapter class but I could't display them in listview. Listview remains empty. How can i fix my code?

main activity:

public class MainActivity extends Activity {

protected static final String edits = "mainTask";

private ToDoItemAdapter listAdapter;
//private ToDoItemAdapter myCustomAdapter;
//private ArrayList<String> listString;
public ArrayList<ToDoItem> listItems;

public static final int ADD_TASKS = 1;
public static final int EDIT_TASKS = 2;

Button button;
ListView listView;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private void initUI() {

    getViewReferences();
    initializeToDoList();

}

private void setListener() {
    // TODO Auto-generated method stub
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent addTaskIntent = new Intent(MainActivity.this, AddActivity.class);
            startActivityForResult(addTaskIntent, ADD_TASKS);
        }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            System.out.println(arg2);
            ToDoItemAdapter myAdapter = new ToDoItemAdapter(MainActivity.this,R.layout.editing_task,listItems);
            listView.setAdapter(myAdapter);
            Intent editTaskIntent = new Intent(MainActivity.this, EditingTask.class);
            //editTaskIntent.putExtra("mainTask", arg2);
            startActivityForResult(editTaskIntent, EDIT_TASKS);
        }
    });

}

private void getViewReferences() {
    // TODO Auto-generated method stub
    button = (Button) findViewById(R.id.addButton);
    listView = (ListView) findViewById(R.id.listView);
}


private void initializeToDoList() {
    // TODO Auto-generated method stub
    listItems = new ArrayList<ToDoItem>();
    //listString = new ArrayList<String>();
    listAdapter = new ToDoItemAdapter(MainActivity.this, R.layout.activity_main, listItems);
    listView.setAdapter(listAdapter);

    View noTaskView = findViewById(R.id.emptyToDoList);
    listView.setEmptyView(noTaskView);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case ADD_TASKS:
            updateToDoList(data);
            break;
        case EDIT_TASKS:
            break;
        default:
            break;
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

private void updateToDoList(Intent data) {
    // TODO Auto-generated method stub
    String task = AddActivity.tasks;
    ArrayList<String> list = data.getStringArrayListExtra(task);
    String addedTask = list.get(0);
    String addedDeadline = list.get(1);
    String addedPriority = list.get(2);
    ToDoItem item = new ToDoItem(addedTask, addedDeadline ,"0", addedPriority);
    listItems.add(item);
    //listString.add(addedTask + "   " + addedDeadline + "   " + addedPriority);
    Log.w("Items:",listItems.get(0).getTask());
    //Log.w("String:",listString.get(0));
    listAdapter.notifyDataSetChanged();
}

}

ToDoItemAdapter class:

public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> { 

    Context context;
    private int resource; 
    ArrayList<ToDoItem> todoItem;

    public ToDoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) { 

        super(context, resource, objects); 
        this.context = context;
        this.resource = resource;
        this.todoItem = objects;
    } 

    @Override
        public ToDoItem getItem(int position) {
        return this.todoItem.get(position);
    }

    @Override
        public int getCount() {
        return this.todoItem.size();
    }

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
        // TODO Auto-generated method stub 

        View row = convertView;

        if (convertView == null) 
        { 
            /*todoView = new LinearLayout(getContext()); 
            String inflater = Context.LAYOUT_INFLATER_SERVICE; 
            LayoutInflater li; 
            li = (LayoutInflater)getContext().getSystemService(inflater); 
            li.inflate(resource, todoView, true); 
            */

            LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(resource, parent, false);
        } 


        //LinearLayout todoView; 
        ToDoItem todo = getItem(position); 
        String taskString = todo.getTask(); 
        Log.w("task:", taskString);
        String dateString = todo.getDeadline(); 
        String priorityString = todo.getPriority(); 
        String itemRow = taskString + "   " + dateString + "   " + priorityString;

        return row; 
    } 
}

Adding class:

public class AddActivity extends Activity{


    private String[] states;
    private Spinner spinner;
    int position1;
    String priority;

    EditText etDate;
    Button change_date;
    final int Date_Dialog_ID=0;
    int cDay,cMonth,cYear; // this is the instances of the current date
    Calendar cDate;
    int sDay,sMonth,sYear; // this is the instances of the entered date

    protected static final String tasks = "addingTask";
    private static final String LOG_TAG = "addingTaskActivity";

    MainActivity main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        initUI();
        showDatePicker();
        showPriorityLevel();
    }

    private void showPriorityLevel() {
        // TODO Auto-generated method stub
        states = getResources().getStringArray(R.array.priority_level);
        spinner = (Spinner) findViewById(R.id.priority_spinner);

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, states);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                position1 = spinner.getSelectedItemPosition();

                switch(position1)
                {
                    case 0: priority = "0";
                            break;
                    case 1: priority = "1";
                            break;
                    case 2: priority = "2";
                            break;
                    case 3: priority = "3";
                            break;
                    case 4: priority = "4";
                            break;
                    case 5: priority = "5";
                            break;
                    case 6: priority = "6";
                            break;
                    case 7: priority = "7";
                            break;
                    case 8: priority = "8";
                            break;
                    case 9: priority = "9";
                            break;
                    default: break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });
    }


    private void showDatePicker() {
        // TODO Auto-generated method stub

        etDate=(EditText)findViewById(R.id.EditText01);
        change_date=(Button)findViewById(R.id.Button01);
        change_date.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        //triggers the DatePickerDialog
        showDialog(Date_Dialog_ID);
        }
        });
        //getting current date
        cDate=Calendar.getInstance();
        cDay=cDate.get(Calendar.DAY_OF_MONTH);
        cMonth=cDate.get(Calendar.MONTH);
        cYear=cDate.get(Calendar.YEAR);
        //assigning the edittext with the current date in the beginning
        sDay=cDay;
        sMonth=cMonth;
        sYear=cYear;
        updateDateDisplay(sYear,sMonth,sDay);

    }

    @Override
    protected Dialog onCreateDialog(int id) {

    switch (id) {
    case Date_Dialog_ID:
    return new DatePickerDialog(this, onDateSet, cYear, cMonth,
    cDay);
    }
    return null;
    }

    private void updateDateDisplay(int year,int month,int date) {
    // TODO Auto-generated method stub
    etDate.setText(date+"-"+(month+1)+"-"+year);
    }

    private OnDateSetListener onDateSet=new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            sYear=year;
            sMonth=monthOfYear;
            sDay=dayOfMonth;
            updateDateDisplay(sYear,sMonth,sDay);
        }
    };

    private void initUI() {
        // TODO Auto-generated method stub
        setContentView(R.layout.adding_task);

        final EditText editTextTask = (EditText) findViewById(R.id.edit_text_task);
        Button OKbutton = (Button) findViewById(R.id.ok_Button);
        final EditText editTextDate = (EditText) findViewById(R.id.EditText01);

        OKbutton.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                ArrayList<String> addedDatas = new ArrayList<String>();

                String addingTask = editTextTask.getText().toString();

                String deadline = editTextDate.getText().toString();

                //String concatenate = priority + "   " + addingTask + "   " +  deadline;

                Intent myIntent = new Intent();

                addedDatas.add(addingTask);
                addedDatas.add(deadline);
                addedDatas.add(priority);

                myIntent.putExtra("addingTask", addedDatas);

                setResult(Activity.RESULT_OK, myIntent);

                finish();
            }
        });
    }

}

ToDoItem class

public class ToDoItem {

    String task;
    String deadline;
    String status;
    String priority;

    public ToDoItem(String task, String deadline, String status, String priority) {
        super();
        this.task = task;
        this.deadline = deadline;
        this.status = status;
        this.priority = priority;
    }

    public String getTask() {
        return task;
    }

    public String getDeadline() {
        return deadline;
    }

    public String getStatus() {
        return status;
    }

    public String getPriority() {
        return priority;
    }

    @Override
    public String toString() {

        return priority +  "   " + task + "   " + deadline + "   " + status;
    }

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-23 06:52

What you should do, is make sure that the Adding Activity can access the ToDoItem Array that is used to populate the ListView in the Main Activity. Then it can just add to or modify this list directly. Then you can call a notifyAdapters() in onStart() of MainActivity to check for updates whenever it becomes visible.

查看更多
登录 后发表回答