我在 android 中做了一个应用程序,并使用 Sqlite 数据库来存储数据。我已经尝试过 sqlite Open helper 并为它上课。它运行良好,但问题是当我插入数据时,它在表中插入了两次。
我的代码如下:
db-helper.java
package com.example.timerdemo2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class dbhelper extends SQLiteOpenHelper {
public static String db_name = "myDB.db";
public static String Name = "name";
public static String Timerpoint1 = "timerpoint1";
public static String Timerpoint2 = "timerpoint2";
public static String Timerpoint3 = "timerpoint3";
public static String Servicetime1 = "servicetime1";
public static String Servicetime2 = "servicetime2";
public dbhelper(Context context) {
super(context, db_name, null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL("CREATE TABLE timer(_ID INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,Timerpoint1 TEXT,Timerpoint2 TEXT,Timerpoint3 TEXT,Servicetime1 TEXT,Servicetime2 TEXT);");
/*String sql = "INSERT INTO register (Email,Name,Contact)" + "VALUES (" + Email + "," + Name + "," + Contact + ")";
db.execSQL(sql);*/
}catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
android.util.Log.v("Constants", "Upgrading database which will destroy all data");
onCreate(db);
}
}
TimeDetails.java
package com.example.timerdemo2;
import java.sql.SQLOutput;
import java.util.jar.Attributes.Name;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Timedetails extends Activity {
EditText eta,etb,etc,service1,service2;
Button btn,btn1;
TextView tv1;
SQLiteDatabase db;
dbhelper dh = new dbhelper(this);
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
} */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timedetails);
Bundle b1 = this.getIntent().getExtras();
final String title = b1.getString("title");
tv1 = (TextView)findViewById(R.id.Projecttitle);
tv1.setText(title);
Bundle bundle = getIntent().getExtras();
String tim1 = bundle.getString("t1");
String tim2 = bundle.getString("t2");
String tim3 = bundle.getString("t3");
final String titl = bundle.getString("titl1");
final TextView tv = (TextView)findViewById(R.id.Projecttitle);
tv.setText(titl);
eta = (EditText)findViewById(R.id.timval1);
eta.setText(tim1);
etb = (EditText)findViewById(R.id.timval2);
etb.setText(tim2);
etc = (EditText)findViewById(R.id.timval3);
etc.setText(tim3);
String ser1 = bundle.getString("dif1");
String ser2 = bundle.getString("dif2");
service1 = (EditText)findViewById(R.id.servicetime1a);
service1.setText(ser1);
service2 = (EditText)findViewById(R.id.servicetime2a);
service2.setText(ser2);
// btn1 =(Button)findViewById(R.id.delete);
/* btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showMessageAlert();
}
/* private void showMessageAlert() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Timedetails.this);
final Dialog dialog = null;
builder.setTitle("Alert");
builder.setMessage("Are you sure you want to delete");
builder.setCancelable(true);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("I Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// dialog.dismiss();
Intent intent = new Intent(Timedetails.this,ListActivity.class);
Toast.makeText(getApplicationContext(), "Your Time Details has been Deleted", Toast.LENGTH_SHORT).show();
startActivity(intent);
// delete the stuff you wan to
}
});
builder.setNegativeButton("I decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//Do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});*/
btn=(Button)findViewById(R.id.save);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent =new Intent(Timedetails.this,ListActivity.class);
// Toast.makeText(getApplicationContext(), "Project has been added to List", 1).show();
startActivity(intent);
addRecord();
// Toast.makeText(getApplicationContext(), "Record inserted successfully !", 1).show();
addRecord();
}
private void addRecord() {
// TODO Auto-generated method stub
String tv1 = tv.getText().toString();
tv.setText(tv1);
//String title = tv1.getText().toString();
//tv1.setText(tv);
String tmp1 = eta.getText().toString();
String tmp2 = etb.getText().toString();
String tmp3 = etc.getText().toString();
String ser1 = service1.getText().toString();
String ser2 = service2.getText().toString();
insertData(titl,tmp1,tmp2,tmp3,ser1,ser2);
Toast.makeText(getApplicationContext(), "Record inserted suceessfully", Toast.LENGTH_LONG).show();
}
private void insertData(String titl, String tmp1, String tmp2,
String tmp3, String ser1, String ser2) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), titl + " " + tmp1 + " " + tmp2 + " "+ tmp3 + " "+ ser1 +" "+ ser2, 1).show();
SQLiteDatabase db = dh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dh.Name, titl);
cv.put(dh.Timerpoint1, tmp1);
cv.put(dh.Timerpoint2, tmp2);
cv.put(dh.Timerpoint3, tmp3);
cv.put(dh.Servicetime1, ser1);
cv.put(dh.Servicetime2, ser2);
// Toast.makeText(getApplicationContext(), " " + cv, 1).show();
db.insert("timer", dh.Name, cv);
}
});
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
ListActivity.java
package com.example.timerdemo2;
import java.util.ArrayList;
import android.R.menu;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class ListActivity extends Activity {
ListView lv;
ArrayList<String> items = new ArrayList<String>();
ArrayList<String> items_id = new ArrayList<String>();
dbhelper dh;
SQLiteDatabase db;
private boolean Distinct = true;
int index_id;
Button btn;
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button btn;
btn = (Button)findViewById(R.id.newProjectlist);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent= new Intent(ListActivity.this,NewProject.class);
startActivity(intent);
}
});
lv = (ListView)findViewById(R.id.projectListView);
setUpList();
dh = new dbhelper(this);
Cursor c = getAllData();
showAllData(c);
registerForContextMenu(lv);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId() == R.id.projectList){
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("Record List");
menu.add(0,1,menu.NONE,"Delete Record");
menu.add(0,2,menu.NONE,"Show Record");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
int itemId = item.getItemId();
if(itemId == 1)
{
AdapterView.AdapterContextMenuInfo menuinfo;
menuinfo = (AdapterContextMenuInfo) item.getMenuInfo();
index_id = menuinfo.position;
deleteUserData(index_id);
}
if(itemId == 2){
AdapterView.AdapterContextMenuInfo menuinfo;
menuinfo = (AdapterContextMenuInfo) item.getMenuInfo();
index_id = menuinfo.position;
editUserData(index_id);
}
return super.onContextItemSelected(item);
}
private void editUserData(int indexid) {
// TODO Auto-generated method stub
String user_id = items_id.get(indexid);
Intent intEdit = new Intent(ListActivity.this, MainActivity.class);
intEdit.putExtra("EditID", user_id);
startActivityForResult(intEdit, 1);
}
private void deleteUserData(int indexid) {
// TODO Auto-generated method stub
String user_id = items_id.get(indexid);
//Toast.makeText(getApplicationContext(), "id " + user_id, 1).show();
db = dh.getWritableDatabase();
db.delete("timer","_ID" + "=" + user_id, null);
finish();
// Toast.makeText(getApplicationContext(), "Record deleted successfully", 1).show();
}
private void showAllData(Cursor c) {
// TODO Auto-generated method stub
while(c.moveToNext())
{
int id = c.getInt(0);
String name = c.getString(1);
String timerpoint1 = c.getString(2);
String timerpoint2 = c.getString(3);
String timerpoint3 = c.getString(4);
String servicetime1 = c.getString(5);
String servicetime2 = c.getString(6);
items.add("" + name);
items_id.add(""+id);
}
setUpList();
}
@SuppressWarnings("deprecation")
private Cursor getAllData() {
// TODO Auto-generated method stub
db = dh.getReadableDatabase();
//String sortorder = dh.Name + "DESC";
// String query ="SELECT DISTINCT name FROM timer";
// Cursor c = db.rawQuery(query, null);
// if (c != null) {
// c.moveToFirst();
// }
Cursor cur = db.query(Distinct,"timer", null, null, null, null, null, null, null);
startManagingCursor(cur);
return cur;
}
private void setUpList() {
// TODO Auto-generated method stub
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,items));
}
}