使用现有数据库

时间:2011-12-25 13:38:44

标签: android

您好, 我正在构建一个使用现有数据库的Android应用程序。但是,应用程序无法在我的设备上正常运行。

这是我的代码:

Mainactivity.java:

public class MainActivity extends TabActivity {

    Cursor model = null;
    TerrainAdapter adapter = null;
    TextView nom = null;
    TextView prenom = null;
    TextView fonction = null;
    terrainHelper helper = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    helper = new terrainHelper(this);
    nom = (TextView) findViewById(R.id.nom);
    prenom = (TextView) findViewById(R.id.prenom);
    fonction = (TextView) findViewById(R.id.fonction);


    ListView list = (ListView) findViewById(R.id.terrains);

    model = helper.getAll();
    startManagingCursor(model);
    adapter = new TerrainAdapter(model);
    list.setAdapter(adapter);

    TabHost.TabSpec spec = getTabHost().newTabSpec("tag1");

    spec.setContent(R.id.terrains);
    spec.setIndicator("List", getResources().getDrawable(R.drawable.list));
    getTabHost().addTab(spec);

    spec = getTabHost().newTabSpec("tag2");

    spec.setContent(R.id.details);
    spec.setIndicator("Details", getResources().getDrawable(R.drawable.terrain));
    getTabHost().addTab(spec);

    getTabHost().setCurrentTab(0);

    list.setOnItemClickListener(onListClick);
}

@Override
public void onDestroy() {
    super.onDestroy();

    helper.close();
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        model.moveToPosition(position);

        nom.setText(helper.getNom(model));
        prenom.setText(helper.getPrenom(model));
        fonction.setText(helper.getFonction(model));

        getTabHost().setCurrentTab(1);
    }
};

class TerrainAdapter extends CursorAdapter {

    TerrainAdapter(Cursor c) {
        super(MainActivity.this, c);
    }

    @Override
    public void bindView(View row, Context ctxt, Cursor c) {
        TerrainHolder holder = (TerrainHolder) row.getTag();
        holder.populateFrom(c, helper);
    }

    @Override
    public View newView(Context ctxt, Cursor c, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.row, parent, false);
        TerrainHolder holder = new TerrainHolder(row);

        row.setTag(holder);

        return (row);
    }
}

static class TerrainHolder {

    private TextView ville = null;
    private TextView tache = null;

    TerrainHolder(View row) {
        ville = (TextView) row.findViewById(R.id.ville);
        tache = (TextView) row.findViewById(R.id.tache);

    }

    void populateFrom(Cursor c, terrainHelper helper) {
        ville.setText(helper.getNom(c));
        tache.setText(helper.getFonction(c));


    }
}

}

terrainHelper:

class terrainHelper extends SQLiteOpenHelper {

//Le path des bases du system Android (attention au nom du package de l'appli).
private static String DB_PATH = "/data/data/com.abouchan.docs/databases/";
//nom de la base
private static String DB_NAME = "db.sqlite3";
// la base
private SQLiteDatabase myDataBase;
// le context
private final Context myContext;

/**
 * Constructeur
 *
 * @param context
 */
public terrainHelper(Context context) {

    super(context, DB_NAME, null, 2);
    this.myContext = context;
}

/**
 * On cré une base vide dans le system Android et on réécris dessus.
 * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        //On fait rien - La base existe déja.
    } else {

        //By calling this method and 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 {

            //Copie de la base
            copyDataBase();

        } catch (IOException e) {

            throw new Error("Erreur de copie de la base !");

        }
    }

}

/**
 * On Check la base pour voir si elle existe ou pas
 *  
 * @return true si la base existe, false si elle existe pas.
 */
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 does't exist yet.
    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/* (non-Javadoc)
 * @see android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()
 */
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
    return super.getReadableDatabase();
}

/**
 * On copie la base depuis le dossier assets dans le dossier system des bases sous android dans la base vide fraichement créé.
 *
 * */
private void copyDataBase() throws IOException {

    //On ouvre la base locale
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // On choisi l'endroit
    String outFileName = DB_PATH + DB_NAME;

    //On ouvre la base vide
    OutputStream myOutput = new FileOutputStream(outFileName);

    //On transfert...
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    //On ferme ...
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

/**
 *Fonction pour acceder à la base en mode lecture seul
 **/
public void openDataBase() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);

}



@Override
public synchronized void close() {

    if (myDataBase != null) {
        myDataBase.close();
    }

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {
    // On ne crées pas de base
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // pas de mis a jour
}

// developper vos methodes d'acces à la base que vous appelerez dans la Main ETC....
public Cursor getAll() {
    return (myDataBase.rawQuery("SELECT nom, prenom, fonction FROM terrain ORDER BY nom ASC", null));

}

public String getNom(Cursor c) {
    return (c.getString(1));
}

public String getPrenom(Cursor c) {
    return (c.getString(2));
}
public String getFonction(Cursor c) {
    return (c.getString(3));
}

}

这是我的logCat:

    ERROR    AndroidRuntime    FATAL EXCEPTION: main
ERROR    AndroidRuntime    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abouchan.docs/com.abouchan.docs.MainActivity}: java.lang.NullPointerException
ERROR    AndroidRuntime        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
ERROR    AndroidRuntime        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
ERROR    AndroidRuntime        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
ERROR    AndroidRuntime        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
ERROR    AndroidRuntime        at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR    AndroidRuntime        at android.os.Looper.loop(Looper.java:130)
ERROR    AndroidRuntime        at android.app.ActivityThread.main(ActivityThread.java:3703)
ERROR    AndroidRuntime        at java.lang.reflect.Method.invokeNative(Native Method)
ERROR    AndroidRuntime        at java.lang.reflect.Method.invoke(Method.java:507)
ERROR    AndroidRuntime        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
ERROR    AndroidRuntime        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
ERROR    AndroidRuntime        at dalvik.system.NativeStart.main(Native Method)
ERROR    AndroidRuntime    Caused by: java.lang.NullPointerException
ERROR    AndroidRuntime        at com.abouchan.docs.terrainHelper.getAll(terrainHelper.java:166)
ERROR    AndroidRuntime        at com.abouchan.docs.MainActivity.onCreate(MainActivity.java:54)
ERROR    AndroidRuntime        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
ERROR    AndroidRuntime        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
ERROR    AndroidRuntime        ... 11 more

1 个答案:

答案 0 :(得分:0)

这是你第一次运行吗?

似乎很简单的事实是您的活动可能未在Manifest.xml中声明

<activity android:name=".MainActivity"></activity>

<activity android:name=".TabActivity"></activity>

至少你需要这样的东西。

希望有所帮助!