0

我有一个带日期的列表视图,所以一旦你运行应用程序,它会自动显示日期(非数据库项目)。我的问题是如何在同一个列表视图中插入和查看来自 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);

我的基础适配器

    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);
4

1 回答 1

0

我以某种方式理解您的问题,即您想将项目添加到列表视图中,而不删除已经包含的项目。您可以通过向 adpater 添加项目并调用 notifychanged 来更新列表视图来做到这一点:

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 db 中的数据添加到 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();
}

你做了 setListAdapter(...); 之前,它替换了旧适配器,因此之前在列表视图中查看的数据被替换。现在使用上述方法,您只需添加新数据。

于 2013-07-02T07:19:50.043 回答