2017-10-10 39 views
-2

我有一個問題,我需要從我的數據庫中提取一些數據,但我無法準確創建SQL查詢,我的意思是。 我想從CARS和PLANES表格中檢索「_id」和「NAME」,當選中複選框(FAVORITE)時。如何在rawQuery中創建確切的SQL查詢?

請耐心等待,我只是在學習SQL。

順便說一句,如果我已經有了一個名單充滿了數據和我
想轉到相應的活動,怎麼辦呢,如果 名單充滿了如2-3個活動?

DataBaseHelper.class

public class DataBaseHelper extends SQLiteOpenHelper { 


public void onCreate(SQLiteDatabase db) { 

db.execSQL("CREATE TABLE CARS (_id INTEGER KEY AUTOINCREMENT, " 
         + "NAME TEXT, " 
         + "IMAGE_RESOURCE_ID INTEGER, " 
         + "FAVORITE INTEGER);"); 

db.execSQL("CREATE TABLE PLANES (_id INTEGER KEY AUTOINCREMENT, " 
         + "NAME TEXT, " 
         + "IMAGE_RESOURCE_ID INTEGER, " 
         + "FAVORITE INTEGER);"); 

      etc.. 
      } 
      } 

NewActivity.class

public class NewActivity extends AppCompatActivity { 

protected void onCreate(Bundle savedInstanceState){ 

    ListView listfavorites = findViewById(R.id.favorites); 

try{ 
     SQLiteOpenHelper helper = new DataBaseHelper(this); 
     SQLiteDatabase db = helper.getReadableDatabase(); 

// Now with this query, my list is filled with all the data, when I tickle 
// which object is the favorite. 

Cursor favorite = db.rawQuery ("SELECT CARS._id, PLANES._id, 
CARS.NAME, PLANES.NAME FROM CARS, 
PLANES WHERE 
    CARS.FAVORITE=1 AND 
PLANES.FAVORITE=1, null); 

    CursorAdapter favoriteAdapter = new 
SimpleCursorAdapter(NewActivity.this,    
    android.R.layout.simple_list_item_1, 
favorite, 
new String[]{"NAME", 
    new int[]}{android.R.id.text1},0); 

    listfavorites.setAdapter(favoriteAdapter); 

      }catch(SQLite Exception e){ 
      Toast.makeText(this, "Database not available", 
      Toast.LENGTH_SHORT).show(); } 


// By the way, if I already have a list filled up with data and I 
// would like to go to the corresponding activity, how to do it if 
// the list is filled with eg 2-3 activity?  

    listfavorites.setOnItemClickListener(new AdapterView.OnItemClickListener(){  

      public void onItemClick(AdapterView<?> parent, View view, int position, long id){ 
      Intent intent = new Intent(this, Cars.class);  
      intent.putExtra(Cars.EXTRA_CAR, (int)id);  
      startActivity(intent); 
      } }); 

       } 
      } 

回答

0

你的SQL壞了。你所做的將會加入這兩個表格,並且會返回兩行都是最喜歡的組合。相反,你想要兩個不同的SQL查詢的聯合,一個得到你最喜歡的汽車和一個你最喜歡的飛機。

https://www.w3schools.com/sql/sql_union.asp

+0

我建立了一個這樣的查詢,但它仍然無法正常工作,我究竟做錯了什麼?最喜歡的= db.rawQuery(「SELECT _id,CARS.NAME從CARS WHERE CARS.FAVORITE = 1 UNION SELECT _id,PLANES.NAME FROM PLANES WHERE PLANES.FAVORITE = 1」,null); java.IllegalArgumentException:列'_id'不存在? – newActivity21