Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android SQLitedatabase每个用户名都有相同的列表_Android_Listview_Sqlite - Fatal编程技术网

Android SQLitedatabase每个用户名都有相同的列表

Android SQLitedatabase每个用户名都有相同的列表,android,listview,sqlite,Android,Listview,Sqlite,在我的应用程序数据库中,我有两个表,一个叫做“玩家”,保存每个用户的数据,另一个叫做“好友列表”,它是每个注册帐户的个人“好友”列表。在我的应用程序中,这个过程是如何进行的,当一个玩家(乔)注册用户名时,他的信息进入“玩家”中现在他可以进入MyFindFriends活动,在应用程序中搜索他朋友的用户名(Bob),然后单击ADD按钮 然后,好友(Bob)被添加到“FRIENDSLIST”表中。当他进入PlayAFriend活动时,将加载一个列表,显示他添加的“好友”。所有这些都很有效,直到我意识到

在我的应用程序数据库中,我有两个表,一个叫做“玩家”,保存每个用户的数据,另一个叫做“好友列表”,它是每个注册帐户的个人“好友”列表。在我的应用程序中,这个过程是如何进行的,当一个玩家(乔)注册用户名时,他的信息进入“玩家”中现在他可以进入MyFindFriends活动,在应用程序中搜索他朋友的用户名(Bob),然后单击ADD按钮

然后,好友(Bob)被添加到“FRIENDSLIST”表中。当他进入PlayAFriend活动时,将加载一个列表,显示他添加的“好友”。所有这些都很有效,直到我意识到当我登录到他的一个好友帐户(Bob)时,该好友的列表与(Joe)的列表相同

我知道我用来加载(Joe)朋友列表的光标与我用来加载(Bob)朋友列表的光标相同,所以我要问的问题是

我如何让乔和鲍勃有他们自己的朋友名单

我曾尝试在这个网站上搜索和谷歌搜索,以找到任何关于如何实现这一点的例子,但我发现我没有找到任何关于这一主题的教程或帖子,这是疯狂的,即使这种做法在每一个流行的应用程序中都使用。很抱歉,我知道这不是一个简单的问题,所以我必须详细解释问题是什么

我正在发布我的DBAdapter类,以显示我是如何使它适应这个问题的,并且我的PlayAFriend类将显示我的游标和ListView

DBAdapter类

