2016-07-14 63 views
0

我正在嘗試使用listactivity,我將項目添加到listview行。但是當我加載不同的數據來添加列表視圖中的項目時,它會重複之前添加的相同項目。Android Listview項目重複添加具有不同數據的新項目

這裏是我的baseadapter類:

public class MyNotiAdapter extends BaseAdapter { 

    Context context; 
    String[] data; 
    String time; 
    String Name ; 
    String Number; 

    private static LayoutInflater inflater = null; 
    public MyNotiAdapter(Context context, String[] data,String time, String Name ,String Number) { 
     // TODO Auto-generated constructor stub 
     this.context = context; 
     this.data = data; 
     this.time = time; 
     this.Name = Name; 
     this.Number=Number; 
     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return data.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return data[position]; 
    } 

    @Override 
    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return position; 
    } 

    @Override 
    public int getViewTypeCount() { 

    return getCount(); 
    } 

    @Override 
    public int getItemViewType(int position) { 

    return position; 
    } 

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

     ViewHolder mHolder; 
     View vi = convertView; 
     if (vi == null){ 
      vi = inflater.inflate(R.layout.row2, null); 

     mHolder = new ViewHolder(); 
     mHolder.text= (TextView) vi.findViewById(R.id.lablel); 
     mHolder.Nameo = (TextView) vi.findViewById(R.id.person); 
     mHolder.Numbero = (TextView) vi.findViewById(R.id.edu); 
     mHolder.Time = (TextView) vi.findViewById(R.id.tym); 
     vi.setTag(mHolder); 



     mHolder.text.setText(data[position]); 
     mHolder.Nameo.setText(Name); 
     mHolder.Numbero.setText(Number); 
     mHolder.Time.setText(time); 

    }else { 
      mHolder = (ViewHolder) convertView.getTag(); 
     } 

     return vi; 
    } 


    public class ViewHolder { 
     public TextView text; 
     public TextView Nameo; 
     public TextView Numbero; 
     public TextView Time; 


    } 


} 

,這裏是在我設置適配器數據的活動......

public class noticall extends ListActivity { 


    CustomDateTimePicker custom; 
    TextView tv,tv1; 
    EditText ed; 
    String store; 
    static String Names; 
    public static final int PICK_CONTACT = 1; 
    String [] adi ; 
    static int incre=0; 
    ArrayList<String> myrows = new ArrayList<String>(); 
    private PendingIntent pendingIntent; 
    ListView listview; 
    String temp1 ,temp2 ; 
    int x=0; 
    OnItemClickListener listener; 
    String Date,Time,Name,Number; 
    MyNotiAdapter adp; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.notify); 
      listview = (ListView) findViewById(android.R.id.list); 

      listview.setDividerHeight(5); 


      custom = new CustomDateTimePicker(noticall.this,new CustomDateTimePicker.ICustomDateTimeListener() { 

       @Override 
       public void onCancel() { 
        finish(); 
       } 


       @Override 
       public void onSet(Dialog dialog, Calendar calendarSelected,Date dateSelected, int year, String monthFullName, 
          String monthShortName, int monthNumber, int date, 
          String weekDayFullName, String weekDayShortName, 
          int hour24, int hour12, int min, int sec, 
          String AM_PM) { 

         Calendar calendar = Calendar.getInstance(); 
         calendar.set(year, monthNumber, date, hour24, min, 0); 

         long when = calendar.getTimeInMillis();   // notification time 

         Intent myIntent = new Intent(noticall.this, MyReceiver.class); 
         pendingIntent = PendingIntent.getBroadcast(noticall.this, 0, myIntent,0); 

         AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
         alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); 



     //temp1= store =calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" + 
    // year + ", " + hour12 + ":" + min + " " + AM_PM; 


     Date = calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" +year; 
     Time = hour12 + ":" + min + " " + AM_PM; 

     Log.e("Timeee", Time+""); 


     setlisto(Date); 

     Toast.makeText(noticall.this, store, Toast.LENGTH_SHORT).show(); 

      } 
    });  


     /* 
      Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
      startActivityForResult(intent,PICK_CONTACT); 

      /** 
      * Pass Directly current time format it will return AM and PM if you set 
      * false 
      */ 
      custom.set24HourFormat(false); 
      /** 
      * Pass Directly current data and time to show when it pop up 
      */ 
      custom.setDate(Calendar.getInstance()); 

      //custom.showDialog(); 


       findViewById(R.id.button_date).setOnClickListener(
        new OnClickListener() { 
         @Override 
         public void onClick(View v) { 
         Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
         startActivityForResult(intent,PICK_CONTACT); 
         custom.showDialog(); 
         incre++; 
         } 
        }); 

     // ((BaseAdapter) listview.getAdapter()).notifyDataSetChanged() ; 
     // listview.getAdapter().notifyAll(); 
    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 

     if(resultCode != RESULT_CANCELED){ 

      if (requestCode == 1) 
      { 
       // Get the URI that points to the selected contact 
       Uri contactUri = data.getData(); 

       // We only need the NUMBER column, because there will be only one row in the result 
       String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}; 

       String[] segments = contactUri.toString().split("/"); 
       String id = segments[segments.length - 1]; 

       // Perform the query on the contact to get the NUMBER column 
       // We don't need a selection or sort order (there's only one result for the given URI) 
       // CAUTION: The query() method should be called from a separate thread to avoid blocking 
       // your app's UI thread. (For simplicity of the sample, this code doesn't do that.) 
       // Consider using CursorLoader to perform the query. 
       Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); 
       cursor.moveToFirst(); 
       while (!cursor.isAfterLast()) 
       { 
        int cid = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID); 
        String contactid = cursor.getString(cid); 

        if (contactid.equals(id)) 
        { 
         // Retrieve the phone number from the NUMBER column 
         int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 
         String number = cursor.getString(column); 

         // Retrieve the contact name from the DISPLAY_NAME column 
         int column_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
         String name = cursor.getString(column_name); 

         // Do something with the phone number... 
         // Toast.makeText(this, "I added the Contact: \n" + name + " " + number, Toast.LENGTH_SHORT).show(); 

         // ed.setText(name+" - "+number); 

         Name= Names=name; 
         Number =number; 



        } 

       cursor.moveToNext(); 
       } 
       cursor.close(); 

       } 
      } 
     } 


    public void setlisto(String one){ 

    Log.e("setlistoo",one+""); 
    myrows.add(one); 
    adi = myrows.toArray(new String[myrows.size()]); 
    listview.setAdapter(new MyNotiAdapter(noticall.this, adi,Time,Name,Number)); 


    // ((BaseAdapter) listview.getAdapter()).notifyDataSetChanged(); 
    //listview.invalidateViews(); 

    x++; 

    } 

} 

