Код для DBHelper
класса:
class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = Environment.getDataDirectory()
+ "/data/test.data/databases/";
private static final String DATABASE_NAME = "test.sqlite3";
private static final int SCHEMA_VERSION = 1;
public static final String TABLE_NAME = "terran_builds";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_OVERVIEW = "overview";
public SQLiteDatabase dbSqlite;
private final Context myContext;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbExist = DBExists();
if (!dbExist) {
this.getReadableDatabase();
copyDBFromResource();
}
}
private boolean DBExists() {
SQLiteDatabase db = null;
try {
String databasePath = DATABASE_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.setVersion(1);
} catch (SQLiteException e) {
Log.e("SqlHelper", "database not found");
}
if (db != null) {
db.close();
}
return db != null ? true : false;
}
private void copyDBFromResource() {
InputStream inputStream = null;
OutputStream outStream = null;
String dbFilePath = DATABASE_PATH + DATABASE_NAME;
try {
inputStream = myContext.getAssets().open(DATABASE_NAME);
outStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
outStream.flush();
outStream.close();
inputStream.close();
} catch (IOException e) {
throw new Error("Problem copying database from resource file.");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
// TODO Auto-generated method stub
if (dbSqlite != null) {
dbSqlite.close();
}
super.close();
}
public Cursor getTerran() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
COLUMN_OVERVIEW };
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, "name");
return mCursor;
}
public String getName(Cursor c) {
return (c.getString(1));
}
}
Код для Terran
активности:
public class Terran extends Activity {
private DBHelper dbHelp = null;
private Cursor ourCursor = null;
private DBAdapter adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.terran_layout);
// this is our listview element, obtained by id from our xml layout
ListView myListView = (ListView) findViewById(R.id.tvterran);
// create our database helper
dbHelp = new DBHelper(this);
// we call the create right afther initializing helper
dbHelp.createDatabase();
// open the database
dbHelp.openDataBase();
// get our cursor
ourCursor = dbHelp.getTerran();
// tell android to start managing cursor
startManagingCursor(ourCursor);
// create our adapter
adapter = new DBAdapter(ourCursor);
// set the adapter
myListView.setAdapter(adapter);
} catch (Exception e) {
// send real error message
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
class DBAdapter extends CursorAdapter {
DBAdapter(Cursor c) {
super(Terran.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
// TODO Auto-generated method stub
terranHolder holder = (terranHolder) row.getTag();
holder.populateFrom(c, dbHelp);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.terran_layout, parent, false);
terranHolder holder = new terranHolder(row);
row.setTag(holder);
return (row);
}
}
static class terranHolder {
private TextView name = null;
terranHolder(View row) {
name = (TextView) row.findViewById(R.id.tvterran);
}
void populateFrom(Cursor c, DBHelper r) {
name.setText(r.getName(c));
}
}
}
Logcat
исключение:
01-30 20:07:13.765: E/ERROR(7153): ERROR IN CODE: java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): at com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
01-30 20:07:13.775: W/System.err(7153): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 20:07:13.775: W/System.err(7153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-30 20:07:13.775: W/System.err(7153): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1499)
01-30 20:07:13.775: W/System.err(7153): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-30 20:07:13.775: W/System.err(7153): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:731)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost.setCurrentTab(TabHost.java:403)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost.addTab(TabHost.java:242)
Я не могу получить ListView
для генерации из результатов запроса.Из своей отладки я понимаю, что ошибка в классе Terran
на line 46
.Я не могу понять, что не так.Протестировано с другой базой данных, соединение с базой данных работает.