简体   繁体   English

如何将列表视图数据传递到SQLite数据库?

[英]How to pass list-view data to SQLite database?

I'm building message app and my message and number are showing in list-view but I'm not sure how to pass the list-view data to SQLite database? 我建立的消息应用程序,并且我的消息和数字显示在列表视图,但我不知道如何将列表视图数据传递给SQLite数据库? This is my list view code looks like but not sure how to pass the data to database. 这是我的列表视图代码,但不确定如何将数据传递到数据库。

package com.example.sunny.messager;

import java.util.ArrayList;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class ListActivity extends Activity {

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

        ListView lv=(ListView)findViewById(R.id.SmsList);

        if(fetchInbox()!=null){
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fetchInbox());
            lv.setAdapter(adapter);
        }

    }
    public ArrayList<String> fetchInbox(){

        ArrayList<String> sms=new ArrayList<String>();

        Uri uriSms=Uri.parse("content://sms/");

        Cursor cursor=getContentResolver().query(uriSms, new String[]{"_id","address","date","body"}, null, null, null);
        cursor.moveToFirst();
        while(cursor.moveToNext()){

            String address=cursor.getString(1);
            String body=cursor.getString(3);

            sms.add("Number: " +address+"\n Message: " +body);
        }
        return sms;
    }
}

You need to use these classes SQLiteDatabase and and SQLiteOpenHelper. 你需要使用这些类SQLiteDatabase并和SQLiteOpenHelper。

  • SQLiteDatabase is the class for us to perform CRUD function. SQLiteDatabase是类为我们执行CRUD功能。
  • SQLiteOpenHelper is a helper class to manage database creation and version management. SQLiteOpenHelper是一个辅助类来管理数据库的创建和版本管理。

Now let's start code on table structure portion first – create table in Android. 现在,让我们第一次开始对表结构部分的代码 - 在Android中创建表。 We will create a file name SMSData.java , and the code in this file will look like this 我们将创建一个文件名SMSData.java,并在此文件中的代码看起来像这样

package com.example.sqlitedb;
public class SMSData {
    // Labels table name
    public static final String TABLE = "SMSData";

    // Labels Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_number = "number";
    public static final String KEY_message= "message";

    // property help us to keep data
    public int SMSData_ID;
    public int number;
    public String message;
}

We'll create a class and name it DBHelper.java and code in this file will look like this, to ease on understand code line by line i put comment in code. 我们将创建一个类并将其命名为DBHelper.java和代码在这个文件看起来像这样,以缓解由行,我把注释代码理解的代码行。

package com.example.sqlitedb;

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

public class DBHelper  extends SQLiteOpenHelper {
    //version number to upgrade database version
    //each time if you Add, Edit table, you need to change the
    //version number.
    private static final int DATABASE_VERSION = 4;

    // Database Name
    private static final String DATABASE_NAME = "crud.db";

    public DBHelper(Context context ) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //All necessary tables you like to create will create here

        String CREATE_TABLE_SMSDATA= "CREATE TABLE " + SMSData.TABLE  + "("
                + SMSData.KEY_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + SMSData.KEY_number+ " INTEGER, "
                + SMSData.KEY_message+ " TEXT )";

        db.execSQL(CREATE_TABLE_SMSDATA);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed, all data will be gone!!!
        db.execSQL("DROP TABLE IF EXISTS " + SMSData.TABLE);

        // Create tables again
        onCreate(db);

    } 

}

With above 2 steps, SMSData table will be created when app get started and now we could code the CRUD functions! 通过上述两个步骤,将在应用程序启动时创建SMSData表,现在我们可以编写CRUD函数了! Create SMSDataRepo.java, the purpose of this class is to perform CRUD on the SMSData table. 创建SMSDataRepo.java,此类的目的是对SMSData表执行CRUD。 The code in this file will look like this. 在这个文件中的代码看起来像这样。

package com.example.sqlitedb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashMap;

public class SMSDataRepo {
    private DBHelper dbHelper;

    public SMSDataRepo(Context context) {
        dbHelper = new DBHelper(context);
    }

    public int insert(SMSData sMSData) {

        //Open connection to write data
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(SMSData.KEY_number, sMSData.number);
        values.put(SMSData.KEY_message,sMSData.message);

        // Inserting Row
        long SMSData_Id = db.insert(SMSData.TABLE, null, values);
        db.close(); // Closing database connection
        return (int) SMSData_Id;
    }

    public void delete(int SMSData_Id) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // It's a good practice to use parameter ?, instead of concatenate string
        db.delete(SMSData.TABLE, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData_Id) });
        db.close(); // Closing database connection
    }

    public void update(SMSData sMSData) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(SMSData.KEY_number, sMSData.number);
        values.put(SMSData.KEY_message,sMSData.message);

        // It's a good practice to use parameter ?, instead of concatenate string
        db.update(SMSData.TABLE, values, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData.SMSData_ID) });
        db.close(); // Closing database connection
    }

    public ArrayList<HashMap<String, String>>  getSMSDataList() {
        //Open connection to read only
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  " +
                SMSData.KEY_ID + "," +
                SMSData.KEY_number+                     
                SMSData.KEY_message+ "," +
                " FROM " + SMSData.TABLE;

        //SMSData sMSData= new SMSData();
        ArrayList<HashMap<String, String>> sMSDataList = new ArrayList<HashMap<String, String>>();

        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list

        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> sMSData= new HashMap<String, String>();
                sMSData.put("number", cursor.getString(cursor.getColumnIndex(SMSData.KEY_number)));
                sMSData.put("message", cursor.getString(cursor.getColumnIndex(SMSData.KEY_message)));
                sMSDataList.add(sMSData);

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return sMSDataList;

    }

    public SMSData getSMSDataById(int Id){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  " +
                SMSData.KEY_ID + "," +
                SMSData.KEY_number + "," +
                SMSData.KEY_message +
                " FROM " + SMSData.TABLE
                + " WHERE " +
                SMSData.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string

        int iCount =0;
        SMSData sMSData= new SMSData();

        Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );

        if (cursor.moveToFirst()) {
            do {
                sMSData.SMSData_ID =cursor.getInt(cursor.getColumnIndex(SMSData.KEY_ID));
                sMSData.number=cursor.getInt(cursor.getColumnIndex(SMSData.KEY_number));
                sMSData.message=cursor.getString(cursor.getColumnIndex(SMSData.KEY_message));

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return sMSData;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Android中将边框赋予列表视图 - How to give Border to list-view in android 列表视图JSON解析数据中的搜索栏错误NullPointerException - Search bar in list-view JSON parsed data error NullPointerException 如何从SQLite数据库读取数据并将其显示在列表视图中 - How to Read Data from SQLite Database and show it on a list view 用arraylist填充列表视图 - Populating a list-view with an arraylist 如何在 Sap Hybris 中配置实体的参考搜索列表视图 - How configure reference search list-view of an entity in Sap Hybris 如何将编辑文本值添加到列表视图 - How to add Edit Text Values to List-view 将数据从列表视图(从Rest Api生成)传递到另一个活动,并将其保存到SQLite数据库中 - pass Data from a List View (generated from Rest Api) to another activity and save that into SQLite Database SQLite数据库列表视图 - SQLite database list view 通过比较java android中的当前时间和数据库输入时间来显示列表视图的详细信息 - Display details on list-view by comparing current time and database input time in java android 在列表视图中使用Android Studio从Parse中的指针检索数据 - Retrieving data from pointer in Parse using android studio in list-view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM