使用Intent检索特定的数据库单元

时间:2013-11-06 12:51:45

标签: android android-intent android-sqlite

我已经回来编写代码了很久以后,几天后仍然遇到我的代码问题。

我的应用中有一个包含两个表的预填充数据库。第一个用于第一个活动(AllEnglandList)并显示一个列表。单击该列表中的一行时,将从第二个表中的数据启动第二个列表视图Activity(Autheils)。为此,我使用了.putExtra,效果很好。

单击此列表中的一行时,我尝试使用单击行中的字符串从数据库中调用特定单元格。因此,例如,如果单击Apple,它将查看我的数据库中的FruitName列,并查看哪一行包含Apple。然后它将读取此行并返回Column FruitDescription的内容。

目前我点击时会收到空白活动(AllEnglandList)。

这是我的助手

class AllEnglandHelper extends SQLiteOpenHelper {

// we declare a bunch of useful constants
// they should be pretty obvious what they are!
private static final String DATABASE_PATH =           "/data/data/com.wills.master/databases/";
private static final String DATABASE_NAME = "Fruit.db";
private static final int SCHEMA_VERSION = 1;
public static final String TABLE_NAME = "Databasing_Index";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "ObjectIndex";

// BE AWARE - if you make changes to your database using sqlitebrower, you
// will need to refresh the assets folder in eclipse
public static final String SECOND_TABLE_NAME = "Databasing_Details";
public static final String SECOND_COLUMN_ID = "_id";
public static final String SECOND_COLUMN_TITLE = "ObjectName";
public static final String SECOND_COLUMN_TITLE2 = "ObjectDescription";

public SQLiteDatabase dbSqlite;

private final Context myContext;

public AllEnglandHelper(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    this.myContext = context;
    // check if exists and copy database from resource
    // createDB();
}

@Override
public void onCreate(SQLiteDatabase db) {
    // check if exists and copy database from resource

}

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

}

public void createDatabase() {
    createDB();
}

private void createDB() {

    boolean dbExist = DBExists();

    if (!dbExist) {

        // By calling the method we create an empty database into the
        // default system location
        // We need this so we can overwrite that database with our database
        this.getReadableDatabase();

        // now we copy the database we included!
        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() {

    if (dbSqlite != null) {
        dbSqlite.close();
    }
    super.close();
}

// the following two methods return the column you want and it's title
// (getName)
public Cursor getCursor() {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    queryBuilder.setTables(TABLE_NAME);

    String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE };

    // make sure you get your search pass correctly!
    Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
            null, null, null, "_id");
    // the name after the nulls dictates how the results are returned. ie in
    // order of "column name"

    return mCursor;
}

public String getName(Cursor c) {
    return (c.getString(1));
    // where 1 refers to COLUMN_TITLE line 11 rows above (0 would be
    // COLUMN_ID and so on)
}

public Cursor getTrailByType(String id) {
    String[] args = {id};

    return (getReadableDatabase()
            .rawQuery("SELECT _id, ObjectName FROM Databasing_Details WHERE Index_id=?", args));
}

public Cursor getTrailByDetails(String id) {
    String[] args = {id};

    return (getReadableDatabase()
            .rawQuery("SELECT _id, ObjectDescription FROM Databasing_Details WHERE ObjectName=?", args));

}

}

第一项活动

public class AllEnglandList extends Activity {

// we use a string to hold the name of our extra,
// it must include the full package name
public final static String ID_EXTRA = "com.wills.master._ID";

private AllEnglandHelper dbDataBaseHelper = null;
private Cursor ourCursor = null;
private DataBaseAdapter adapter = null;

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

        // this is our ListView element, obtained by id from our XML Layout
        ListView myListView = (ListView) findViewById(R.id.list_view);

