我已经创建了一个数据库应用程序,我正在使用预先创建的数据库。这个应用程序是显示cse电子书的下载链接,但是当我点击Myappactivity.java上的按钮后转到intent 2,然后出现错误并且app停止。 感谢所有人回复。
Myappactivity.java
package com.nic;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
public class MyappActivity extends Activity {
/** Called when the activity is first created. */
LinearLayout l;
EditText name ;
Spinner sub ;
SQLiteDatabase db;
RadioButton i_yr;
RadioButton ii_yr;
RadioButton iii_yr;
RadioButton iv_yr;
String sub2[] = {"Digital Electronics","Electronic Devices and Circuits","Data Structures and Algorithms","Discrete Mathematical Structures","Mathematics III","Internet Technology","Principles of Prog Language","Microprocessor and Interfaces","Object Oriented Programming Languages","Computer Architecture","Statistics and Probability Theory","Management Information Systems"};
String sub3[] = {"Software Engineering","System Software Engineering","Database Management System","Computer Graphics","Advanced Java","Advanced Data Structures","Operating Systems","Computer Networks","Design and Analysis of Algorithms","Embedded Systems","Theory Of Computation","Multimedia Systems"};
String sub4[] = {"Compiler Construction","Data Mining and Warehousing","Advanced Logic Systems","Artifical Intelligence","Advanced Software Engineering","Real Time Systems","Information and Security Systems","CAD for VLSI","Advanced Computer Architecture","Distributed Systems"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
l=(LinearLayout)findViewById(R.id.Layout);
l.setBackgroundColor(Color.CYAN);
name = (EditText)findViewById(R.id.name);
sub = (Spinner)findViewById(R.id.subject);
i_yr = (RadioButton)findViewById(R.id.i_year);
ii_yr = (RadioButton)findViewById(R.id.ii_year);
iii_yr = (RadioButton)findViewById(R.id.iii_year);
iv_yr = (RadioButton)findViewById(R.id.iv_year);
}
public void onrbClicked (View v) {
boolean checked = ((RadioButton) v).isChecked();
switch(v.getId()) {
case R.id.i_year:{
if (checked){
ArrayAdapter<String> ob = (new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,sub3));
sub.setAdapter(ob);
}
}break;
case R.id.ii_year:{
if (checked){
ArrayAdapter<String> ob = (new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,sub2));
sub.setAdapter(ob);
}
}break;
case R.id.iii_year:{
if (checked){
ArrayAdapter<String> ob = (new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,sub3));
sub.setAdapter(ob);
}
}break;
case R.id.iv_year:{
if (checked){
ArrayAdapter<String> ob = (new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,sub4));
sub.setAdapter(ob);
}
}
break ;
}
}
public void ok (View v){
Bundle b = new Bundle();
b.putString("name", name.getText().toString());
b.putString("subject", sub.getSelectedItem().toString());
Intent i = new Intent(MyappActivity.this,Showbooks.class);
i.putExtras(b);
startActivity(i);
}
}
Showbooks.java
package com.nic;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Showbooks extends Activity {
TextView tV ;
ListView lview;
private Cursor employees;
private MyDatabase db;
ExpandableListView lView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nextview);
tV = (TextView)findViewById(R.id.tV);
lview = (ListView)findViewById(R.id.list);
Bundle bundle = getIntent().getExtras();
db = new MyDatabase(this);
employees = db.getBooks(); // you would not typically call this on the main thread
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
employees,
new String[] {"book_name"},
new int[] {android.R.id.text1});
lview.setAdapter(adapter);
tV.setText("Welcome " +bundle.getCharSequence("name")+
("\n You want book names of - "+bundle.getCharSequence("subject")));
}
@Override protected void onDestroy()
{
super.onDestroy();
employees.close();
db.close();
}
}
MyDatabase.java
package com.nic;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "cse_books.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// you can use an alternate constructor to specify a database location
// (such as a folder on the sd card)
// you must ensure that this folder is available and you have permission
// to write to it
//super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
}
public Cursor getBooks() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"book_name", "down_link"};
String sqlTables = "csebooks";
// String [] sub_name = {""+subject};
// String whereClause = "sub_name = ?";
qb.setTables(sqlTables);
Cursor c = db.query("csebooks", sqlSelect, null, null, null, null, null);
c.moveToFirst();
return c;
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/Layout">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your Name"
android:inputType="text" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_weight="0.04"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/i_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onrbClicked"
android:text="I Year" />
<RadioButton
android:id="@+id/ii_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onrbClicked"
android:text="II Year" />
<RadioButton
android:id="@+id/iii_year"
android:layout_width="109dp"
android:layout_height="wrap_content"
android:onClick="onrbClicked"
android:text="III Year" />
<RadioButton
android:id="@+id/iv_year"
android:layout_width="wrap_content"
android:layout_height="31dp"
android:onClick="onrbClicked"
android:text="IV Year" />
<Spinner
android:id="@+id/subject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Select your Subject" />
<Button
android:id="@+id/ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="ok"
android:text="SUBMIT" />
</RadioGroup>
</LinearLayout>
nextview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
<TextView
android:id="@+id/tV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.07"
android:text="List of Books"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
答案 0 :(得分:0)
您是否已将数据库从资产位置复制到本地存储(即内部应用程序数据文件夹)? 我曾使用DatabaseHelper类来做到这一点。 代码如下:
<强> DatabaseHelper.java 强>
package com.package;
import java.io.*;
import java.sql.*;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//Using Existing Db
private static String DB_PATH = "/data/data/com.package/databases/";
private static String DB_NAME = <database_name>;
private SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context; //Using Existing Db
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}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 {
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 does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* 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.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.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();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
然后我使用了这样的数据库:
myDbHelper = new DatabaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
//throw sqle;
}
db = myDbHelper.getWritableDatabase();
然后您可以使用游标执行查询。