package com.fullfrontalgames.numberfighter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "_id";

    static final String KEY_USERNAME = "USERNAME";

    static final String KEY_PASSWORD = "PASSWORD";

    static final String KEY_EMAIL = "EMAIL";

    static final String KEY_NUMBERINPUT = "NUMBERINPUT";

    static final String KEY_SCORE = "SCORE";

    static final String KEY_FRIENDS = "FRIENDS";

    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "NFDatabase";

    static final String DATABASE_TABLE1 = "PLAYERS";

    static final String DATABASE_TABLE2 = "FRIENDSLIST";

    static final int DATABASE_VERSION = 4;

    static final String DATABASE_CREATE_TABLE1 = "create table PLAYERS ( _id integer primary key autoincrement, "
            + "USERNAME text not null unique,PASSWORD text not null,EMAIL text,NUMBERINPUT text,SCORE text);";

    static final String DATBASE_CREATE_TABLE2 = "create table FRIENDSLIST (_id integer primary key autoincrement,"
            + "FRIENDS text not null,USERNAME text ,NUMBERINPUT text,SCORE text);";

    final Context context;

    DatabaseHelper DBHelper;

    static SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            // TODO Auto-generated constructor stub
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try {
                db.execSQL(DATABASE_CREATE_TABLE1);
                db.execSQL(DATBASE_CREATE_TABLE2);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS PLAYERS");
            db.execSQL("DROP TABLE IF EXISTS FRIENDSLIST");
            onCreate(db);
        }

    }

    public DBAdapter open() throws SQLiteException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        DBHelper.close();
    }

    // PLAYERS TABLE CRUD

    public long insertPlayer(String Username, String Password, String Email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("USERNAME", Username);
        initialValues.put("PASSWORD", Password);
        initialValues.put("EMAIL", Email);

        db.insert("PLAYERS", null, initialValues);

        return db.insertWithOnConflict("PLAYERS", null, initialValues,
                SQLiteDatabase.CONFLICT_IGNORE);
    }

    public boolean deletePlayer(long id) {
        Log.d(TAG, "delete is working");
        return db.delete("PLAYERS", KEY_ROWID + " = " + id, null) > 0;

    }

    public Cursor getAllPlayers() {
        return db.query(false, "Players", new String[] {
                "_id", "USERNAME", "PASSWORD", "EMAIL"
        }, null, null, null, null, null, null);

    }

    public String getData() {
        String[] columns = new String[] {
                "_id", "USERNAME", "PASSWORD"
        };
        Cursor mCursor = db.query("PLAYERS", columns, null, null, null, null, null);
        String result = "";
        int iRow = mCursor.getColumnIndex(KEY_ROWID);
        int iName = mCursor.getColumnIndex(KEY_USERNAME);

        for (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) {
            result = mCursor.getString(iRow) + " " + mCursor.getString(iName) + "/n";
        }
        return result;
    }

    public Cursor getPlayer(int _id) throws SQLException {
        Cursor mCursor = db.query(true, "PLAYERS", new String[] {
                "_id", "USERNAME"
        }, KEY_ROWID + " =  " + "_id", null, null, null, null, null);
        while (mCursor.moveToNext()) {
            int id = mCursor.getInt(mCursor.getColumnIndex("_id"));
        }
        return mCursor;
    }

    public String getUsername(String Username) {
        Cursor mCursor = db.query("Players", new String[] {
            "USERNAME"
        }, "USERNAME = ?", new String[] {
            Username
        }, null, null, null);
        if (mCursor.moveToNext())
            return mCursor.getString(0);
        else
            return "";
    }

    public String getSinlgeEntry(String Username) {
        Cursor cursor = db.query("PLAYERS", null, " USERNAME=?", new String[] {
            Username
        }, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;
    }

    public boolean updatePlayer(long _id, String Username, String Password, String Email) {
        ContentValues args = new ContentValues();
        args.put("USERNAME", Username);
        args.put("PASSWORD", Password);
        args.put("EMAIL", Email);
        return db.update("PLAYERS", args, KEY_ROWID + " = " + _id, null) > 0;
    }

    // FRIENDS TABLE CRUD

    public void insertFriend(String Friend) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("FRIENDS", Friend);
        db.insert("FRIENDSLIST", null, initialValues);
    }

    public boolean deleteFriend() {
        return db.delete("FRIENDSLIST", KEY_ROWID + " = " + "_id", null) > 0;
    }

    public Cursor getAllFriends() {
        return db.query(false, "FRIENDSLIST", new String[] {
                "_id", "FRIENDS"
        }, null, null, null, null, null, null);
    }

    public Cursor getFriend(long rowid) throws SQLException {
        Cursor mCursor = db.query(true, "FRIENDSLIST", new String[] {
                "_id", "FRIENDS"
        }, KEY_ROWID + " =  " + "_id", null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateFriend(long _id, String Friends) {
        ContentValues args = new ContentValues();
        args.put("FRIENDS", Friends);

        return db.update("FRIENDSLIST", args, KEY_ROWID + " = " + _id, null) > 0;
    }

}
新DBAdapter

package com.fullfrontalgames.numberfighter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "_id";

    static final String KEY_USERNAME = "USERNAME";

    static final String KEY_PASSWORD = "PASSWORD";

    static final String KEY_EMAIL = "EMAIL";

    static final String KEY_NUMBERINPUT = "NUMBERINPUT";

    static final String KEY_SCORE = "SCORE";

    static final String KEY_FRIENDS = "FRIENDS";

    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "NFDatabase";

    static final String DATABASE_TABLE1 = "PLAYERS";

    static final String DATABASE_TABLE2 = "FRIENDSLIST";

    static final int DATABASE_VERSION = 9;

    static final String DATABASE_CREATE_TABLE1 = "create table PLAYERS ( _id integer primary key autoincrement, "
            + "USERNAME text not null unique,PASSWORD text not null,EMAIL text,NUMBERINPUT text,SCORE text);";

    static final String DATBASE_CREATE_TABLE2 = "create table FRIENDSLIST (_id integer primary key autoincrement,"
            + "player_id integer not null references PLAYERS(_id) on update cascade on delete cascade,"
            + "FRIENDS text ,NUMBERINPUT text,SCORE text);";

    final Context context;

    DatabaseHelper DBHelper;

    static SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            // TODO Auto-generated constructor stub
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try {
                db.execSQL(DATABASE_CREATE_TABLE1);
                db.execSQL(DATBASE_CREATE_TABLE2);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS PLAYERS");
            db.execSQL("DROP TABLE IF EXISTS FRIENDSLIST");
            onCreate(db);
        }

    }

    public DBAdapter open() throws SQLiteException {
        db = DBHelper.getWritableDatabase();
        db.execSQL("PRAGMA foreign_keys=ON;");
        return this;
    }

    public void close() {
        DBHelper.close();
    }

    // PLAYERS TABLE CRUD

    public long insertPlayer(String Username, String Password, String Email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("USERNAME", Username);
        initialValues.put("PASSWORD", Password);
        initialValues.put("EMAIL", Email);

        db.insert("PLAYERS", null, initialValues);

        return db.insertWithOnConflict("PLAYERS", null, initialValues,
                SQLiteDatabase.CONFLICT_IGNORE);
    }

    public boolean deletePlayer(long id) {
        Log.d(TAG, "delete is working");
        return db.delete("PLAYERS", KEY_ROWID + " = " + id, null) > 0;

    }

    public Cursor getAllPlayers() {
        return db.query(false, "Players", new String[] {
                "_id", "USERNAME", "PASSWORD", "EMAIL"
        }, null, null, null, null, null, null);

    }

    public String getData() {
        String[] columns = new String[] {
                "_id", "USERNAME", "PASSWORD"
        };
        Cursor mCursor = db.query("PLAYERS", columns, null, null, null, null, null);
        String result = "";
        int iRow = mCursor.getColumnIndex(KEY_ROWID);
        int iName = mCursor.getColumnIndex(KEY_USERNAME);

        for (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) {
            result = mCursor.getString(iRow) + " " + mCursor.getString(iName) + "/n";
        }
        return result;
    }

    public Cursor getPlayer(int _id) throws SQLException {
        Cursor mCursor = db.query(true, "PLAYERS", new String[] {
                "_id", "USERNAME"
        }, KEY_ROWID + " =  " + "_id", null, null, null, null, null);
        while (mCursor.moveToNext()) {
            int id = mCursor.getInt(mCursor.getColumnIndex("_id"));
        }
        return mCursor;
    }

    public String getUsername(String Username) {
        Cursor mCursor = db.query("Players", new String[] {
            "USERNAME"
        }, "USERNAME = ?", new String[] {
            Username
        }, null, null, null);
        if (mCursor.moveToNext())
            return mCursor.getString(0);
        else
            return "";
    }

    public String getSinlgeEntry(String Username) {
        Cursor cursor = db.query("PLAYERS", null, " USERNAME=?", new String[] {
            Username
        }, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;
    }

    public boolean updatePlayer(long _id, String Username, String Password, String Email) {
        ContentValues args = new ContentValues();
        args.put("USERNAME", Username);
        args.put("PASSWORD", Password);
        args.put("EMAIL", Email);
        return db.update("PLAYERS", args, KEY_ROWID + " = " + _id, null) > 0;
    }

    // FRIENDS TABLE CRUD

    public void insertFriend(long playerId, String Friend) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("player_id", playerId);
        initialValues.put("FRIENDS", Friend);
        db.insertWithOnConflict("FRIENDSLIST", null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
    }

    public boolean deleteFriend() {
        return db.delete("FRIENDSLIST", KEY_ROWID + " = " + "_id", null) > 0;
    }

    public Cursor getAllFriends() {
        return db.query(false, "FRIENDSLIST", new String[] {
                "_id", "FRIENDS"
        }, null, null, null, null, null, null);
    }

    public Cursor getFriend(long player_id) throws SQLException {
        Cursor mCursor = db.query(true, "FRIENDSLIST", new String[] {
                "_id", "FRIENDS"
        }, "player_id" + " =  " + "player_id", null, null, null, null, null);
        // cursor from query is never null,
        // should just check for if (cursor.moveToFirst()) in the calling
        // activity
        return mCursor;
    }

    public boolean updateFriend(long _id, String Friends) {
        ContentValues args = new ContentValues();
        args.put("FRIENDS", Friends);

        return db.update("FRIENDSLIST", args, KEY_ROWID + " = " + _id, null) > 0;
    }

    public long getPlayerId(String Username) {
        // TODO Auto-generated method stub
        long id = 0;
        Cursor c = db.query("PLAYERS", new String[] {
            KEY_ROWID
        }, KEY_USERNAME + "=?", new String[] {
            Username
        }, null, null, null);
        if (c.moveToFirst()) {
            id = c.getLong(0);
        }
        c.close();
        return id;
    }

}


