如何在ListView中显示Android数据库数据?

时间:2014-04-01 14:32:35

标签: android database listview layout

我制作的应用程序在其主要布局数据库数据中显示,其中包含两种字符串:标题和作者。

我设法使用第二种布局来注册这些数据,但无法设法显示它们。

这是我的databaseHelper类:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;

// Statement SQL (database creation)
private static final String DATABASE_CREATE = "create table book (_id integer primary key autoincrement, title text not null, author text not null);";

// Constructor
public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// This method is called during database creation
@Override
public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
}

// This method is called during database upgrade, for example while incremented version number
@Override
public void onUpgrade( SQLiteDatabase database, int oldVersion, int newVersion ) {

        database.execSQL("DROP TABLE IF EXISTS book");
        onCreate(database);

}
}

这是我的DbAdapter:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DbAdapter {
@SuppressWarnings("unused")
private static final String LOG_TAG = DbAdapter.class.getSimpleName();

private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;

// Database fields
private static final String DATABASE_TABLE = "book";

public static final String KEY_BOOKID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";

public DbAdapter(Context context) {
  this.context = context;
}

public DbAdapter open() throws SQLException {
  dbHelper = new DatabaseHelper(context);
  database = dbHelper.getWritableDatabase();
  return this;
}

public void close() {
  dbHelper.close();
}

private ContentValues createContentValues(String title, String author ) {
  ContentValues values = new ContentValues();
  values.put( KEY_TITLE, title );
  values.put( KEY_AUTHOR, author ); 
  return values;
}

//create a book
public long createBook(String title, String author ) {
  ContentValues initialValues = createContentValues(title, author);
  return database.insertOrThrow(DATABASE_TABLE, null, initialValues);
}

//update a book
public boolean updateBook( long bookID, String title, String author ) {
  ContentValues updateValues = createContentValues(title, author);
  return database.update(DATABASE_TABLE, updateValues, KEY_BOOKID + "=" + bookID, null) > 0;
}

//delete a book      
public boolean deleteBook(long bookID) {
  return database.delete(DATABASE_TABLE, KEY_BOOKID + "=" + bookID, null) > 0;
}

//fetch all books
public Cursor fetchAllBooks() {
  return database.query(DATABASE_TABLE, new String[] { KEY_BOOKID, KEY_TITLE, KEY_AUTHOR }, null, null, null, null, null);
}

//fetch books filter by a string
public Cursor fetchBooksByFilter(String filter) {
  Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
                                  KEY_BOOKID, KEY_TITLE, KEY_AUTHOR },
                                  KEY_TITLE + " like '%"+ filter + "%'", null, null, null, null, null);

  return mCursor;
}
}

然后,我的主要活动:

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements ActionBar.TabListener {

    Button newbook_btn;
ListView BookList;
private Cursor cursor;
private DbAdapter dbHelper;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
 * derivative, which will keep every loaded fragment in memory. If this
 * becomes too memory intensive, it may be best to switch to a
 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);
    newbook_btn =(Button)findViewById(R.id.newbook_btn);
    newbook_btn.setOnClickListener(
            new View.OnClickListener()
            {
                    public void onClick(View aView)
                    {
                           Intent toAnotherActivity = new Intent(aView.getContext(), NewbookActivity.class);
                           startActivityForResult(toAnotherActivity, 0);
                    }
            }
    );
    ListView BookList = (ListView)findViewById(R.id.listView1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
        // below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

}

最后,我的上一个活动(将新数据注册到数据库中):

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.***.DatabaseHelper;
import com.***.DbAdapter;

public class NewbookActivity extends MainActivity {

private DbAdapter dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_newbook);
    dbHelper = new DbAdapter(this);
    Button addnewbook_btn = (Button) findViewById(R.id.button1);

    addnewbook_btn.setOnClickListener(
        new View.OnClickListener() {
            public void onClick(View aView) {
                dbHelper.open();
                EditText editTextTitle = (EditText)findViewById(R.id.editText1);
                String TitleValue = editTextTitle.getText().toString();
                EditText editTextAuthor = (EditText)findViewById(R.id.editText2);
                String AuthorValue = editTextAuthor.getText().toString();
                if (TitleValue.matches("") && AuthorValue.matches("")){
                    Toast.makeText(NewbookActivity.this, "You didn't entered the book info", Toast.LENGTH_SHORT).show();
                    return;
                }else if (TitleValue.matches("")) {
                    Toast.makeText(NewbookActivity.this, "You didn't entered the book Title", Toast.LENGTH_SHORT).show();
                    return;
                }else if (AuthorValue.matches("")) {
                    Toast.makeText(NewbookActivity.this, "You didn't entered the book Author", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    dbHelper.createBook(TitleValue, AuthorValue);
                    dbHelper.close();
                    Toast.makeText(NewbookActivity.this, "The book has correctly added", Toast.LENGTH_SHORT).show();
                    Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
                    startActivityForResult(toAnotherActivity, 0);
                }
            }
        }
    );
}

}

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

您需要一种方法来创建List<String>来自Cursor的{​​{1}}。

DBAdapter

然后,您需要创建一个适配器来帮助填充public List<String> cursorToList(Cursor c) { List<String> data = new ArrayList<String>(); if (c.getCount() > 0) { while (c.moveToNext()) { data.add(/*String created from c*/); } } return data; } 。此适配器将存储您的ListView以及显示它的格式。

List<String>

最后,您需要将此适配器设置为/* In the onCreate method of MainActivity*/ ArrayAdapter<String> adapter = new ArrayAdapter<>(/*context*/this, android.R.layout.simple_list_item_1, cursorToList(/*get your cursor here*/dbHelper.fetchAllBooks())); ,您就完成了。

ListView

这是一个基本的BookList.setAdapter(adapter); ,它会为每个对象显示ListView。对于更加自定义的String,您可以扩展ListView类。