        // create our database Helper
        dbDataBaseHelper = new AllEnglandHelper(this);
        // we call the create right after initializing the helper, just in
        // case
        // they have never run the app before
        dbDataBaseHelper.createDatabase();
        //
        // open the database!! Our helper now has a SQLiteDatabase database
        // object
        dbDataBaseHelper.openDataBase();
        // get our cursor. A cursor is a pointer to a dataset, in this case
        // a set of results from a database query
        ourCursor = dbDataBaseHelper.getCursor();
        // tell android to start managing the cursor
        // we do this just incase our activity is interrupted or ends, we
        // want the activity
        // to close and deactivate the cursor, as needed
        startManagingCursor(ourCursor);
        // create our adapter
        adapter = new DataBaseAdapter(ourCursor);
        // set the adapter!!!
        myListView.setAdapter(adapter);

        // this is how we know what to do when a list item is clicked
        myListView.setOnItemClickListener(onListClick);
    } catch (Exception e) {

        // this is the line of code that sends a real message to the Log
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());

        // this is the line that prints out the location
        // the code where the error occurred.
        e.printStackTrace();
    }

}

private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // Create our intent, as per usual
        Intent i = new Intent(AllEnglandList.this, AllTrails.class);

        i.putExtra(ID_EXTRA, String.valueOf(id));
        startActivity(i);
    }
};

class DataBaseAdapter extends CursorAdapter {
    DataBaseAdapter(Cursor c) {
        super(AllEnglandList.this, c);
    }

    @Override
    // this is a CursorAdapter
    // instead of Using a getView and if(row=null)
    // we use a bindView and newView calls
    // we can get away with this because CursorAdapters have
    // a default implementation of getView that calls bindView and newView
    // as needed. This makes our code a bit cleaner, and is the better way
    // to
    // do this
    public void bindView(View row, Context ctxt, Cursor c) {
        DataBaseHolder holder = (DataBaseHolder) row.getTag();
        holder.populateFrom(c, dbDataBaseHelper);
    }

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

static class DataBaseHolder {
    private TextView name = null;

    DataBaseHolder(View row) {
        name = (TextView) row.findViewById(R.id.row);

    }

    void populateFrom(Cursor c, AllEnglandHelper r) {
        name.setText(r.getName(c));
    }

}

}

第二项活动

public class AllTrails extends Activity{

String passedVar=null;
boolean passedVar1=false;


public final static String ID_EXTRA = "com.wills.master._ID";

private AllEnglandHelper dbTrailTypeHelper = null;
private Cursor ourCursor = null;
private TrailAdapter adapter=null;

public void onCreate(Bundle savedInstanceState) {
    try {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.trail_list);

    //Get our passed variable from our intent's EXTRAS
    passedVar=getIntent().getStringExtra(AllEnglandList.ID_EXTRA);

    //this is our ListView element, obtained by id from our XML layout
    ListView myListView = (ListView)findViewById(R.id.list_view);

    String string = passedVar;  
    int passedInt = Integer.parseInt(string); 

    if (passedInt==1) { passedVar1 = true;

    }
    //create our database Helper
    dbTrailTypeHelper=new AllEnglandHelper(this);
    //a set of results from a database query
    ourCursor=dbTrailTypeHelper.getTrailByType(passedVar);

    //tell android to start managing the cursor,
    //we do this just incase our activity is interrupted or ends, we want the activity
    //to close and deactivate the cursor, as needed
    startManagingCursor(ourCursor);
    //create our adapter
    adapter=new TrailAdapter(ourCursor);
    //set the adapter!!!
    myListView.setAdapter(adapter);

    myListView.setOnItemClickListener(onListClick);
    } catch (Exception e) {

        // this is the line of code that sends a real message to the Log
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());

        // this is the line that prints out the location
        // the code where the error occurred.
        e.printStackTrace();
    }
}

private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // Create our intent, as per usual
        Intent i = new Intent(AllTrails.this, AllEnglandTrails.class);
        i.putExtra(ID_EXTRA, String.valueOf(id));
        startActivity(i);

    }
};


