2013-03-14 2 views
0

아래 코드를 사용하여 SQLite 데이터베이스에서 Android Listview를 채우려고했습니다. 나는 같은 클래스의 배열에서 성공적으로이 작업을 수행했다. 하지만이 경우에는 다른 클래스에서 반환 한 String 배열에서 채우려고합니다. 나는 이것에 익숙하지 않기 때문에이 일을 완전히 잘못했을 수도 있습니다. 누구든지 코드를보고 내가 잘못하고있는 것에 조언하면 훌륭합니다.SQLite 데이터베이스에서 Android Listview 채우기

정말 도움이 될 것입니다. 끝내야한다는 심각한 압력을 받고 있습니다. 감사합니다.

LoginActivity 클래스

공용 클래스 LoginActivity를 확장 활동 {

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 
    final EditText txtUserName = (EditText)findViewById(R.id.txtUsername); 
    final EditText txtPassword = (EditText)findViewById(R.id.txtPassword); 
    Button btnLogin = (Button)findViewById(R.id.btnLogin); 
    btnLogin.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      String username = txtUserName.getText().toString(); 
      String password = txtPassword.getText().toString(); 

      try{ 
       if(username.length() > 0 && password.length() >0) 
       { 
        DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this); 
        dbUser.open(); 

        int UID = dbUser.Login(username, password); 

        if(UID != -1) 
        { 
         // TEST 
         //int UID = dbUser.getUserID(username, password); 
         //getSitesByClientname(UID); 
         // END TEST 
         // MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES 
           Intent myIntent = new Intent(LoginActivity.this, ClientSites.class); 
           //Intent myIntent = new Intent(getApplicationContext(), ClientSites.class); 
           myIntent.putExtra("userID", UID); 
           startActivity(myIntent); 
           //finish(); 
         // END MY TEST CODE 

         //Cursor UserID = dbUser.getUserID(); 

         Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show(); 
        }else{ 
         Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show(); 
        } 
        dbUser.close(); 
       } 

      }catch(Exception e) 
      { 
       Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show(); 
      } 
     } 

    }); 
} 

}

방법 문자열 배열을 반환 할 DBHelper 클래스에서

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

    //return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args); 

     Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args); 
     // loop through all rows and adding to array 
     int count; 
     count = myCursor.getCount(); 
     final String[] results = new String[count]; 
     results[0] = new String(); 
     int i = 0; 
     try{ 
      if (myCursor.moveToFirst()) { 
       do { 
        results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename")); 

       } while (myCursor.moveToNext()); 
      } 
     }finally{ 
      myCursor.close(); 
     } 
     db.close(); 
     // return results array 
     return results; 

ClientSites 클래스

공용 클래스 ClientSites 좋은 것 ListActivity {

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

    private DBUserAdapter dbHelper = null; 
    //private Cursor ourCursor = null; 
    private ArrayAdapter<String> adapter=null; 


    //@SuppressWarnings("deprecation") 
    @SuppressLint("NewApi") 
    public void onCreate(Bundle savedInstanceState) { 
     try 
     { 
      super.onCreate(savedInstanceState); 
      //setContentView(R.layout.client_sites); 

      Intent i = getIntent(); 
      String uID = String.valueOf(i.getIntExtra("userID", 0)); 
      //int uID = i.getIntExtra("userID", 0); 

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

      dbHelper = new DBUserAdapter(this); 

      dbHelper.createDatabase(); 

      //dbHelper.openDataBase(); 
      dbHelper.open(); 

      String[] results = dbHelper.getSitesByClientname(uID); 

      //setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results)); 
      //adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results); 
      setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results)); 

      //ListView myListView = (ListView)findViewById(R.id.myListView); 
      ListView listView = getListView(); 
      listView.setTextFilterEnabled(true); 

      //@SuppressWarnings("deprecation") 
      //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); 
      //CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0); 
      //adapter = new Adapter(ourCursor); 

      //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show(); 

      //myListView.setAdapter(adapter); 

      //myListView.setOnItemClickListener(onListClick); 


     } 
     catch (Exception e) 
     { 
      Log.e("ERROR", "XXERROR IN CODE: " + e.toString()); 
      e.printStackTrace(); 
     } 
    } 

}이와

