在刷新之前,android无法清除listview中的数据

时间:2012-09-26 08:43:44

标签: android listview android-arrayadapter

我有一个显示交易列表的应用。当我点击一个按钮来获得第二天的交易时,列表视图仍然会附加前一天的交易。如何在getView重新填充之前清除数组或适配器?

我已经尝试过clear()和adapter.notifyDataSetChanged()但它仍然不起作用。

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

         setCurrentDateOnView();


        Log.e(TAG, "title = " + getTitle());
        Log.e(TAG, "super.title = " + super.getTitle());
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        date = nfcscannerapplication.getDate();
        listView = (ListView) findViewById(R.id.rotalist);
        intent = this.getIntent();
        Bundle bundle = intent.getBundleExtra("rotaArrayBundle");
        if(array != null){
            array.clear();
        }
        array = (ArrayList<?>) bundle.get("rotaArray");

        arrayAdapter = new MySimpleArrayAdapter(this, array);
        arrayAdapter.notifyDataSetChanged();

        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(this);

。[更新]

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

         setCurrentDateOnView();


        Log.e(TAG, "title = " + getTitle());
        Log.e(TAG, "super.title = " + super.getTitle());
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        date = nfcscannerapplication.getDate();
        listView = (ListView) findViewById(R.id.rotalist);
        intent = this.getIntent();
        Bundle bundle = intent.getBundleExtra("rotaArrayBundle");

        array = (ArrayList<?>) bundle.get("rotaArray");

        if (arrayAdapter == null){

        arrayAdapter = new MySimpleArrayAdapter(this, array);
        }else{

            ((MySimpleArrayAdapter)getListAdapter()).clear();

        }

        for(YourListItem item : yourNewDataArray){
            ((MySimpleArrayAdapter)getListAdapter()).add(item);
        }



        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(this);


    }// end of onCreate

    private MySimpleArrayAdapter getListAdapter() {
        // TODO Auto-generated method stub
        return arrayAdapter;
    }

。 [UPDATE2]

public class GetRota extends NfcBaseActivity implements OnItemClickListener {

    private static final String TAG = GetRota.class.getSimpleName();
    ListView listView;
    Intent intent;
    String callID;
    DateTime date;
    NfcScannerApplication nfcscannerapplication;
    ArrayList<?> array;
    String needName = "";
    MySimpleArrayAdapter arrayAdapter;
    private DatePicker dpResult;
    private int year;
    private int month;
    private int day;

    static final int DATE_DIALOG_ID = 999;

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

         setCurrentDateOnView();


        Log.e(TAG, "title = " + getTitle());
        Log.e(TAG, "super.title = " + super.getTitle());
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        date = nfcscannerapplication.getDate();
        listView = (ListView) findViewById(R.id.rotalist);
        intent = this.getIntent();
        Bundle bundle = intent.getBundleExtra("rotaArrayBundle");

        array = (ArrayList<?>) bundle.get("rotaArray");

