如何在Android Listview上显示数据库内容?

时间:2013-09-04 12:47:36

标签: android

我正在处理类似应用程序的联系簿。我有一个数据库,我想在ListView中显示数据。任何人都可以告诉我如何实现这一目标吗?以下是我到目前为止所尝试的内容,

public class Contacts {

    private int id;
    private String name;
    private String phone_number;
    private String email;


    public Contacts()
    {

    }

    public Contacts(int id, String name, String phone_number, String email) 
    {
        this.id = id;
        this.name = name;
        this.phone_number = phone_number;
        this.email = email;
    }

    public Contacts(String name, String phone_number, String email) 
    {
        this.name = name;
        this.phone_number = phone_number;
        this.email = email;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone_number() {
        return phone_number;
    }
    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

}

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "ContactsManager";
    private static final String TABLE_CONTACTS = "contacts";

    private static final String KEY_ID = "id";

    private static final String KEY_NAME = "name";

    private static final String KEY_PH_NO = "phone_number";

    private static final String KEY_EMAIL = "email";


    public DatabaseHandler(Context context) {

        super( context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("

        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"

        + KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";

        db.execSQL(CREATE_CONTACTS_TABLE);

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        onCreate(db);

    }


    public void insertContact(Contacts contacts) 
    {

        SQLiteDatabase db = this.getWritableDatabase();



        ContentValues cv = new ContentValues();

        cv.put(KEY_NAME, contacts.getName()); // Contact Name

        cv.put(KEY_PH_NO, contacts.getPhone_number()); // Contact Phone

        cv.put(KEY_EMAIL, contacts.getEmail()); //Contact  Email



        // Inserting Row

        db.insert(TABLE_CONTACTS, null, cv);

        db.close();

    }


    // Getting All Contacts

    public List<Contacts> getAllContacts() 
    {

    List<Contacts> contactList = new ArrayList<Contacts>();

    // Select All Query

    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;



    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(selectQuery, null);




    // looping through all rows and adding to list

    if (cursor.moveToFirst()) 
    {

    do {

    Contacts contact = new Contacts();

    //contact.setId(Integer.parseInt(cursor.getString(0)));

    contact.setName(cursor.getString(1));

    contact.setPhone_number(cursor.getString(2));

    contact.setEmail(cursor.getString(3));

    // Adding contact to list

    contactList.add(contact);

    } 
    while (cursor.moveToNext());

    }



    // return contact list


    return contactList;
    }
}

public class View_data extends ListActivity {

    DatabaseHandler db = new DatabaseHandler(this);
    Cursor c ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_data);



        db.getWritableDatabase();

        List<Contacts> values = db.getAllContacts();

        ArrayAdapter<Contacts> adapter = new ArrayAdapter<Contacts>(this,
                android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);

          }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.view_data, menu);
        return true;
    }

}

View_data课程中,我尝试显示数据但无法执行此操作。 任何建议将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

您必须将上下文,列表项布局和光标传递到自定义适配器.........

final CustomAdapter adapter = new CustomAdapter(MainActivity.this,
                    R.layout.listitem, cursor);
            list.setAdapter(adapter); 

然后就是如何实现CustomAdapter类,你必须覆盖你的bindView方法。这看起来很复杂,直到你研究它,然后尝试自己做。

 public class CustomAdapter extends CursorAdapter {
        // Cursor cursor;
        Context context;

        public CustomAdapter(Context context, int RId, Cursor cursor) {
            super(context, cursor);
            // this.cursor = cursor;
            this.context = context;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {


            TextView team1 = (TextView) view.findViewById(R.id.listitem_team1);
            team1.setText(cursor.getString(10));
            TextView team2 = (TextView) view.findViewById(R.id.listitem_team2);
            team2.setText(cursor.getString(11));
            TextView date = (TextView) view.findViewById(R.id.listitem_date);
            date.setText(cursor.getString(3));
            TextView city = (TextView) view.findViewById(R.id.listitem_city);
            city.setText(cursor.getString(2));
            TextView time = (TextView) view.findViewById(R.id.listitem_time);
            time.setText(cursor.getString(4));
            TextView ground = (TextView) view.findViewById(R.id.listitem_ground);
            date.setText(cursor.getString(1));}

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(context);
            View v = inflater.inflate(R.layout.listitem, parent, false);
            return v;
        }
    }

您也可以参考此链接http://dj-android.blogspot.in/2012/10/android-show-data-from-sqlite-db-into.html

答案 1 :(得分:0)

您必须将数据传递给UserAdapter。代码

List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase);用于从SQL数据库中检索应用于变量数据的数据。试试这个方法。

List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase);
    UsersAdapter adapter = new UsersAdapter(this, (ArrayList<DataProvider>) data);
   list.setAdapter(adapter);

然后在下面给出了UserAdapter类的实现,它扩展了ArrayAdapter ..

public class UsersAdapter extends ArrayAdapter<DataProvider> {
private static class ViewHolder {
    TextView id;
    TextView name;
    TextView number;
}
public UsersAdapter(Context context, ArrayList<DataProvider> users) {
    super(context, R.layout.new_layout, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
  //  User user = getItem(position);

    DataProvider dataProvider = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag
    if (convertView == null) {
        // If there's no view to re-use, inflate a brand new view for row
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.new_layout, parent, false);
        viewHolder.id = (TextView)convertView.findViewById(R.id.textId);
        viewHolder.name = (TextView) convertView.findViewById(R.id.textname);
        viewHolder.number = (TextView) convertView.findViewById(R.id.textnumber);
        // Cache the viewHolder object inside the fresh view
        convertView.setTag(viewHolder);
    } else {
        // View is being recycled, retrieve the viewHolder object from tag
        viewHolder = (ViewHolder) convertView.getTag();
    }
    // Populate the data from the data object via the viewHolder object
    // into the template view.
    viewHolder.id.setText(dataProvider.getId());
    viewHolder.name.setText(dataProvider.getName());
    viewHolder.number.setText(dataProvider.getMob());
    // Return the completed view to render on screen
    return convertView;
}
}

上面的代码是UserAdapter,它扩展了ArrayAdapter。试试这个方法你就会得到解决方案。 您也可以参考此链接https://github.com/codepath/android_guides/wiki/using-an-arrayadapter-with-listview