简体   繁体   English

将SQLite数据库中的数据加载到ListView中

[英]Loading data from SQLite Database into ListView

I'm trying to load data from SQLite DB in Android and set its values into a ListView. 我正在尝试从Android中的SQLite DB加载数据并将其值设置为ListView。 The problem is, when I load the data in OnCreate, it doesn't show anything but when I refresh the app it shows the data. 问题是,当我在OnCreate中加载数据时,它没有显示任何内容,但是当我刷新应用程序时它显示数据。

Please help me to fix this problem ! 请帮我解决这个问题!

Load tasks code: 加载任务代码:

public void loadTasks() {

    Cursor c = notesDb.rawQuery("SELECT * FROM notes", null);
    int titleIndex = c.getColumnIndex("title");
    int contentIndex = c.getColumnIndex("content");
    int dateIndex = c.getColumnIndex("date");
    int idIndex = c.getColumnIndex("object");
    if (c.moveToFirst()) {
        if (!titles.isEmpty()) {
            titles.clear();
        }
        if (!content.isEmpty()) {
            content.clear();
        }
        if (!dates.isEmpty()) {
            dates.clear();
        }
        if (!objectId.isEmpty()) {
            objectId.clear();
        }

        do {
            titles.add(c.getString(titleIndex));
            content.add(c.getString(contentIndex));
            dates.add(c.getString(dateIndex));
            objectId.add(c.getString(idIndex));

            Log.i("Title", c.getString(titleIndex));
            Log.i("Content", c.getString(contentIndex));
            Log.i("Date", c.getString(dateIndex));
            Log.i("Id", c.getString(idIndex));

        } while (c.moveToNext());

        tasksList.setAdapter(customAdapter);
        loadingBar.setVisibility(View.INVISIBLE);

    } else {

        if (titles.size() > 0 || content.size() > 0) {
            tasksList.setAdapter(customAdapter);
            loadingBar.setVisibility(View.INVISIBLE);
        } else {
            titles.add("Welcome To App !");
            content.add("Start taking notes by clicking the add button below !");

            final Calendar c1 = Calendar.getInstance();
            final String monthName = new SimpleDateFormat("MMMM").format(c1.getTime());
            dates.add(String.valueOf(monthName + " " + c1.get(Calendar.DAY_OF_MONTH)) + " " + c1.get(Calendar.YEAR));
            objectId.add("randomId");
            tasksList.setAdapter(customAdapter);
            loadingBar.setVisibility(View.INVISIBLE);
        }
    }
}

OnCreate code OnCreate代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dolt);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    loadTasks();

Passing data to adapter in OnCreate: 在OnCreate中将数据传递给适配器:

customAdapter = new CustomAdapter(DoltActivity.this, titles, content, dates);

Custom Adapter code: 定制适配器代码:

public class CustomAdapter extends BaseAdapter{

ArrayList<String> title;
ArrayList<String> contents;
ArrayList<String> dates;
Context context;
private static LayoutInflater inflater=null;
public CustomAdapter(DoltActivity mainActivity, ArrayList<String> titles, ArrayList<String> content, ArrayList<String> date) {
    // TODO Auto-generated constructor stub
    title=titles;
    contents=content;
    dates=date;
    context=mainActivity;
    inflater = ( LayoutInflater )context.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return title.size();
}

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

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

@Override
public int getItemViewType(int position) {
    return CustomAdapter.IGNORE_ITEM_VIEW_TYPE;
}

public static class Holder
{
    TextView tv;
    TextView content;
    TextView date;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder = new Holder();
    View rowView = null;

    rowView = inflater.inflate(R.layout.custom_row, null);

    holder.tv = (TextView) rowView.findViewById(R.id.textView10);
    holder.content = (TextView) rowView.findViewById(R.id.textView3);
    holder.date = (TextView) rowView.findViewById(R.id.textView4);

    holder.tv.setText(title.get(position));
    holder.content.setText(contents.get(position));
    holder.date.setText(dates.get(position));

    rowView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            DoltActivity.tapped = true;
            DoltActivity.id = position;
            Log.i("Position", String.valueOf(position));

            }
        });

    rowView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {

            DoltActivity.longTapped = true;
            DoltActivity.id = position;

            Log.i("Long ", "Tapped");

            return true;
        }
    });


    return rowView;
}

} }

Refresh code: 刷新代码:

swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
                loadTasks();               
            swipeRefresh.setRefreshing(false);
        }
    });

Thanks in advance ! 提前致谢 !

Try this, 试试这个,

1- Initialize your customAdapter inside the loadTask() before setting it to ListView ie before 1-在将loadTask()设置为ListView(即之前loadTask()之前,先在loadTask()初始化customAdapter

customAdapter = new CustomAdapter(getActivity(), titles, content, dates);
tasksList.setAdapter(customAdapter);

There looks like a logical data flow error in your code, you initialized customAdapter after calling loadTask() but inside loadTask() you are using that object without initializing it with updated lists of titles , contents and dates . 在您的代码中看起来像一个逻辑数据流错误,您在调用loadTask()之后初始化了customAdapter ,但在loadTask()内部,您正在使用该对象而不使用更新的标题内容日期列表初始化它。

create your adapter after updating your arrays. 更新阵列后创建适配器。 Move your line: 移动你的线:

 customAdapter = new CustomAdapter(DoltActivity.this, titles, content, dates);

to be before: 以前:

tasksList.setAdapter(customAdapter);

also, you can move below code to be outside your if, just to remove code repetition. 另外,您可以在代码之下移动到if之外,只是为了删除代码重复。 your loadTask function will be as follows: 你的loadTask函数如下:

public void loadTasks() {

Cursor c = notesDb.rawQuery("SELECT * FROM notes", null);
int titleIndex = c.getColumnIndex("title");
int contentIndex = c.getColumnIndex("content");
int dateIndex = c.getColumnIndex("date");
int idIndex = c.getColumnIndex("object");
if (c.moveToFirst()) {
    if (!titles.isEmpty()) {
        titles.clear();
    }
    if (!content.isEmpty()) {
        content.clear();
    }
    if (!dates.isEmpty()) {
        dates.clear();
    }
    if (!objectId.isEmpty()) {
        objectId.clear();
    }

    do {
        titles.add(c.getString(titleIndex));
        content.add(c.getString(contentIndex));
        dates.add(c.getString(dateIndex));
        objectId.add(c.getString(idIndex));

        Log.i("Title", c.getString(titleIndex));
        Log.i("Content", c.getString(contentIndex));
        Log.i("Date", c.getString(dateIndex));
        Log.i("Id", c.getString(idIndex));

    } while (c.moveToNext());

} else {

    if (titles.size() > 0 || content.size() > 0) {

    } else {
        titles.add("Welcome To App !");
        content.add("Start taking notes by clicking the add button below !");

        final Calendar c1 = Calendar.getInstance();
        final String monthName = new SimpleDateFormat("MMMM").format(c1.getTime());
        dates.add(String.valueOf(monthName + " " + c1.get(Calendar.DAY_OF_MONTH)) + " " + c1.get(Calendar.YEAR));
        objectId.add("randomId");

    }
}

customAdapter = new CustomAdapter(DoltActivity.this, titles, content, dates);
tasksList.setAdapter(customAdapter);
loadingBar.setVisibility(View.INVISIBLE);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM