我想从Array适配器检索数据并将其存储在数据库中 就像scaned bluetooth的细节存储在arrayadapter中一样,我想获取那些数据并将其存储在我的数据库中。
答案 0 :(得分:1)
您可以添加到适配器类,它将返回列表中的所有适配器项,然后您可以随意执行任何操作
编辑:
public class MainActivity extends Activity {
MyAdapter<String> btArrayAdapter; // don't forget to change type here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
btArrayAdapter = new MyAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
...
}
public class MyAdapter<String> extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource) {
super(context, resource);
}
//Adapter implementation
//so this is the function that retrieve data from the adapter
public List<String> getAllItems() {
ArrayList<String> result = new ArrayList<>()
for (int i = 0; i < getCount(); i++) {
result.add(getItem(i));
}
return result;
}
}
}
然后,您可以通过调用btArrayAdapter.getAllItems();
对于xml上的按钮:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="btnClick"
android:text="save "/>
对于数据库,您可以添加:
public class MainActivity extends Activity {
//constant used for database
private static final String DEVICE = "Device";
private static final String BLUETOOTH_DEVICES = "BluetoothDevice";
private static final String DATE = "date";
SQLiteDatabase myDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//how to create or open databse
myDatabase = openOrCreateDatabase("DATABASE",MODE_PRIVATE,null);
// here we create a table like following
// BluetoothDevice :
// | Device : VARCHAR |
// | date : INTEGER |
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS " + BLUETOOTH_DEVICES + "(" + DEVICE + " VARCHAR," + DATE + " INTEGER);");
}
private Map<String, Date> getItemFromDatabase() {
Map<String,Date> result = new HashMap<>();
//Query to retrieve data from database
Cursor c = myDatabase.rawQuery("Select * from " + BLUETOOTH_DEVICES, null);
//how to iterate hover database cursor
while (c.moveToNext()){
result.put(c.getString(c.getColumnIndex(DEVICE)),new Date(c.getInt(c.getColumnIndex(DATE))));
}
c.close();
return result;
}
public void store(List<String> data){
for (String value : data) {
//Query to insert item in databse
myDatabase.rawQuery("INSERT INTO "+BLUETOOTH_DEVICES+" VALUES(?,?);",new String[]{value, String.valueOf(new Date().getTime())});
}
}
//button click listenner defined in xml
public void btnClick(View view) {
// here we store all adapter item in database
store(btArrayAdapter.getAllItems());
}
}
您可以将其添加到以前的代码中。 它只是一个基础我高兴你重新格式化代码创建不同的java类,使用sql数据助手类和东西
答案 1 :(得分:0)
FATAL EXCEPTION: main
Process: com.example.test.test, PID: 17458
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3989)
at android.view.View.performClick(View.java:4741)
at android.view.View$PerformClick.run(View.java:19384)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5679)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3984)
at android.view.View.performClick(View.java:4741)
at android.view.View$PerformClick.run(View.java:19384)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5679)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "s": syntax error (code 1): , while compiling: INSERT INTO BluetoothDevice VALUES('Faiz's iPhone
28:ED:6A:E0:E4:C8','1470825437206');
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1793)
答案 2 :(得分:0)
好的,就像你要求我创建了一个带有2个列表的活动,在第一个列表中我们有一个项目列表。下面有一个标有&#34;保存&#34;的按钮。当您单击它时,它将获取所有适配器项并将它们存储到数据库中。在,有一个按钮刷新,它将检索数据drom数据库并在第二个列表上显示它们。
因此对于xml我们有:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:id="@+id/list" />
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/button"
android:onClick="btnSaveClick"
android:text="Save" />
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:id="@+id/dbList" />
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/refresh"
android:onClick="btnRefreshClick"
android:text="refresh" />
</LinearLayout>
然后有3个java类,一个用于定义蓝牙设备,一个用于适配器,另一个用于活动。 首先是BluetoothDevice.java:
public class BluetoothDevice {
public String name;
public String address;
public Date date;
public String scan;
public BluetoothDevice(String name, String address, Date date,String scan) {
this.name = name;
this.address = address;
this.date = date;
this.scan =scan;
}
private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
public String getDateFormatted() {
if (date == null){
return " no date ";
}
return format.format(date);
}
}
第二个MyAdapter.java:
public class MyAdapter extends ArrayAdapter<BluetoothDevice> {
public MyAdapter(Context context, int resource, List<BluetoothDevice> devices) {
super(context, resource, devices);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// here we can define custom design of list item
TextView textView = new TextView(getContext());
BluetoothDevice item = getItem(position);
textView.setTextColor(Color.BLACK);
textView.setText(item.name+" : "+item.address +" date :"+item.getDateFormatted()+" "+item.scan);
return textView;
}
//method to get all adapter objects
public List<BluetoothDevice> getAllItem() {
List<BluetoothDevice> result = new ArrayList<>();
for (int i = 0; i < getCount(); i++) {
Log.e("fef", "getAllItem: " );
result.add(getItem(i));
}
return result;
}
}
和最终的MyActivity.java
public class MainActivity extends Activity {
SQLiteDatabase myDatabase;
private MyAdapter adapter;
private ListView listOfDatabaseObject;
private ListView list;
private String databaseName = "DATABASENAME2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
listOfDatabaseObject = (ListView) findViewById(R.id.dbList);
List<BluetoothDevice> devices = new ArrayList<>();
//for the exemple i crate a new device to add to the list
devices.add(new BluetoothDevice("device 1", "14:5E:FE:AA", null,"scan record : 78984f9s8d4f98 s4df98s4f 984sf 984sd9f8 4cucoucou 7f578sfd57f8"));
adapter = new MyAdapter(getApplicationContext(), 0, devices);
list.setAdapter(adapter);
myDatabase = openOrCreateDatabase(databaseName, MODE_PRIVATE, null);
// here we create a table like following
// BluetoothDevice :
// | Device : VARCHAR |
// | Address : VARCHAR |
// | date : VARCHAR |
// | Scan : VARCHAR |
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS BluetoothDevice ( Device VARCHAR , Address VARCHAR , Date VARCHAR ,Scan VARCHAR);");
}
private List<BluetoothDevice> getItemFromDatabase() {
List<BluetoothDevice> result = new ArrayList<>();
// query database elements
Cursor c = myDatabase.rawQuery("Select * from BluetoothDevice ;", null);
while (c.moveToNext()) {
Date v = new Date();
v.setTime(c.getInt(c.getColumnIndex("Date")) * 1000);
Date date = new Date();
date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));
result.add(
new BluetoothDevice(
c.getString(c.getColumnIndex("Device")),
c.getString(c.getColumnIndex("Address")),
date,
c.getString(c.getColumnIndex("Scan"))
)
);
}
c.close();
return result;
}
public void store(List<BluetoothDevice> data) {
for (BluetoothDevice value : data) {
String s = String.valueOf(new Date().getTime());
//insert in database
myDatabase.execSQL("INSERT INTO BluetoothDevice VALUES(?,?,?,?);", new String[]{value.name, value.address, s,value.scan});
}
}
// save button click listener
public void btnSaveClick(View view) {
store(adapter.getAllItem());
}
// refresh button click listener
public void btnRefreshClick(View view) {
List<BluetoothDevice> itemFromDatabase = getItemFromDatabase();
MyAdapter adapter = new MyAdapter(getApplicationContext(), 0, itemFromDatabase);
listOfDatabaseObject.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
在此代码中,您将找到从适配器获取所有项目所需的一切,创建一个按钮及其操作,创建一个简单的sqlite数据库,使用自定义字段,在数据库中插入项目,从数据库中检索项目,最后在列表视图中显示它们。