TQC-209 讀取資源檔,並操作sqlite做刪除、新增、排序
這是TQC的209題,
程式碼為自行撰寫,
僅供參考。
主要練習取得資源檔資料後,操作sqlite,刪除並新增,再用spinner顯示。
private CharSequence[] strNames;
Resources resources = getResources();
strNames = getResources().getTextArray(R.array.strNames);
資源檔:
姓名清單
- Ella
- Body
- David
- Andy
- Cindy
- GiGi
- Fancy
- Fancy
程式:
package COM.TQC.GDD02;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class GDD02 extends Activity {
private static final String DBNAME = "MY_DB";
private static final String TABLENAME = "MY_TABLE";
private static final String FIELD01_NAME = "_id";
private static final String FIELD02_NAME = "_text1";
private SQLiteDatabase dataBase;
private Spinner Spinner01;
private CharSequence[] strNames;
private Cursor cursor;
private String orderNames[];
private TextView infoView;
private String[] querycloumn={"_text1"};
//資料筆數
private int recordCount;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findview();
setspinner();
}
public void findview()
{
Spinner01 = (Spinner) findViewById(R.id.Spinner01);
infoView=(TextView)findViewById(R.id.textView1);
}
public void setspinner()
{
Resources resources = getResources();
strNames = getResources().getTextArray(R.array.strNames);
dataBase = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
String CREATE_SQL = "create table if not exists "+TABLENAME+" ("+FIELD01_NAME+" integer primary key autoincrement, "+FIELD02_NAME+" varchar not null);";
dataBase.execSQL(CREATE_SQL);
dataBase.execSQL("delete from "+TABLENAME);
int _i=0;
int _j=strNames.length;
for(_i=0;_i<_j;_i++)
{
dataBase.execSQL("INSERT INTO "+TABLENAME+" VALUES (NULL, ?)", new Object[]{strNames[_i]});
}
int _k;
//int _m;
cursor=dataBase.query(TABLENAME, new String[] { "_text1" }, null, null, null, null, "_text1");
_k=cursor.getCount();
infoView.setText(String.valueOf(_k));
ArrayList strings = new ArrayList();
cursor.moveToFirst();
do {
String mTitleRaw = cursor.getString(0);
strings.add(mTitleRaw);
} while (cursor.moveToNext());
orderNames = (String[]) strings.toArray(new String[strings.size()]);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, orderNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner01.setAdapter(adapter);
}
}
自我LV~