class TrailAdapter extends CursorAdapter {
    TrailAdapter(Cursor c) {
      super(AllTrails.this, c);
    }
    @Override
    //this is a CusorAdapter
    //instead of Using a getView and if(row==null)
    // we use bindView and newView calls
    //we can get away with this because CursorAdapters have
    //a default implementation of getView that calls bindView and newView
    //as needed.  This makes our code a bit cleaner, and is the better way to 
    //do this.  
    public void bindView(View row, Context ctxt,
                       Cursor c) {
        TrailTypeHolder holder=(TrailTypeHolder)row.getTag();
        holder.populateFrom(c, dbTrailTypeHelper);
    }
    @Override
    public View newView(Context ctxt, Cursor c, ViewGroup parent) {
      LayoutInflater inflater=getLayoutInflater();
      View row=inflater.inflate(R.layout.trail_list, parent, false);
      TrailTypeHolder holder=new TrailTypeHolder(row);
      row.setTag(holder);
      return(row);
    }
  }

static class TrailTypeHolder {
    private TextView name=null;

    TrailTypeHolder(View row) {
        name=(TextView)row.findViewById(R.id.row);
    }

    void populateFrom(Cursor c, AllEnglandHelper r) {
        name.setText(r.getName(c));
    }
}
}

第三项活动

public class AllTrails extends Activity{

String passedVar=null;
boolean passedVar1=false;


public final static String ID_EXTRA = "com.wills.master._ID";

private AllEnglandHelper dbTrailTypeHelper = null;
private Cursor ourCursor = null;
private TrailAdapter adapter=null;

public void onCreate(Bundle savedInstanceState) {
    try {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.trail_list);

    //Get our passed variable from our intent's EXTRAS
    passedVar=getIntent().getStringExtra(AllEnglandList.ID_EXTRA);

    //this is our ListView element, obtained by id from our XML layout
    ListView myListView = (ListView)findViewById(R.id.list_view);

    String string = passedVar;  
    int passedInt = Integer.parseInt(string); 

    if (passedInt==1) { passedVar1 = true;

    }
    //create our database Helper
    dbTrailTypeHelper=new AllEnglandHelper(this);
    //a set of results from a database query
    ourCursor=dbTrailTypeHelper.getTrailByType(passedVar);

    //tell android to start managing the cursor,
    //we do this just incase our activity is interrupted or ends, we want the activity
    //to close and deactivate the cursor, as needed
    startManagingCursor(ourCursor);
    //create our adapter
    adapter=new TrailAdapter(ourCursor);
    //set the adapter!!!
    myListView.setAdapter(adapter);

    myListView.setOnItemClickListener(onListClick);
    } catch (Exception e) {

        // this is the line of code that sends a real message to the Log
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());

        // this is the line that prints out the location
        // the code where the error occurred.
        e.printStackTrace();
    }
}

private AdapterView.OnItemClickListener onListClick = new         AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // Create our intent, as per usual
        Intent i = new Intent(AllTrails.this, AllEnglandTrails.class);
        i.putExtra(ID_EXTRA, passedVar);
        startActivity(i);

    }
};


class TrailAdapter extends CursorAdapter {
    TrailAdapter(Cursor c) {
      super(AllTrails.this, c);
    }
    @Override
    //this is a CusorAdapter
    //instead of Using a getView and if(row==null)
    // we use bindView and newView calls
    //we can get away with this because CursorAdapters have
    //a default implementation of getView that calls bindView and newView
    //as needed.  This makes our code a bit cleaner, and is the better way to 
    //do this.  
    public void bindView(View row, Context ctxt,
                       Cursor c) {
        TrailTypeHolder holder=(TrailTypeHolder)row.getTag();
        holder.populateFrom(c, dbTrailTypeHelper);
    }
    @Override
    public View newView(Context ctxt, Cursor c, ViewGroup parent) {
      LayoutInflater inflater=getLayoutInflater();
      View row=inflater.inflate(R.layout.trail_list, parent, false);
      TrailTypeHolder holder=new TrailTypeHolder(row);
      row.setTag(holder);
      return(row);
    }
  }

static class TrailTypeHolder {
    private TextView name=null;

    TrailTypeHolder(View row) {
        name=(TextView)row.findViewById(R.id.row);
    }

    void populateFrom(Cursor c, AllEnglandHelper r) {
        name.setText(r.getName(c));
    }
}
}

我做了很多搜索,但没有找到任何专门处理此问题的内容。

0 个答案:

没有答案
相关问题