не отображается отображение данных sqlite во фрагменте - PullRequest
0 голосов
/ 29 ноября 2018

Код

public class UsageSettings2 extends Fragment {
MainData mDatabaseHelper;
RecyclerView mRecyclerView;
UserDataHelper mHelper;
private List<UsageHelper> usage = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private UsageAdapter mAdapter;
SQLiteDatabase db;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView =  inflater.inflate(R.layout.settings_usage2, container, false);

    final MainData myDBHlpr = new MainData(getActivity());
    db = myDBHlpr.getWritableDatabase();

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.usagelist);
        //Add the data first
        linearLayoutManager = new LinearLayoutManager(getActivity());
        //and then create a object and pass the lis
        mAdapter = new UsageAdapter(usage);

    mRecyclerView.setLayoutManager(linearLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();

    Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
    while (csr.moveToNext()) {

        String name = csr.getString(csr.getColumnIndex("Name"));
        int sent = csr.getInt(csr.getColumnIndex("MessagesSent"));
        int recieved = csr.getInt(csr.getColumnIndex("MessagesRecieved"));
        int total = csr.getInt(csr.getColumnIndex("Messages"));
        String time = csr.getString(csr.getColumnIndex("TimeSpent"));

        new UsageHelper(name,sent,recieved,total,time);


        int profile_counts = myDBHlpr.getProfilesCount2();
        Log.d("FFF", String.valueOf(profile_counts));


    }



        return rootView;
    }
}

Адаптер

public class UsageAdapter extends RecyclerView.Adapter<UsageAdapter.UsageViewHolder>{

private List<UsageHelper> mUsageHelper;

public UsageAdapter(List<UsageHelper> UsageAdapter) {
    this.mUsageHelper = UsageAdapter;
}

public class UsageViewHolder extends RecyclerView.ViewHolder{
    public TextView mName;
    public TextView mSent;
    public TextView mRecieved;
    public TextView mTotal;
    public TextView mTime;

    public UsageViewHolder(View view) {
        super(view);
        mName = (TextView)view.findViewById(R.id.name);
        mSent = (TextView)view.findViewById(R.id.sent);
        mRecieved = (TextView)view.findViewById(R.id.recieved);
        mTotal = (TextView)view.findViewById(R.id.total);
        mTime = (TextView)view.findViewById(R.id.time);
    }
}

@Override
public UsageAdapter.UsageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_usage,parent,false);
    return new UsageAdapter.UsageViewHolder(V);
}

@Override
public void onBindViewHolder(final UsageViewHolder holder, int position) {
    final UsageHelper usageHelper = mUsageHelper.get(position);

    holder.mName.setText(usageHelper.getName());
    holder.mSent.setText(usageHelper.getSent());
    holder.mRecieved.setText(usageHelper.getRecieved());
    holder.mTotal.setText(usageHelper.getTotal());
    holder.mTime.setText(usageHelper.getTime());

}


@Override
public  int getItemCount() {
    return mUsageHelper.size();
}

Модальный

public class UsageHelper {
private String Name;
private int Sent;
private int Recieved;
private int Total;
private String Time;

public UsageHelper() {
}

public UsageHelper(String Name, int Sent ,int Recieved, int Total, String Time) {

    this.Name = Name;
    this.Sent = Sent;
    this.Recieved = Recieved;
    this.Total = Total;
    this.Time = Time;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    this.Name = name;
}

public int getSent() {
    return Sent;
}

public void setSent(int sent) {
    this.Sent = sent;
}

public int getRecieved() {
    return Recieved;
}

public void setRecieved(int recieved) {
    this.Recieved = recieved;
}

public String getTime() {
    return Time;
}

public void setTime(String time) {
    this.Time = time;
}

public int getTotal() {
    return Total;
}

public void setTotal(int total) {
    this.Total = total;
}

}

Проблема в том, что он ничего не показывает ..Фрагмент пуст, когда я открываю его, хотя данные присутствуют ... Любая идея, почему он теперь показывает какие-либо данные?Я не получаю никакой ошибки только, что данные не показывают ..........................................................................

Получена ошибка после внесения изменений в соответствии с ответами

Пользовательский

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/usage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black">

<RelativeLayout
    android:weightSum="1"
    android:id="@+id/linear"
    android:padding="1dp"
    android:background="@color/white"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:textSize="15dp"
        android:layout_toLeftOf="@+id/mid"
        android:text="Name"
        android:layout_alignParentStart="true"
        android:id="@+id/name"
        android:paddingVertical="10dp"
        android:background="@color/black"
        android:gravity="center_horizontal"
        android:textColor="@color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />



    <TextView
        android:id="@+id/sent"
        android:layout_toRightOf="@id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/black"
        android:gravity="center_horizontal"
        android:paddingVertical="10dp"
        android:text="Sent"
        android:textColor="@color/white"
        android:textSize="15dp" />

    <TextView
        android:id="@+id/recieved"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/sent"
        android:background="@color/black"
        android:gravity="center_horizontal"
        android:paddingVertical="10dp"
        android:text="Recieved"
        android:textColor="@color/white"
        android:textSize="15dp" />

    <TextView
        android:id="@+id/total"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/recieved"
        android:background="@color/black"
        android:gravity="center_horizontal"
        android:paddingVertical="10dp"
        android:text="Total"
        android:textColor="@color/white"
        android:textSize="15dp" />

    <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/recieved"
        android:background="@color/black"
        android:gravity="center_horizontal"
        android:paddingVertical="10dp"
        android:text="Time \nSpent"
        android:textColor="@color/white"
        android:textSize="15dp" />


</RelativeLayout>

Ответы [ 3 ]

0 голосов
/ 29 ноября 2018

Список usage всегда пуст, потому что вы не добавляете новый «UsageHelper», который вы создаете из курсора, в список.

Вам нужно сделать следующее:

Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
while (csr.moveToNext()) {

    ...

    UsageHelper newListItem = new UsageHelper(name,sent,recieved,total,time);
    usage.add(newListItem);

    ...

}
mAdapter.notifyDataSetChanged();

Когда вы закончите добавлять элементы в список, вы захотите уведомить свой адаптер, что в списке есть новые элементы, поэтому вам нужно позвонить на mAdapter.notifyDataSetChanged(); и новые элементы будут отображаться

0 голосов
/ 29 ноября 2018

добавить mAdapter.notifyDataSetChanged ();в то время как условие или после добавления ваших данных в классе модели.

0 голосов
/ 29 ноября 2018

В цикле while onCreateView() добавьте каждую строку из БД в список:

usage.add(new UsageHelper(name,sent,recieved,total,time));

вместо просто:

new UsageHelper(name,sent,recieved,total,time)

, который ничего не делает.И после завершения цикла:

mAdapter.notifyDataSetChanged();

, поэтому RecyclerView загружает все добавленные строки в список. Редактировать Замените

holder.mSent.setText(usageHelper.getSent());

на

holder.mSent.setText("" + usageHelper.getSent());

, поскольку usageHelper.getSent() равно int и обрабатывается как идентификатор ресурса.

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