Android Адаптер массива клиентов не отображает данные - PullRequest
0 голосов
/ 20 апреля 2020

Привет, сообщество StackOverflow! Мне нужна ваша помощь, чтобы понять следующее поведение:

Я пытался реализовать ListView, для которого каждое представление следует следующей схеме:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLWLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:weightSum="100">


<TextView
    android:id="@+id/noteText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="66.6" />

<LinearLayout
    android:id="@+id/linearVLWLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="33.3"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textcolor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/reminder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textcolor" />

    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/reminder" />

    <TextView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/location" />
</LinearLayout>

Теперь, когда я ' Приписывая элементы к списку, я использую следующий адаптер:

public class MyAdapter extends ArrayAdapter<Note> {

private Context mContext;
private int mResource;

public MyAdapter(@NonNull Context context, int resource, ArrayList<Note> objects) {
    super(context, resource);
    mContext =context;
    mResource=resource;
}

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

    String text = getItem(position).getText();
    String color = getItem(position).getColor();
    String location = getItem(position).getLocation();
    String reminder = getItem(position).getReminder();
    String image = getItem(position).getImage();

    Note note = new Note(text,color,location,reminder,image);

    LayoutInflater inflater = LayoutInflater.from(mContext);
    convertView=inflater.inflate(mResource,parent,false);

    TextView nttxt = (TextView) convertView.findViewById(R.id.noteText);
    TextView ntcolor = (TextView) convertView.findViewById(R.id.textcolor);
    TextView ntrem = (TextView) convertView.findViewById(R.id.reminder);
    TextView ntlocat = (TextView) convertView.findViewById(R.id.location);
    TextView ntimg = (TextView) convertView.findViewById(R.id.image);

    nttxt.setText(text);
    ntcolor.setText(color);
    ntrem.setText(reminder);
    ntlocat.setText(location);
    ntimg.setText(image);
    Log.i("Convert",convertView.toString());
    Log.i("Text",nttxt.toString());
    return convertView;
}

}

Конечным результатом должен быть список заметок вместе с предпочтениями пользователя и местоположением / напоминанием. Пожалуйста, смотрите ниже назначение списка, сделанное по методу OnCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_explorer);
        FloatingActionButton myFab = this.findViewById(R.id.fabAddNote);
        myFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intentNoteEditor = new Intent(getApplicationContext(), NoteEditor.class);
            startActivity(intentNoteEditor);
        }
    });
        ListView notesList = (ListView) findViewById(R.id.listviewNotes);
        Note note1 = new Note("Note1","Col1","Reminder1","Location1","Image1");
        Note note2 = new Note("Note2","Col2","Reminder2","Location2","Image2");
        Note note3 = new Note("Note3","Col3","Reminder3","Location3","Image3");
        Note note4 = new Note("Note4","Col4","Reminder4","Location4","Image4");
        ArrayList<Note> notesArray = new ArrayList<>();
        notesArray.add(note1);
        notesArray.add(note2);
        notesArray.add(note3);
        notesArray.add(note4);
        Log.i("Notes",note1.getText().toString());
        MyAdapter adapter = new MyAdapter(this,R.layout.list_item,notesArray);
        notesList.setAdapter(adapter);
        Log.i("Adapter",adapter.getContext().toString());
}

Что я делаю не так? Любые предложения будут высоко оценены. Заранее спасибо!

1 Ответ

0 голосов
/ 20 апреля 2020

Вы не сохранили список, в который отправляете адаптер, в локальное поле Здесь вы передаете ArrayList<Note> objects через конструктор адаптера, но не сохраняете его локально в каком-либо хранилище.

  • Итак, сначала измените ваш адаптер, чтобы он имел поле ArrayList<Note> и инициализировали его в конструктор.
  • Во-вторых, переопределите адаптер getCount(), чтобы вернуть размер вашего списка.
  • В-третьих: измените ваш getView (), чтобы получить объект Note текущей позиции в list
public class MyAdapter extends ArrayAdapter<Note> {

private Context mContext;
private int mResource;
private ArrayList<Note> mNotes;

    public MyAdapter(@NonNull Context context, int resource, ArrayList<Note> objects) {
        super(context, resource);
        mContext = context;
        mResource = resource;
        mNotes = objects;
    }

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

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

        String text = mNotes.get(position).getText(); 
        String color = mNotes.get(position).getColor();
        String location = mNotes.get(position).getLocation();
        String reminder = mNotes.get(position).getReminder();
        String image = mNotes.get(position).getImage();

       // ....  continue the rest of code.

Надеюсь, что этот адрес решит вашу проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...