2016-02-27 43 views
-2

檢索數據,我正在嘗試從sqlite的數據,但我不知道什麼是錯我的代碼從SQLite的

public class MainPage extends AppCompatActivity { 
    private RequestQueue requestQueue; 
    private String user,position; 
    private DatabaseHelper helper; 
    private List<User> user_position; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     helper=new DatabaseHelper(this); 
     if (helper.getUserlogin()==0) { 
      finish(); 
     startActivity(new Intent(getApplicationContext(), LoginActivity.class)); 
     }else { 
      setContentView(R.layout.activity_main_page); 

     user_position= helper.getUserPosition(); 
     user = String.valueOf(user_position.get(0).getUserName()); 
     position=String.valueOf(user_position.get(1).getUserPosition()); 
     TextView textView = (TextView) findViewById(R.id.user); 
     textView.setText(user+"("+position+")"); 
    } 
} 

,這是數據庫的讀寫方法

public List<User> getUserPosition() { 

     List<User> oList = new ArrayList<User>(); 

     SQLiteDatabase db = getReadableDatabase(); 

     Cursor cursor = db.query(ORDER_TABLE, null, null, null, null, null, 
       null); 


      User user = new User(); 
      user.setUserName(cursor.getString(cursor 
        .getColumnIndex(ROW_USER))); 
      user.setUserPosition(cursor.getString(cursor 
        .getColumnIndex(ROW_POSITION))); 

      oList.add(user); 

     if (cursor != null) 
      cursor.close(); 

     if (db != null) 
      db.close(); 

     return oList; 

    } 
+1

什麼是不工作的清單?什麼是預期的結果和你得到什麼? – Rohit5k2

+0

你在哪裏初始化'helper'? – Rohit5k2

+0

是的我會編輯的問題更清楚@ Rohit5k2 –

回答

0

你是不循環遊標,所以返回的數組中沒有結果(遊標在第一個結果之前開始,並且您還沒有使用moveToFirst())。

更換

User user = new User(); 
user.setUserName(cursor.getString(cursor 
       .getColumnIndex(ROW_USER))); 
user.setUserPosition(cursor.getString(cursor 
       .getColumnIndex(ROW_POSITION))); 
oList.add(user); 

while (cursor.moveToNext()) { 
    User user = new User(); 
    user.setUserName(cursor.getString(cursor 
       .getColumnIndex(ROW_USER))); 
    user.setUserPosition(cursor.getString(cursor 
       .getColumnIndex(ROW_POSITION))); 
    oList.add(user); 
} 

更新:您正在返回從DB

user_position = helper.getUserPosition(); 
if(user_position.size() > 0){ 
    User user = user_position.get(0); 
    user = String.valueOf(user.getUserName()); 
    position=String.valueOf(user.getUserPosition()); 
    TextView textView = (TextView) findViewById(R.id.user); 
    textView.setText(user+"("+position+")"); 
} 
else 
    Log.e("No user", "NO user found"); 
+0

謝謝先生,但不工作也 –

+0

是它顯示此錯誤: 引起:java.lang.NullPointerException at com.amaiub.hussain.smartmenu.MainPage.onCreate(MainPage.java:91) –

+0

這意味着在這個問題行: user_position = helper.getUserPosition(); user = String.valueOf(user_position.get(0).getUserName()); position = String.valueOf(user_position.get(1).getUserPosition()); –