如何在不替换listview文本的情况下在listview中查看数据库



我有一个带日期的列表视图,所以一旦运行应用程序,它将自动显示日期(非数据库项)。我的问题是如何在同一个listview中插入和查看sqlite数据库中的数据。

前任。

List item
Current date //default text
text1
List item2
next date //default text
text1

这是我的活动代码

{
SimpleDateFormat curFormater = new SimpleDateFormat("EEE, MMM dd, yyyy"); 
GregorianCalendar date = new GregorianCalendar();
final String[] datas = new String[3];
for (int day = 0; day <7 ; day++) {
    datas[day] = curFormater.format(date.getTime());//to automatically show the date in listview
    date.roll(Calendar.DAY_OF_YEAR, true);
}
}
//  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_planner);
    lview = (ListView) findViewById(R.id.listView2);
    lviewAdapter = new ListViewAdapter(this,datas);

lview.setAdapter(lviewAdapter);

我的BaseAdatper

    public class ListViewAdapter extends BaseAdapter
{
Activity context;
//String title[];
//String description[];
String mo[];

public int getCount() {
    // TODO Auto-generated method stub
    return mo.length;
}
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}
private class ViewHolder {
   // TextView txtViewTitle;
    //TextView txtViewDescription;
    TextView mo;
}
public View getView(int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    ViewHolder holder;
    LayoutInflater inflater =  context.getLayoutInflater();
    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.listitem_row, null);
        holder = new ViewHolder();
    //  holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
        //holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
        holder.mo = (TextView) convertView.findViewById(R.id.textView3);
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.mo.setText(mo[position]);
return convertView;
}

我的数据库

public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
@SuppressLint("SimpleDateFormat")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    openAndQueryDatabase();

    displayResultList();

}
private void displayResultList() {
    TextView tView = new TextView(this);
    tView.setText("This data is retrieved from the database and only 4 " +
            "of the results are displayed");
    //getListView().addHeaderView(tView);
    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,results));
}
private void openAndQueryDatabase() {
    try {
        DBHelper dbHelper = new DBHelper(this.getApplicationContext());
        newDB = dbHelper.getWritableDatabase();
        Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
                tableName +
                " where Age > 10 LIMIT 4", null);
        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    String firstName = c.getString(c.getColumnIndex("FirstName"));
                    int age = c.getInt(c.getColumnIndex("Age"));
                    results.add("Name: " + firstName + ",Age: " + age);
                }while (c.moveToNext());
            } 
        }           
    } catch (SQLiteException se ) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    } finally {
        if (newDB != null) 
            newDB.execSQL("DELETE FROM " + tableName);
            newDB.close();
    }
}

}我的数据库助手

public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "sample";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "Resource";

public DBHelper(Context context) {
    super(context, DBName, null, version);
    currentContext = context;
    DBPath = "/data/data/" + context.getPackageName() + "/databases";
    createDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
}
private void createDatabase() {
    boolean dbExists = checkDbExists();
    if (dbExists) {
        // do nothing
    } else {
        DB = currentContext.openOrCreateDatabase(DBName, 0, null);
        DB.execSQL("CREATE TABLE IF NOT EXISTS " +
                tableName +
                " (LastName VARCHAR, FirstName VARCHAR," +
                " Country VARCHAR, Age INT(3));");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('M','Sing','India',25);");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('C','Raje','India',25);");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('D','Phonu','Argentina',20);");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('V','Veera','EU',25);");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('T','Shenoi','Bangla',25);");
        DB.execSQL("INSERT INTO " +
                tableName +
                " Values ('L','Lamha','Australia',20);");
    }

}
private boolean checkDbExists() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DBPath + DBName;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

我在某种程度上理解您的问题,即您希望将项目添加到列表视图中,而不删除已经包含的项目。您可以通过将项目添加到adpader并调用notificationchanged来更新列表视图来完成此操作:

lviewAdapter.setNotifyOnChange(false);
lviewAdapter.addAll(model.getItems());
lviewAdapter.notifyDataSetChanged();

使用以下内容作为您班级的成员

ListAdapter lviewAdapter;

在onCreate方法中初始化它并将适配器设置为ListView:

lviewAdapter = new ListViewAdapter(this,datas);
lview.setAdapter(lviewAdapter);

如果您想稍后在添加新项目之前清除ListView,请使用以下命令:

lviewAdapter.setNotifyOnChange(false);
lviewAdapter.clear();
lviewAdapter.addAll(model.getItems());
lviewAdapter.notifyDataSetChanged();

更新

将sql数据库中的数据添加到ListView中,例如:

List<String> anotherDataFromSQLDB = new ArrayList<String>();
// Fill data here in list anotherDataFromSQLDB
lviewAdapter.setNotifyOnChange(false);
lviewAdapter.addAll(anotherDataFromSQLDB);
lviewAdapter.notifyDataSetChanged();

更新2

重写你的方法如下:

private void displayResultList() {
   TextView tView = new TextView(this);
   tView.setText("This data is retrieved from the database and only 4 " +
        "of the results are displayed");
   ListViewAdapter adapter = getListView().getAdapter();
   lview.setNotifyOnChange(false);
   lview.addAll(results);
   lview.notifyDataSetChanged();
}

您已设置ListAdapter(…);之前,它将替换旧适配器,以便替换之前在listview中查看的数据。现在使用上面的方法,您只需要添加新的数据。

相关内容

最新更新