2014-04-01 60 views
0

我正在制作一个应用程序,其主要布局显示数据库数据,其中包含两种字符串:标题和作者。如何在ListView中显示Android数据库数据?

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

这是我的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); 
       } 
      } 
     } 
    ); 
} 

} 

请帮忙吗?

+0

无法看到你把数据放入你的ListView。与之相关的唯一代码是 - ListView BookList =(ListView)findViewById(R.id.listView1);你的初始化? –

+0

你想在哪里显示数据?我看不到任何关于此的代码。 –

+0

@AtulOHolic:不知道在哪里可以找到相关的行。你能告诉我怎么做吗? – mackief

回答

0

您需要一种方法,通过DBAdapter获得的Cursor创建List<String>

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,您可以扩展ArrayAdapter类。