从数据库onitemclick listview中检索数据到TextView中的另一个Activity

时间:2013-12-28 21:27:40

标签: android sqlite listview

我有两项活动: -Term活动:listview - 详细活动:textview

我想在我的DetailActivity中显示一个textView,来自我的数据库,关于onclickitem的上一个活动,TermActivity。

其实我只能得到id或“Android.database.sqlite.SQLiteCursor@45cabae8”所以我认为我的代码是错的。

DetailActivity

package com.example.afpcv2;

import com.example.afpcv2.DetailActivity;
import com.example.afpcv2.SocActivity;
import com.example.afpcv2.R;
import com.example.afpcv2.SocActivity.SocHolder;
import com.example.afpcv2.TermActivity.TermAdapter;
import com.example.afpcv2.TermActivity.TermHolder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class DetailActivity extends Activity{

String passedVar=null;
private TextView passedView=null;
private Cursor ourCursor = null;
private SoclistHelper dbSocHelper = null;
private DetailAdapter adapter=null;


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

    passedVar=getIntent().getStringExtra(TermActivity.ID_EXTRA);
    passedView=(TextView)findViewById(R.id.bookText);

    dbSocHelper=new SoclistHelper(this);

    ourCursor=dbSocHelper.getDetailByTerm(passedVar);
    startManagingCursor(ourCursor);

    adapter=new DetailAdapter(ourCursor);


    if(ourCursor != null){
        if(ourCursor.moveToFirst()){
            String value = ourCursor.getString(ourCursor.getColumnIndex("Grade1"));
            passedView.setText("Definition " + value);
        }
    }




}

class DetailAdapter extends CursorAdapter {
    DetailAdapter(Cursor c) {
        super(DetailActivity.this, c);

    }

    public void bindView(View row, Context ctxt, 
            Cursor c) {
        DetailHolder holder=(DetailHolder)row.getTag();
        holder.populateFrom(c, dbSocHelper);

    }

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


}

static class DetailHolder {
    private TextView name=null;

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

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

}

学期活动

package com.example.afpcv2;

import com.example.afpcv2.TermActivity;
import com.example.afpcv2.SocActivity;
import com.example.afpcv2.R;
import com.example.afpcv2.SocActivity.SocHolder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;



public class TermActivity extends Activity{

public final static String ID_EXTRA="com.example.afpcv2._ID";

String passedVar=null;
private TextView passedView=null;
private SoclistHelper dbSocHelper = null;
private Cursor ourCursor = null;
private TermAdapter adapter=null;




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

    passedVar=getIntent().getStringExtra(SocActivity.ID_EXTRA);

    ListView myListView = (ListView)findViewById(R.id.myListView);

    dbSocHelper=new SoclistHelper(this);

    ourCursor=dbSocHelper.getTermBySoc(passedVar);

    startManagingCursor(ourCursor);

    adapter=new TermAdapter(ourCursor);

    myListView.setAdapter(adapter);

    myListView.setOnItemClickListener(onListClick);

}

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, 
            View view, int position,
            long id)
    {
        Intent i=new Intent(TermActivity.this, DetailActivity.class);

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

    }
};


class TermAdapter extends CursorAdapter {
    TermAdapter(Cursor c) {
        super(TermActivity.this, c);

    }

    public void bindView(View row, Context ctxt, 
            Cursor c) {
        TermHolder holder=(TermHolder)row.getTag();
        holder.populateFrom(c, dbSocHelper);

    }

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


}

static class TermHolder {
    private TextView name=null;

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

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

}

我的DatabaseHelper

package com.example.afpcv2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

public class SoclistHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.afpcv2/databases/";
private static String DB_NAME = "soclist.db";
private static final String TABLE_NAME = "Soc";
private static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "soc_name";

private static final String SECOND_TABLE_NAME = "Term";
private static final String SECOND_COLUMN_ID = "_id";
public static final String SECOND_COLUMN_TITLE = "term_name";

private static final String THIRD_TABLE_NAME = "Detail";
private static final String THIRD_COLUMN_ID = "_id";
public static final String THIRD_COLUMN_TITLE = "Grade1";


private SQLiteDatabase myDataBase; 

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public SoclistHelper(Context context) {

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


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) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

    // Add your public helper methods to access and get content from the database.
   // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
   // to you to create adapters for your views.
public Cursor getCursor() {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

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

        //make sure get search by string pass correctly
        Cursor mCursor = queryBuilder.query(myDataBase, asColumnsToReturn, null, 
                null, null, null, "soc_name ASC");



        return mCursor;

    }

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

    }

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

        return(getReadableDatabase()
                .rawQuery("SELECT _id, term_name FROM Term WHERE soc_id=?",
                        args));
    }

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

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Term_name FROM Detail WHERE Term_id=?",
                        args));
    }

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

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Grade1 FROM Detail WHERE Term_id=?",
                        args));
    }
    public Cursor getDetailByTerm3(String id) {
        String[] args={id};

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Grade2 FROM Detail WHERE Term_id=?",
                        args));
    }
    public Cursor getDetailByTerm4(String id) {
        String[] args={id};

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Grade3 FROM Detail WHERE Term_id=?",
                        args));
    }
    public Cursor getDetailByTerm5(String id) {
        String[] args={id};

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Grade4 FROM Detail WHERE Term_id=?",
                        args));
    }
    public Cursor getDetailByTerm6(String id) {
        String[] args={id};

        return(getReadableDatabase()
                .rawQuery("SELECT _id, Grade5 FROM Detail WHERE Term_id=?",
                        args));
    }

}

告诉我你是否需要更多信息。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

问题出现在这一行:passedView.setText("Definition "+ourCursor);

您必须从要从光标

显示的列中获取值
if(ourCursor != null){
    if(ourCursor.moveToFirst()){
        string value = ourCursor.getString(ourCursor.getColumnIndex("term_name"));
        passedView.setText("Definition " + value);
    }
}