2012-10-17 6 views
1

SQLite 데이터베이스 브라우저를 사용하여 미리 작성한 sqlite 데이터베이스에 데이터를 저장하는 데 문제가 있습니다. DB를 자산 폴더에 저장했습니다.안드로이드 데이터가 데이터베이스에 저장되지 않습니다

ApplicationContextProvider 클래스 :

이 내가 사용하는 코드는

import android.app.Application; 
import android.content.Context; 
public class ApplicationContextProvider extends Application { 

private static Context sContext; 

public void onCreate() { 
     super.onCreate(); 
sContext = getApplicationContext(); 

} 

public static Context getContext() { 
    return sContext; 
} 

} 

내 DatabaseHelper 클래스 :

public class DataBaseHelper extends SQLiteOpenHelper { 

// The Android's default system path of your application database. 
//data/data/ and /databases remain the same always. The one that must be changed is com.example which represents 
//the MAIN package of your project 
private static String DB_PATH = "/data/data/com.fps/databases/"; 

//the name of your database 
private static String DB_NAME = "bmiDB"; 

private static SQLiteDatabase mDataBase; 

private static DataBaseHelper sInstance = null; 
// database version  
private static final int DATABASE_VERSION = 1; 

/** 
* Constructor Takes and keeps a reference of the passed context in order to 
* access to the application assets and resources. 
*/ 
private DataBaseHelper() { 
    super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION); 

    try { 
     createDataBase(); 
     openDataBase(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

/** 
* Singleton for DataBase 
* 
* @return singleton instance 
*/ 
public static DataBaseHelper instance() { 

    if (sInstance == null) { 
     sInstance = new DataBaseHelper(); 
    } 
    return sInstance; 
} 

/** 
* Creates a empty database on the system and rewrites it with your own 
* database. 
* 
* @throws java.io.IOException io exception 
*/ 
private void createDataBase() throws IOException { 

    boolean dbExist = checkDataBase(); 

    if (dbExist) { 
     // do nothing - database already exist 
    } else { 

     // By calling this method an empty database will be created into 
     // the default system path 
     // of your application so we are gonna be able to overwrite that 
     // database with our database. 
     this.getReadableDatabase(); 

     try { 

      copyDataBase(); 

     } catch (IOException e) { 

      throw new Error("Error copying database"); 
     } 
    } 
} 

/** 
* Check if the database already exist to avoid re-copying the file each 
* time you open the application. 
* 
* @return true if it exists, false if it doesn't 
*/ 
private boolean checkDataBase() { 

    SQLiteDatabase checkDB = null; 

    try { 
     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READONLY); 

    } catch (SQLiteException e) { 

     // database doesn't exist yet. 

    } 

    if (checkDB != null) { 

     checkDB.close(); 

    } 

    return checkDB != null; 
} 

/** 
* Copies your database from your local assets-folder to the just created 
* empty database in the system folder, from where it can be accessed and 
* handled. This is done by transfering bytestream. 
* 
* @throws java.io.IOException io exception 
*/ 
public void copyDataBase() throws IOException { 

    // Open your local db as the input stream 
    InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME); 

    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_NAME; 

    // Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    // transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[ 1024 ]; 
    int length; 
    while ((length = myInput.read(buffer)) > 0) { 
     myOutput.write(buffer, 0, length); 
    } 

    // Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

} 

private void openDataBase() throws SQLException { 

    // Open the database 
    String myPath = DB_PATH + DB_NAME; 
    mDataBase = SQLiteDatabase.openDatabase(myPath, null, 
      SQLiteDatabase.OPEN_READWRITE); 
} 

/** 
* Select method 
* 
* @param query select query 
* @return - Cursor with the results 
* @throws android.database.SQLException sql exception 
*/ 
public Cursor select(String query) throws SQLException { 
    return mDataBase.rawQuery(query, null); 
} 

/** 
* Insert method 
* 
* @param table - name of the table 
* @param values values to insert 
* @throws android.database.SQLException sql exception 
*/ 

public void insert(String table, ContentValues values) throws SQLException { 
    mDataBase.insert(table, null, values); 
} 

/** 
* Delete method 
* 
* @param table - table name 
* @param where WHERE clause, if pass null, all the rows will be deleted 
* @throws android.database.SQLException sql exception 
*/ 
public void delete(String table, String where) throws SQLException { 

    mDataBase.delete(table, where, null); 

} 

/** 
* Update method 
* 
* @param table - table name 
* @param values - values to update 
* @param where - WHERE clause, if pass null, all rows will be updated 
*/ 
public void update(String table, ContentValues values, String where) { 

    mDataBase.update(table, values, where, null); 

} 

/** 
* Let you make a raw query 
* 
* @param command - the sql comand you want to run 
*/ 


public void sqlCommand(String command) { 
    mDataBase.execSQL(command); 
} 

@Override 
public synchronized void close() { 

    if (mDataBase != null) 
     mDataBase.close(); 

    super.close(); 

} 

@Override 
public void onCreate(SQLiteDatabase db) { 

} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

} 

} 

및 방법 viewSavedToast 코드의 조각() :

AlertDialog ad = new AlertDialog.Builder(this).create(); 
    //ad.setCancelable(true); 
    ad.setTitle("Successful"); 
    ad.setMessage("You're result is saved in the database!"); 
    ad.setButton("OK", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      //with ContentValues put the data we want into the database 
      ContentValues values = new ContentValues(); 
      String column_name = etanswer.getText().toString(); 
      values.put(COLUMN_NAME, column_name ); 

      //here we insert the data we have put in values 
      dataBase.insert(TABLE_NAME, values); 
      dialog.dismiss();   
      } 
    }); 
    ad.show(); 

응용 프로그램을 실행할 때 데이터를 DB에 저장하면 onClick() 메서드에서 오류가 발생합니까? 문제가 무엇입니까? 나는 내가 여기에서 찾은 튜토리얼의 모든 단계를 따라 갔다고 믿는다 : http://myandroidsolutions.blogspot.com/2012/07/android-database-tutorial.html 그러나 어떻게 든 나는 오류가있다.

로그 :

10-17 20:50:11.118: E/AndroidRuntime(368): FATAL EXCEPTION: main 
    10-17 20:50:11.118: E/AndroidRuntime(368): java.lang.NullPointerException 
    10-17 20:50:11.118: E/AndroidRuntime(368): at         com.fps.iHealthFirst.BMICalculator.viewBMISavedToast(BMICalculator.java:121) 
    10-17 20:50:11.118: E/AndroidRuntime(368): at com.fps.iHealthFirst.BMICalculator.calculateMen(BMICalculator.java:194) 
10-17 20:50:11.118: E/AndroidRuntime(368): at com.fps.iHealthFirst.BMICalculator.onClick(BMICalculator.java:143) 
10-17 20:50:11.118: E/AndroidRuntime(368): at android.view.View.performClick(View.java:2485) 
10-17 20:50:11.118: E/AndroidRuntime(368): at android.view.View$PerformClick.run(View.java:9080) 
10-17 20:50:11.118: E/AndroidRuntime(368): at android.os.Handler.handleCallback(Handler.java:587) 
+0

WHT 오류가 표시됩니다. ??? ??? – SilentKiller

+0

onClick()에서 오류가 발생했습니다! 어떤 오류입니까? 로그를 올리십시오. –

+0

내 게시물을 편집했습니다. THanks – Dunkey

답변

1

시도는 다음과 같이 속성을 설정 빌더를 사용하고 그것을 보여 직전에 AlertDialog를 생성하여 대화 상자를 만들려면 다음

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Successful") 
    .setMessage("You're result is saved in the database!") 
    .setButton("OK", new DialogInterface.OnClickListener() {   
     public void onClick(DialogInterface dialog, int which) { 
      // ... 
     } 
    });  
AlertDialog ad = builder.create(); 
ad.show(); 
+0

안녕하세요,이 줄에 또한 오류를 보여줍니다 : dataBase.insert (TABLE_NAME, values); – Dunkey

관련 문제