我已經通過提供互聯網上的所有解決方案了。我想我在某個地方犯了一些錯誤。如果有人能找到問題所在......?

我只注意到Data []數組正在用不同的值更新。但其他字符串變量覆蓋每個項目添加..爲什麼會發生這種情況?

+0

您可以提供myrows對象類? – faruk

+0

編輯並添加了類 –

+0

@AlZill我認爲當將新數據添加到適配器時,它將添加新的數據添加到以前添加的項目中。 –

回答

0

好的,我有我自己解決它。問題是我傳遞簡單的字符串,但我必須傳遞字符串數組,以便將新數據添加到列表視圖。

下面是我所做的更改..

在活動

:在baseadapter類

public void setlisto(String one){ 

    Log.e("setlistoo",one+""); 
    myrows.add(one); 
    time1.add(Time); 
    name1.add(Name); 
    number1.add(Number); 


    adi = myrows.toArray(new String[myrows.size()]); 
    adi1=time1.toArray(new String[time1.size()]); 
    adi2=name1.toArray(new String[name1.size()]); 
    adi3=number1.toArray(new String[number1.size()]); 
    listview.setAdapter(new MyNotiAdapter(noticall.this, adi,adi1,adi2,adi3)); 

    // if(adi!=null) 
     //adp.notifyDataSetChanged(); 

    x++; 

    } 

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

     ViewHolder mHolder; 
     View vi = convertView; 
     if (vi == null){ 
      vi = inflater.inflate(R.layout.row2, null); 

     mHolder = new ViewHolder(); 
     mHolder.text= (TextView) vi.findViewById(R.id.lablel); 
     mHolder.Nameo = (TextView) vi.findViewById(R.id.person); 
     mHolder.Numbero = (TextView) vi.findViewById(R.id.edu); 
     mHolder.Time = (TextView) vi.findViewById(R.id.tym); 
     vi.setTag(mHolder); 



     mHolder.text.setText(data[position]); 
     mHolder.Nameo.setText(Name[position]); 
     mHolder.Numbero.setText(Number[position]); 
     mHolder.Time.setText(time[position]); 

    }else { 
      mHolder = (ViewHolder) convertView.getTag(); 
     } 

     return vi; 
    } 

現在一切順利...它的工作完美。它可能會幫助像我這樣的人。乾杯..

0

我想你需要做的是調用notifyDataSetChanged方法,並在動態添加數據之前調用一個setAdapter。

或者你可以通過這個鏈接http://androidadapternotifiydatasetchanged.blogspot.in/

+0

我試過使用notifydatasetchanged但它沒有幫助..如果你能看到我的代碼。可能你會發現我犯的錯誤。我會感激.. –

1

你的代碼似乎需要重構很多。

  • 好吧首先,創建一個模型對象類,讓說MyReminderObject.java:

    public class MyReminderObject { 
        public String date; 
        public String time; 
        public String name; 
        public String number; 
    } 
    
  • 在適配器:

    添加MyReminderObject的列表。

    private List<MyReminderObject> mList; 
    

    添加一個新的構造:

    public MyNotiAdapter(Context context) { 
        mList = new ArrayList<MyReminderObject>(); 
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 
    

    改變一些方法:

    @Override 
    public int getCount() { 
        return mList.size(); 
    } 
    
    @Override 
    public Object getItem(int position) { 
        return mList.get(position); 
    } 
    

    在你getView方法,改變一些代碼:

    MyReminderObject item = mList.get(position); 
    mHolder.text.setText(item.date); 
    mHolder.Nameo.setText(item.name); 
    mHolder.Numbero.setText(item.number); 
    mHolder.Time.setText(item.time); 
    

    仍然在你的適配器,添加一個函數來添加項目:

    public void addReminder(MyReminderObject item){ 
        mList.add(item); 
        notifyDataSetChanged(); 
    } 
    
  • 在你的活動:

    在你的onCreate():

    listview.setDividerHeight(5); 
    adp = new MyNotiAdapter(noticall.this); 
    listview.setAdapter(adp); 
    

    最後,您setListTo()方法:

    public void setlisto(String one){ 
    
        Log.e("setlistoo",one+""); 
        MyReminderObject newItem = new MyReminderObject(); 
        newItem.date = one; 
        newItem.time = Time; 
        newItem.name = Name; 
        newItem.number = Number; 
    
        adp.addReminder(newItem); 
    
        x++; 
    
    } 
    
+0

我明白你的觀點。是的,我的代碼大致需要重構,但我必須稍後再做。現在我只想讓功能起作用。你的答案很好。它幫助了很多..謝謝 –