New PlayAFriend




package com.fullfrontalgames.numberfighter;

import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;

public class PlayAFriend extends ListActivity {

    DBAdapter DBAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playafriend);

        final DBAdapter db = new DBAdapter(this);
        DBAdapter = db.open();

        long player_id = 0;
        getListView().setAdapter(new FriendsListAdapter(this, db.getFriend(player_id)));

    }

    private class FriendsListAdapter extends BaseAdapter implements OnClickListener, ListAdapter {
        private static final long player_id = 0;

        private Cursor fFriends;

        private Context fContext;

        public FriendsListAdapter(Context context, Cursor friends) {
            // TODO Auto-generated constructor stub
            fContext = context;
            fFriends = friends;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return fFriends.getCount();
        }

        @Override
        public FriendInfo getItem(int position) {
            // TODO Auto-generated method stub
            if (fFriends.moveToPosition(position)) {
                String name = fFriends.getString(fFriends.getColumnIndex("FRIENDS"));

                return new FriendInfo(name);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            fFriends.moveToPosition(position);
            return fFriends.getLong(fFriends.getColumnIndex("_id"));
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = LayoutInflater.from(fContext).inflate(R.layout.playafriendlistitems,
                        parent, false);
            }
            FriendInfo friendinfo = getItem(position);
            TextView friendTV = ViewHolder.get(convertView, R.id.textview_friends);
            Button playbutton = ViewHolder.get(convertView, R.id.playbutton, position);
            playbutton.setOnClickListener(this);

            friendTV.setText(friendinfo.getName());

            return convertView;
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            DBAdapter db = new DBAdapter(fContext);
            db.open();
            int position = (Integer)v.getTag();
            fFriends.moveToPosition(position);
            long id = fFriends.getLong(fFriends.getColumnIndex("_id"));
            fFriends = db.getFriend(id);
            db.close();
        }

    }

}
LogCat

 04-22 21:11:37.834: E/SQLiteDatabase(15862): Error inserting player_id=0 FRIENDS=null
    04-22 21:11:37.834: E/SQLiteDatabase(15862): android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
    04-22 21:11:37.834: E/SQLiteDatabase(15862):    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    04-22 21:11:37.834: E/SQLiteDatabase(15862):    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)