        if (arrayAdapter == null){

        arrayAdapter = new MySimpleArrayAdapter(this, array);
        }else{

            ((MySimpleArrayAdapter)getListAdapter()).clear();

        }

//      for(YourListItem item : yourNewDataArray){
//          ((MySimpleArrayAdapter)getListAdapter()).add(item);
//      }



        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(this);


    }// end of onCreate

    private MySimpleArrayAdapter getListAdapter() {

        return arrayAdapter;
    }

    public void setCurrentDateOnView() {

        dpResult = (DatePicker) findViewById(R.id.datepicker1);

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);


    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menurotadetails, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.previous:
            DateTime now2 = nfcscannerapplication.getDate();
            Log.e(TAG, "now2 = " + now2);
            DateTime dateTimePlusOne2 = now2.minusDays(1);
            Log.e(TAG, "now2 after -1 = " + dateTimePlusOne2);
            nfcscannerapplication.setDate(dateTimePlusOne2);
            DateTimeFormatter fmt2 = DateTimeFormat.forPattern("d-MMM-Y");
            String nextDay2 = fmt2.print(dateTimePlusOne2);

            Intent i2 = new Intent(this, NfcscannerActivity.class);
            i2.putExtra("nextRota", nextDay2);
            i2.setAction("NEXT_ROTA");
            startActivity(i2);
            return true;

        case R.id.next:

            DateTime now = nfcscannerapplication.getDate();
            Log.e(TAG, "now = " + now);
            DateTime dateTimePlusOne = now.plusDays(1);
            Log.e(TAG, "now after +1 = " + dateTimePlusOne);
            nfcscannerapplication.setDate(dateTimePlusOne);
            DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
            String nextDay = fmt.print(dateTimePlusOne);

            Intent i = new Intent(this, NfcscannerActivity.class);
            i.putExtra("nextRota", nextDay);
            i.setAction("NEXT_ROTA");
            startActivity(i);
            return true;

        case R.id.today:
            setCurrentDateOnView();
            showDialog(DATE_DIALOG_ID);
            return true;

        default:

            return super.onOptionsItemSelected(item);
        }
    }






    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            return new DatePickerDialog(this, datePickerListener, year, month,
                    day);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;



            DateTime spinnyTime = new DateTime(year, month+1, day, 1, 1);
            Log.e(TAG, "spinnyTime = " + spinnyTime);
            DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
            String formattedSpinnyTime = fmt.print(spinnyTime);
            Log.e(TAG, "spinnyTime = " + formattedSpinnyTime);
            Log.e(TAG, "year = " + year);
            Log.e(TAG, "month = " + month);
            Log.e(TAG, "day = " + day);


            Intent i = new Intent(GetRota.this, NfcscannerActivity.class);
            i.putExtra("nextRota", formattedSpinnyTime);
            i.setAction("NEXT_ROTA"); 
            startActivity(i);

        }
    };








    private class MySimpleArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final ArrayList<?> list;

        public MySimpleArrayAdapter(Context context, ArrayList<?> list) {

            super(context, R.layout.rotarowlayout);
            Log.e(TAG, "inside adapter constructor");
            this.context = context;
            this.list = list;

            if(list.get(6).toString().equalsIgnoreCase("Out of range")){

                AlertDialog alertDialog = new AlertDialog.Builder(GetRota.this).create();
                alertDialog.setTitle("No Rota Available Error");
                alertDialog.setMessage("Unable To View Rota For That Day");
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {



                    } }); 

                alertDialog.show();
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.rotarowlayout, parent,
                    false);

            TextView startTime = (TextView) rowView
                    .findViewById(R.id.rowstarttime);
            TextView duration = (TextView) rowView
                    .findViewById(R.id.rowduration);
            TextView status = (TextView) rowView.findViewById(R.id.rowstatus);
            TextView name = (TextView) rowView.findViewById(R.id.rowclientname);

            String record = list.get(position).toString();
            String[] itemsInRecord = record.split(",");
            Log.e(TAG, "itemin record = " + itemsInRecord.length);
            String[] recordItem = new String[itemsInRecord.length];

            for (int x = 0; x < itemsInRecord.length; x++) {

                recordItem[x] = itemsInRecord[x];
                Log.e(TAG, "x = " + x);
            }

            startTime.setText("Start Time: " + recordItem[0]);
            duration.setText("Duration:" + recordItem[1]);
            status.setText("Status:" + recordItem[2]);
            name.setText("Client:" + recordItem[3] + recordItem[4]);
            callID = recordItem[5];
            needName = recordItem[6];

            return rowView;

        }

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

    }// end of adapter class

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

        Log.e(TAG, "inside onItemClick");

        Intent intent = new Intent(GetRota.this, GetRotaDetails.class);
        intent.putExtra("callIDExtra", callID);

        startActivity(intent);

    }

}// end of GetRota

[UPDATE3]

@Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        super.onNewIntent(intent);

        // Get your ArrayList from getIntent.getExtras() here, and use my code from above
        Bundle bundle = intent.getBundleExtra("rotaArrayBundle");
        array = (ArrayList<?>) bundle.get("rotaArray");
    }


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

         setCurrentDateOnView();


        Log.e(TAG, "title = " + getTitle());
        Log.e(TAG, "super.title = " + super.getTitle());
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        date = nfcscannerapplication.getDate();
        listView = (ListView) findViewById(R.id.rotalist);
        onNewIntent(intent);
        //intent = this.getIntent();
        //Bundle bundle = intent.getBundleExtra("rotaArrayBundle");

        //array = (ArrayList<?>) bundle.get("rotaArray");

        if (arrayAdapter == null){

        arrayAdapter = new MySimpleArrayAdapter(this, array);
        }else{

            ((MySimpleArrayAdapter)getListAdapter()).clear();

        }

//      for(YourListItem item : yourNewDataArray){
//          ((MySimpleArrayAdapter)getListAdapter()).add(item);
//      }



        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(this);


    }// end of onCreate

2 个答案:

答案 0 :(得分:4)

您应该保留旧适配器,每当您想要更新列表时,您可以执行以下操作:

((MySimpleArrayAdapter)getListAdapter()).clear();
for(String[] item : array){
    ((MySimpleArrayAdapter)getListAdapter()).add(item);
}

您也不必致电notifyDataSetChange(),因为clear()add()会为您做好准备。

编辑:在您的活动的清单XML中设置android:launchMode="singleTop",然后覆盖onNewIntent()方法,如下所示:

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    super.onNewIntent(intent);
}

<强> EDIT2:

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    super.onNewIntent(intent);
}


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

     setCurrentDateOnView();


    Log.e(TAG, "title = " + getTitle());
    Log.e(TAG, "super.title = " + super.getTitle());
    nfcscannerapplication = (NfcScannerApplication) getApplication();
    date = nfcscannerapplication.getDate();
    listView = (ListView) findViewById(R.id.rotalist);


    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(this);


}

@Override
protected void onResume(){
    super.onResume();
    ArrayList<String[]> array = (ArrayList<String[]>)getIntent().getBundleExtra("rotaArrayBundle").get("rotaArray"); 
    MySimpleArrayAdapter arrayAdapter = new MySimpleArrayAdapter(this, array);
    listView.setAdapter(arrayAdapter)
}

[更新4]

    for(int i = 0; i < count; i++){

                String s = new Integer(i).toString();

                 JSONObject jsonobject2 = (JSONObject) jsonObject1.get(s);
                 String startdate = jsonobject2.getString("StartDate");
                 String duration = jsonobject2.getString("Duration");
                 String callStatusName = jsonobject2.getString("CallStatusName");
                 String clientForeName = jsonobject2.getString("ClientForename");
                 String clientSurName = jsonobject2.getString("ClientSurname");
                 String clientCallId = jsonobject2.getString("CallID");
                 String needName = jsonobject2.getString("NeedName");

                 ArrayList<String> arr = new ArrayList<String>();
                 arr.add(startdate);
                 arr.add(duration);
                 arr.add(callStatusName);
                 arr.add(clientForeName);
                 arr.add(clientSurName);
                 arr.add(clientCallId);
                 arr.add(needName);

                 Log.e(TAG, "arr size = "+arr.size());
                arrayList.add(i, arr);

                }

            } catch (Exception e) {

                e.printStackTrace();
            }
            return arrayList;


class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {

        private static final long serialVersionUID = 1L;

        public void addToInnerArray(int index, T element) {
            while (index >= this.size()) {
                this.add(new ArrayList<T>());
            }
            this.get(index).add(element);
        }

        public void addToInnerArray(int index, int index2, T element) {
            while (index >= this.size()) {
                this.add(new ArrayList<T>());
            }

            ArrayList<T> inner = this.get(index);
            while (index2 >= inner.size()) {
                inner.add(null);
            }

            inner.set(index2, element);
        }
    }

答案 1 :(得分:0)

请您尝试更改订单。

listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();