从android sqlite数据库中的多个表中检索数据

时间:2014-11-26 09:08:57

标签: android

我正在开发一个android项目,其中我有一个listview,listview包含来自我现有的sqlitedatabase的名为“Android.sqlite”的数据。该数据库包含两个表“users”和“post”。 “users”表包含两个coloumns ID和NAME,来自NAME coloumn的数据显示在listview中。“POST”表包含4个coloumns post_id,postname,post_desc,ID .ID在两个表中都很常见。我需要的是当我点击对于listview中的项目,即数据库表中的NAME,必须检索post_desc coloumn中的相应数据并显示在下一个活动的textview中。

数据库助手类

public class DatabaseHelper extends SQLiteOpenHelper {

public static String DB_PATH = "/data/data/com.example.freshdatabase/databases/";
public static String DB_NAME = "Android.sqlite";
public static final int DB_VERSION = 1;

public static final String TB_USER = "Users";
private SQLiteDatabase myDB;
private Context context;

public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);    
    this.context = context;
}

@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

}

@Override
public synchronized void close(){
    if(myDB!=null){
        myDB.close();
    }
    super.close();

}
private boolean checkDataBase() {
    SQLiteDatabase tempDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        tempDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
        Log.e("tle99 - check", e.getMessage());
    }
    if (tempDB != null)
        tempDB.close();
    return tempDB != null ? true : false;
}
public void copyDataBase() throws IOException{
    try {
        InputStream myInput = context.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;

        while((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (Exception e) {
        Log.e("tle99 - copyDatabase", e.getMessage());
    }

}
public void openDataBase() throws SQLException{
    String myPath = DB_PATH + DB_NAME;
    myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();        

    if (dbExist) {

    } else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e("tle99 - create", e.getMessage());
        }
    }

}

public List<String> getAllUsers(){
    List<String> listUsers = new ArrayList<String>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c;

    try {
        c = db.rawQuery("SELECT * FROM " + TB_USER , null);
        if(c == null) return null;

        String name;
        c.moveToFirst();
        do {            
            name = c.getString(1);            
            listUsers.add(name);
        } while (c.moveToNext()); 
        c.close();
    } catch (Exception e) {
        Log.e("tle99", e.getMessage());
    }

    db.close();        

    return listUsers;
}

}  主要活动类

public class MainActivity extends ActionBarActivity {

DatabaseHelper dbHeplper;

ListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHeplper = new DatabaseHelper(getApplicationContext());
    try {
        dbHeplper.createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ListView lvUsers= (ListView)findViewById(R.id.lvUsers);
    List<String> listUsers = dbHeplper.getAllUsers();

    if(listUsers != null){
        adapter = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_list_item_1, android.R.id.text1,
                listUsers);
        lvUsers.setAdapter(adapter);
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

1 个答案:

答案 0 :(得分:1)

试试这个SQL命令

Select post.post_desc  from users INNER JOIN post ON users.ID=post.ID WHERE NAME='Listview_selected item'

首先向OnItemClickListener实施ListView

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
  "Click ListItem: " + listUsers.get(position), Toast.LENGTH_LONG)
  .show();
}
}); 

现在,在DatabaseHelper中创建一个方法,以便post_desc

获取Name
public String getPostDesc(String Name){

SQLiteDatabase db = this.getWritableDatabase();
Cursor c;

try {
    c = db.rawQuery("Select post.post_desc from users INNER JOIN post ON users.ID=post.ID WHERE NAME='"+Name+"'" , null);

    if(c == null) return null;

    String desc="";

    if(c.moveToFirst()){
      desc= c.getString(0);  
    }

    c.close();
} catch (Exception e) {
    Log.e("tle99", e.getMessage());
}

db.close();        

return desc;
}

现在,在您的ListItemClick(....)中将其称为

 listView.setOnItemClickListener(new OnItemClickListener() {

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

String Desc=dbHeplper.getPostDesc(listUsers.get(position));

Toast.makeText(getApplicationContext(),
  "Desc is: " + Desc, Toast.LENGTH_LONG)
  .show();
}
});