更改您的表格
FRIENDSLIST

static final String DATBASE_CREATE_TABLE2 = 
    "create table FRIENDSLIST (_id integer primary key autoincrement,"
    + "player_id integer not null references PLAYERS("_id") on update cascade on delete cascade,"
        + "FRIENDS text not null,USERNAME text ,NUMBERINPUT text,SCORE text);";  
当你插入

public void insertFriend(long playerId, String Friend) {
    ContentValues initialValues = new ContentValues();
    initialValues.put("player_id", playerId);
    initialValues.put("FRIENDS", Friend);
    db.insertWithOnConflict("FRIENDSLIST", null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
}  
交朋友

public Cursor getFriend(long rowid) throws SQLException {
    Cursor mCursor = db.query(true, "FRIENDSLIST", new String[] {
            "_id", "FRIENDS"
    }, player_id + " =  " + "rowid", null, null, null, null, null);
    // cursor from query is never null, 
    // should just check for if (cursor.moveToFirst()) in the calling activity
    return mCursor;
}  
在数据库打开方法中添加

public DBAdapter open() throws SQLiteException {
    db = DBHelper.getWritableDatabase();
    db.execSQL("PRAGMA foreign_keys=ON;"); 
    return this;
}

更改您的表格
FRIENDSLIST

static final String DATBASE_CREATE_TABLE2 = 
    "create table FRIENDSLIST (_id integer primary key autoincrement,"
    + "player_id integer not null references PLAYERS("_id") on update cascade on delete cascade,"
        + "FRIENDS text not null,USERNAME text ,NUMBERINPUT text,SCORE text);";  
当你插入

public void insertFriend(long playerId, String Friend) {
    ContentValues initialValues = new ContentValues();
    initialValues.put("player_id", playerId);
    initialValues.put("FRIENDS", Friend);
    db.insertWithOnConflict("FRIENDSLIST", null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
}  
交朋友

public Cursor getFriend(long rowid) throws SQLException {
    Cursor mCursor = db.query(true, "FRIENDSLIST", new String[] {
            "_id", "FRIENDS"
    }, player_id + " =  " + "rowid", null, null, null, null, null);
    // cursor from query is never null, 
    // should just check for if (cursor.moveToFirst()) in the calling activity
    return mCursor;
}  
在数据库打开方法中添加

public DBAdapter open() throws SQLiteException {
    db = DBHelper.getWritableDatabase();
    db.execSQL("PRAGMA foreign_keys=ON;"); 
    return this;
}

您的代码将有重大更改。设计正确的数据库是项目开始时最重要的事情。我做了所有这些,但似乎用户仍然有相同的朋友在getFriend中rowid应该指玩家id,也就是玩家表中的id。只是让我试试你告诉我的,你仍然需要改变一些事情,就像现在的getAllFriends一样,这将获得表中的所有行,我更改的那一行将获得特定玩家的所有朋友。如果你想知道好友行的id来获取好友的姓名,那么创建一个方法getFriendName(长id),其中该id是好友主键,而不是玩家id。你也必须更改更新方法。代码中会有实质性的更改。设计正确的数据库是项目开始时最重要的事情。我做了所有这些,但似乎用户仍然有相同的朋友在getFriend中rowid应该指玩家id,也就是玩家表中的id。只是让我试试你告诉我的,你仍然需要改变一些事情,就像现在的getAllFriends一样,这将获得表中的所有行,我更改的那一行将获得特定玩家的所有朋友。如果你想获得一个知道朋友行id的朋友的名字,那么创建一个方法getFriendName(长id),其中该id是朋友的主键,而不是玩家id。你也必须更改更新方法。