如何将数据移动到SQLite?

时间:2018-09-22 08:21:10

标签: java android xml sqlite

代码

public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private ContactsAdapter mAdapter;


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

    contactsList = (RecyclerView) findViewById(R.id.usersList);
    //Add the data first
    addDataToList();
    linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    //and then create a object and pass the lis
    mAdapter = new ContactsAdapter(contacts);

    contactsList.setHasFixedSize(true);
    contactsList.setLayoutManager(linearLayoutManager);
    contactsList.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();


}

public void addDataToList() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor != null) {
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                            null);
                    if (phoneCursor != null) {
                        if (phoneCursor.moveToNext()) {
                            String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            contacts.add(new ContactsHelper(name, phoneNumber));
                            phoneCursor.close();
                        }
                    }
                }
            }
        }
        cursor.close();
    }
}
}

这将显示活动中用户电话中的所有联系人...我如何将数据移动到SQLite中的表中?

到目前为止的进展:

public class DatabaseHelper extends SQLiteOpenHelper {

// Table Name
public static final String TABLE_NAME = "Contacts";

// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";

// Database Information
static final String DB_NAME = "MessagePlus_Contacts";

// database version
static final int DB_VERSION = 1;

// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL);";

public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
 }

助手

public class ContactsHelper {
private String Name;
private String PhoneNumber;

public ContactsHelper() {
}

public ContactsHelper(String Name, String PhoneNumber) {
    this.Name = Name;
    this.PhoneNumber = PhoneNumber;
}
public String getName() {
    return Name;
}

public void setName(String Name) {
    this.Name = Name;
}

public String getPhoneNumber() {
    return PhoneNumber;
}

public void setPhoneNumber(String PhoneNumber) {
    this.PhoneNumber = PhoneNumber;
}

}

我已经到了这一步,但是我不知道如何进行,因为到目前为止,我只通过单击按钮或类似的按钮来添加/修改数据。

如何将完整数据移动到SQLite,并且当添加新联系人时显然不会自动将其添加到表中,因此当我添加诸如滑动刷新的功能时,我也希望将新联系人也添加到数据中吗?

1 个答案:

答案 0 :(得分:0)

解决方案:

在您的DatabaseHelper类中添加此方法:

public void insertData(String contactName, String phoneNumber) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(DatabaseHelper.Contact_Name, contactName);
    values.put(DatabaseHelper.Phone_Number, phoneNumber);

    db.insert(DatabaseHelper.TABLE_NAME, null, values);

    // close db connection
    db.close();

}

然后,首先,在您的DatabaseHelper类中创建SettingsContacts全局对象:

public DatabaseHelper database;

将此添加到您的onCreate()

database = new DatabaseHelper(SettingsContacts.this);

然后在此之后,如图所示在addDataToList()方法中添加以下行:

添加此行:

database.insertData(name, phoneNumber)

如下面的代码所示(在此处写入):

if (phoneCursor != null) {
    if (phoneCursor.moveToNext()) {
         String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

          contacts.add(new ContactsHelper(name, phoneNumber));
          phoneCursor.close();

          ....... (Write Here)

     }
}

就是这样。

希望它能起作用。

要查看是否已插入数据,可以检查表的计数:

public int getCount() {
    String countQuery = "SELECT  * FROM " + DatabaseHandler.TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);

    int count = cursor.getCount();
    cursor.close();

    // return count
    return count;
}

在数据库处理程序类中编写上述方法。

然后,在调用insertData(..)后的活动中,您可以这样写:

int count = database.getCount();
Log.e("Count From DB: ", String.valueOf(count));