어떤 도움을 확장합니다, 감사합니다!

+0

나는 작동하지 않는 것을 이해하지 못합니까? – njzk2

+0

DB에서 값을 얻거나 ListView를 채우는 데 문제가 있습니까? –

+0

죄송합니다. 문제는 ListView를 데이터로 채우는 것입니다. 나는 다른 DB 클래스에 넣기 만하면 문제가있는 곳이지만 깨닫지 못했다. 이 점을 분명히하지 못해 죄송합니다. – Confucius

답변

0

몇 가지 활동으로 자신의 프로젝트를 만듭니다. sqlite 데이터베이스 작업 시작

새 응용 프로그램 만들기. 로그인 활동 및 DB 도우미를 작성하십시오. DB에서 데이다를 업로드하려고합니다. Reseach and development 다음은 SQLite DB를 사용하는 방법의 예입니다.

public class DBHelper extends SQLiteOpenHelper { 

private static DBHelper instance; 
private static final String DATABASE_NAME = "UserClientBase"; 
    private static final int DATABASE_VERSION = 1; 
public static interface USER extends BaseColumns { 
     String TABLE_NAME = "userTable"; 
     String NAME = "userName"; 
     String PASSWORD = "userPassword"; 
    } 
public static interface CLIENT extends BaseColumns { 
     String TABLE_NAME = "clientTable"; 
     String NAME = "clientName"; 
     String USER_ID = "userId"; 
    } 
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "; 
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS "; 
    private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT"; 
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID 
      + " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);"; 
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID 
      + " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);"; 
private DBHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 
public static DBHelper getInstance(Context context) { 
     if (instance == null) { 
      instance = new DBHelper(context); 
     } 
     return instance; 
    } 
@Override 
    public void onCreate(SQLiteDatabase db) { 
     db.execSQL(CREATE_TABLE_USER); 
     db.execSQL(CREATE_TABLE_CLIENT); 
    } 
@Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     db.execSQL(DROP_TABLE + USER.TABLE_NAME); 
     db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME); 
     onCreate(db); 
    } 
public long createUser(String newUserName, String newUserPassword) { 
     ContentValues values = new ContentValues(); 
     values.put(USER.NAME, newUserName); 
     values.put(USER.PASSWORD, newUserPassword); 
     return getWritableDatabase().insert(USER.TABLE_NAME, null, values); 
    } 
public long createClient(long userId, String newClientName) { 
     ContentValues values = new ContentValues(); 
     values.put(CLIENT.USER_ID, userId); 
     values.put(CLIENT.NAME, newClientName); 
     return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values); 
    } 
public boolean isCorrectLoginPassword(String login, String password) { 
     Cursor userListCursor = getReadableDatabase().rawQuery(
       "SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD 
         + " =?", new String[] { login, password }); 
     if ((userListCursor != null) && (userListCursor.getCount() > 0)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 
public Cursor getUserClientList(String userName) { 
     Cursor userClientList = getReadableDatabase().rawQuery(
       "SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME 
         + " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE " 
         + USER.NAME + " =?", new String[] { userName }); 
     return userClientList; 
    } 
} 

Example of login button click listener. 
String login = loginEdt.getText().toString(); 
String password = passwordEdt.getText().toString(); 
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password); 
if(loginSuccess) { 
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class); 
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login); 
startActivity(clientListIntent); 
} else { 
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show(); 
} 

And example of listview with data from sql: 

clientLv= (ListView)findViewById(R.id.listClient); 
login = getIntent().getExtras().getString(EXTRAS_LOGIN); 
dbHelper = DBHelper.getInstance(this); 
Cursor clientList = dbHelper.getUserClientList(login); 
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); 
clientLv.setAdapter(adapter); 
관련 문제