2013-11-22 3 views
0

Я пытаюсь получить значение из общего предпочтения и отобразить его в настраиваемом виде списка. Но проблема в том, что просмотр списка не обновляется со вторым значением, означает, что в первый раз он отлично работает нормально, но во второй раз он перезаписывает первое значение или может быть, он открывает другой экран и отображает его там.Данные пользовательского списка Android не обновляются при использовании общих предпочтений

Я хочу добавить все данные общих настроек в виде списка по одному. пожалуйста, помогите мне решить эту проблему. Следующий мой код.

ListModel.java

public class ListModel { 

private String Title = ""; 
private String Description = ""; 

/*********** Set Methods ******************/ 

public void setTitle(String Title) { 
    this.Title = Title; 
} 

public void setDescription(String Description) { 
    this.Description = Description; 
} 

/*********** Get Methods ****************/ 

public String getTitle() { 
    return this.Title; 
} 

public String getDescription() { 
    return this.Description; 
} 
} 

CustomAdapter.java

public class CustomAdapter extends BaseAdapter implements OnClickListener { 

/*********** Declare Used Variables *********/ 
private Activity activity; 
private ArrayList<?> data; 
private static LayoutInflater inflater = null; 
public Resources res; 
ListModel tempValues = null; 

/************* CustomAdapter Constructor *****************/ 
public CustomAdapter(Activity a, ArrayList<?> d, Resources resLocal) { 

    /********** Take passed values **********/ 
    activity = a; 
    data = d; 
    res = resLocal; 

    /*********** Layout inflator to call external xml layout() ***********/ 
    inflater = (LayoutInflater) activity 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

} 

/******** What is the size of Passed Arraylist Size ************/ 
public int getCount() { 

    if (data.size() <= 0) 
     return 1; 
    return data.size(); 
} 

public Object getItem(int position) { 
    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 

/********* Create a holder Class to contain inflated xml file elements *********/ 
public static class ViewHolder { 

    public TextView textViewTitle; 
    public TextView textViewDescr; 
} 

/****** Depends upon data size called for each row , Create each ListView row *****/ 
public View getView(int position, View convertView, ViewGroup parent) { 

    View vi = convertView; 
    ViewHolder holder; 

    if (convertView == null) { 

     /****** Inflate tabitem.xml file for each row (Defined below) *******/ 
     vi = inflater.inflate(R.layout.displaydata, null); 

     /****** View Holder Object to contain tabitem.xml file elements ******/ 

     holder = new ViewHolder(); 
     holder.textViewTitle = (TextView) vi.findViewById(R.id.title); 
     holder.textViewDescr = (TextView) vi.findViewById(R.id.description); 

     /************ Set holder with LayoutInflater ************/ 
     vi.setTag(holder); 
    } else 
     holder = (ViewHolder) vi.getTag(); 

    if (data.size() <= 0) { 
     holder.textViewTitle.setText("No Data"); 

    } else { 
     /***** Get each Model object from Arraylist ********/ 
     tempValues = null; 
     tempValues = (ListModel) data.get(position); 

     /************ Set Model values in Holder elements ***********/ 

     holder.textViewTitle.setText(tempValues.getTitle()); 
     holder.textViewDescr.setText(tempValues.getDescription()); 
     // holder.image.setImageResource(res.getIdentifier(
     // "com.androidexample.customlistview:drawable/" 
     // + tempValues.getImage(), null, null)); 

     /******** Set Item Click Listner for LayoutInflater for each row *******/ 

     vi.setOnClickListener(new OnItemClickListener(position)); 
    } 
    return vi; 
} 

@Override 
public void onClick(View v) { 
    Log.v("CustomAdapter", "=====Row button clicked====="); 
} 

/********* Called when Item click in ListView ************/ 
private class OnItemClickListener implements OnClickListener { 
    private int mPosition; 
    OnItemClickListener(int position) { 
     mPosition = position; 
    } 

    @Override 
    public void onClick(View arg0) { 
     Assignment sct = (Assignment) activity; 
     sct.onItemClick(mPosition); 
    } 
} 
} 

класс, который читает общий preferencedata

public class Assignment extends Activity { 

ListView list; 
ImageView imageView; 
CustomAdapter adapter; 
public Assignment CustomListView = null; 
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.assignment); 

    imageView = (ImageView) findViewById(R.id.createassignment); 
    list = (ListView) findViewById(R.id.displaydata); 

    CustomListView = this; 
    setListData(); 
    Resources res = getResources(); 

    adapter = new CustomAdapter(CustomListView, CustomListViewValuesArr, 
      res); 
    list.setAdapter(adapter); 

    imageView.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      Intent intent = new Intent(Assignment.this, 
        Assignment_Create.class); 
      startActivity(intent); 
     } 
    }); 
} 

public void setListData() { 

    final ListModel sched = new ListModel(); 

    /******* Firstly take data in model object ******/ 
    sched.setTitle("Title : " 
      + PreferenceConnector.readString(this, 
        PreferenceConnector.TITLE, null)); 
    sched.setDescription("Description : " 
      + PreferenceConnector.readString(this, 
        PreferenceConnector.DESC, null)); 

    /******** Take Model Object in ArrayList **********/ 
    CustomListViewValuesArr.add(sched); 
} 

public void onItemClick(int mPosition) { 
    ListModel tempValues = (ListModel) CustomListViewValuesArr 
      .get(mPosition); 
    Toast.makeText(
      CustomListView, 
      "" + tempValues.getTitle() + "" + "" 
        + tempValues.getDescription(), Toast.LENGTH_LONG) 
      .show(); 
} 
} 

Эта функция показывает, как я пишу данные в общей Preference

public void sharedPrefernces() { 
    if (Code.title != null) 
     PreferenceConnector.writeString(this, PreferenceConnector.TITLE, 
       Code.title); 
    if (Code.description != null) 
     PreferenceConnector.writeString(this, PreferenceConnector.DESC, 
       Code.description); 
} 

ответ

0

В setListData() вы добавляете только 1 элемент в адаптер, поэтому в спискеView не будет показан второй элемент.

+0

Hello Quentin DOMMERC, поэтому какие изменения мне нужно сделать ??? вы можете просто предложить пожалуйста. – InnocentKiller

+0

@ user2846106 вам нужно добавить новые данные в список. затем вызовите 'adapter.notifyDataSetChanged()' – Raghunandan

+0

Как сказал @Raghunandan, вы хотите 2 предмета? Добавьте 2 предмета. Вы уже добавили его, просто добавьте еще один из них перед списком list.setAdapter (yourAdapter) или после установки адаптера, вызвав notifyDadaSetChanged() из адаптера. –

Смежные вопросы