Java 从SQLite数据库填充Android Listview

Java 从SQLite数据库填充Android Listview,java,android,sqlite,Java,Android,Sqlite,我一直在尝试使用下面的代码从SQLite数据库填充Android Listview。我已经在同一个类中的数组中成功地完成了这项工作。但在本例中,我试图从另一个类返回的字符串数组中填充它。我是新来的,所以我可能做得完全错误。如果有人能看一下代码并指出我做错了什么,那就太棒了 任何帮助都将非常感谢,因为我正面临着完成它的巨大压力,谢谢 后勤活动类 公共类LoginActivity扩展了活动{ @Override protected void onCreate(Bundle savedInstance

我一直在尝试使用下面的代码从SQLite数据库填充Android Listview。我已经在同一个类中的数组中成功地完成了这项工作。但在本例中,我试图从另一个类返回的字符串数组中填充它。我是新来的,所以我可能做得完全错误。如果有人能看一下代码并指出我做错了什么,那就太棒了

任何帮助都将非常感谢,因为我正面临着完成它的巨大压力,谢谢

后勤活动类

公共类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();
            }
        }

    });
}
    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();
        }
    }
}

方法从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扩展了ListActivity{

@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();
            }
        }

    });
}
    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();
        }
    }
public final静态字符串ID\u EXTRA=“com.example.loginfromlocal.\u ID”;
私有DBUserAdapter dbHelper=null;
//私有游标ourCursor=null;
专用ArrayAdapter适配器=null;
//@抑制警告(“弃用”)
@SuppressLint(“新API”)
创建时的公共void(Bundle savedInstanceState){
尝试
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_站点);
Intent i=getIntent();
stringuid=String.valueOf(i.getIntExtra(“userID”,0));
//int uID=i.getIntExtra(“userID”,0);
//ListView myListView=(ListView)findViewById(R.id.myListView);
dbHelper=新的DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[]results=dbHelper.getSitesByClientname(uID);
//setListAdapter(新的ArrayAdapter(ClientSites.this,R.id.myListView,results));
//adapter=newarrayadapter(ClientSites.this、R.id.myListView、results);
setListAdapter(新的ArrayAdapter(ClientSites.this、R.layout.client_sites、results));
//ListView myListView=(ListView)findViewById(R.id.myListView);
ListView ListView=getListView();
setTextFilterEnabled(true);
//@抑制警告(“弃用”)
//SimpleCursorAdapter=新的SimpleCursorAdapter(getBaseContext(),R.id.myListView,null,null);
//CursorAdapter=new SimpleCursorAdapter(this,R.id.myListView,null,null,0);
//适配器=新适配器(光标);
//Toast.makeText(ClientSites.this,“Booo!!!”,Toast.LENGTH\u LONG.show();
//myListView.setAdapter(适配器);
//myListView.setOnItemClickListener(onListClick);
}
捕获(例外e)
{
Log.e(“ERROR”,“XXERROR IN CODE:+e.toString());
e、 printStackTrace();
}
}
}


这方面的任何帮助都会很好,谢谢

创建自己的项目,活动很少。开始使用sqlite数据库

创建新的应用程序。创建登录活动和DB助手。正在尝试从数据库上载数据。研究与开发 下面是一个如何使用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);

我不明白什么不起作用?从DB检索值或填充ListView是否有问题?抱歉,伙计们,问题是用数据填充ListView。我只是加入了另一个DB类,以防万一这就是我遇到问题的地方,但我没有意识到。很抱歉没有澄清这一点。@最好使用cursorAdapter。使用cursorAdapter填充listview很容易。如果有人能向我指出我为填充listview提供的代码中明显存在的错误,我将非常感谢,因为我真的必须完成这项工作。无论是以建议或代码的形式。非常感谢。