Android数据库连接失败

时间:2014-07-09 05:21:44

标签: java android sql database

我的项目要求用户在页面中进行数据输入。用户输入的这些值必须存储在数据库中,并在要求检索时显示。当我运行应用程序并在UI中输入值并提交到数据库。它只是在一段时间后关闭,什么也不做。请帮我找到连接数据库的方法并获取更新的值。感谢

以下是我的三个班级的代码

MainActivity.java

package pack.dannyzdatabase;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

DatabaseAdapter db = new DatabaseAdapter();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bttn2 = (Button) findViewById(R.id.button2);


    bttn2.setOnClickListener(new OnClickListener(){


        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,ViewActivity.class);
            startActivity(intent);

        }
    });

    try {
        String destPath = "/data/data/" + getPackageName() + "/databases/AndyXDb";
                 File f = new File(destPath);
                 if (!f.exists()) {
                 CopyDB( getBaseContext().getAssets().open("mydb"),
                 new FileOutputStream(destPath));
                 }
                 } catch (FileNotFoundException e) {
                 e.printStackTrace();
                 } catch (IOException e) {
                 e.printStackTrace();
                 }
}

private void CopyDB(InputStream inputStream, OutputStream outputStream) 
throws IOException {
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0){
        outputStream.write(buffer,0,length);
    }
    inputStream.close();
    outputStream.close();

}

}

以下是DatabaseAdapter类,DatabaseAdapter.java

package pack.dannyzdatabase;

import java.sql.SQLException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public  class DatabaseAdapter {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "Unique ID";
public static final String KEY_DEVICETYPE = "Device Type";
public static final String KEY_RSSI = "RSSI";
public static final String TAG = "DBAdapter";

private static final String DATABASE_NAME="DannyzDb";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_TABLE="DannyzData";

private static final String DATABASE_CREATE= "create table if not exist DannyzData( Timestamp TIMESTAMP, Unique ID BLOB," +
        "Device Type VARCHAR, RSSI INTEGER PRIMARY KEY NOT NULL);";

//private final Context context;

private DataBaseHelper DBHelper;
private SQLiteDatabase db;

private static class DataBaseHelper extends SQLiteOpenHelper
{
   DataBaseHelper(Context context){
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try{
            db.execSQL(DATABASE_CREATE);
        } catch (SQLiteException e) {
            e.printStackTrace();
            }
        }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version" +oldVersion+ "to"
            +newVersion + ",which will destroy all old data");
    db.execSQL("DROPTABLE IF EXISTS" + DATABASE_TABLE);
    onCreate(db);
    }   
}


//Opens the database

public DatabaseAdapter open() throws SQLException{
    db=DBHelper.getWritableDatabase();
    return this;
    }

//closes the database

public void close(){
    DBHelper.close();
}

//Insert a record into database

public long insertRecord(String Timestamp, String UniqueId, String DeviceType, String RSSI){
    ContentValues intialValues = new ContentValues();
    intialValues.put(KEY_TIMESTAMP,Timestamp);
    intialValues.put(KEY_UNIQUEID,UniqueId);
    intialValues.put(KEY_DEVICETYPE,DeviceType);
    intialValues.put(KEY_RSSI,RSSI);


    return db.insert(DATABASE_TABLE,null,intialValues);
}

// deletes a particular record

    public boolean deleteRecord(long rssi)
    {
        return db.delete(DATABASE_TABLE,KEY_RSSI + "=" + rssi,null)>0;
        }

      // retrieves all the records

     public Cursor getAllRecords(){
     return db.query(DATABASE_TABLE,new String[] {KEY_TIMESTAMP,KEY_UNIQUEID,KEY_DEVICETYPE,KEY_RSSI},null,null,null,null,null);

}



//Updates a record

public boolean updateRecord(long rssi,String timestamp,String uniqueId,String      DeviceType, String RSSI, String Timestamp, String UniqueId){
ContentValues args = new ContentValues();
args.put(KEY_TIMESTAMP,Timestamp);
args.put(KEY_UNIQUEID,UniqueId);
args.put(KEY_DEVICETYPE,DeviceType);
return db.update(DATABASE_TABLE,args,KEY_RSSI + "=" + rssi,null)>0;
}
}   

这是另一个类ViewActivity.java

package pack.dannyzdatabase;

import java.sql.SQLException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ViewActivity extends Activity 
{
DatabaseAdapter db = new DatabaseAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);

    }

public void ViewActivity(View v)
{

EditText txt1 = (EditText) findViewById(R.id.editText1);
EditText txt2 = (EditText) findViewById(R.id.editText2);
EditText txt3 = (EditText) findViewById(R.id.editText3);
EditText txt4 = (EditText) findViewById(R.id.editText4);

try {
    db.open();
} catch (SQLException e) {

    e.printStackTrace();
}

long id = db.insertRecord(txt1.getText().toString(),
txt2.getText().toString(),txt3.getText().toString(),
txt4.getText().toString());
db.close();


txt1.setText("");
txt2.setText("");
txt3.setText("");
txt4.setText("");
Toast.makeText(ViewActivity.this,"Viewing Activity",Toast.LENGTH_LONG).show();
}


public void ViewAct (View v)
{
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}

}

Android清单代码在这里

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.andyxdatabase"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="pack.andyxdatabase.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您的DataBaseHelper类需要MainActivity类的上下文,而不是DatabaseAdapter类。您需要将活动代码更改为以下内容:

DatabaseAdapter db;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    db = new DatabaseAdapter(this);

    setContentView(R.layout.activity_main);

}

然后您的DatabaseAdapter类需要更改为:

public DatabaseAdapter(Context context) {

    DBHelper = new DataBaseHelper(context);

}