如何从登录的用户过滤ListView?

I want my Android project to have a ListView that will able to let the users see their own posts. I have done the one-to-many relationship on my serverside database using the username to determine who is the poster of which post. How can I filter the ListView to the corresponding username of the logged in username. I used SharedPreferences for login...

well, here are my codes.

Login

MainActivity

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {


final String TAG = this.getClass().getName();
Button btnLogin;
EditText etUsername, etPassword;
TextView tvRegister;
CheckBox cbRemember;
SharedPreferences pref;
SharedPreferences.Editor editor;
boolean checkFlag;
int x = 0;
Toolbar toolbar;
public static final String pref_name = "your shared preference name";
String userId = "userID";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    etUsername = (EditText) findViewById(R.id.etFirstname);
    etPassword = (EditText) findViewById(R.id.etPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    tvRegister = (TextView) findViewById(R.id.tvRegister);
    cbRemember = (CheckBox) findViewById(R.id.cbRemember);
    cbRemember.setOnCheckedChangeListener(this);
    checkFlag = cbRemember.isChecked();

    pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
    editor = pref.edit();


    final String username = pref.getString("username", "");
    String password = pref.getString("password", "");

    HashMap postData = new HashMap();
    postData.put("username", username);
    postData.put("password", password);

    if (!username.equals("") && (!password.equals(""))) {
        PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
                new AsyncResponse() {
                    @Override
                    public void processFinish(String s) {

                if (s.contains("renter")) {
                    Log.d(TAG, s);
                    Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
                    Intent in = new Intent(MainActivity.this, ListActivity.class);
                    startActivity(in);

                    finish();

                } else if (s.contains("owner")) {
                    Log.d(TAG, s);
                    Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
                    Intent in = new Intent(MainActivity.this, ownerhome.class);
                    startActivity(in);
                    finish();
                } else {
                    Toast.makeText(MainActivity.this, "Login Failed!", Toast.LENGTH_SHORT).show();
                }

                    }
                });
        task1.execute("http://carkila.esy.es/authenticate.php");

    }

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HashMap postData = new HashMap();


            postData.put("username", etUsername.getText().toString());
            postData.put("password", MD5.encrypt(etPassword.getText().toString()));

            PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
                    new AsyncResponse() {
                        @Override
                        public void processFinish(String s) {
                            Log.d(TAG,s);
                            if (s.contains("renter")) {
                                if (checkFlag) {


                                    editor.putString("username", etUsername.getText().toString());
                                    editor.putString("password", MD5.encrypt(etPassword.getText().toString()));


                                    editor.apply();

                                    Log.d(TAG, pref.getString("password", ""));
                                }

                                Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
                                Intent in = new Intent(MainActivity.this, ListActivity.class);
                                startActivity(in);
                                finish();

                            } else if (s.contains("owner")) {

                                if (checkFlag) {


                                    editor.putString("username", etUsername.getText().toString());
                                    editor.putString("password", MD5.encrypt(etPassword.getText().toString()));


                                    editor.apply();
                                }

                                editor.putString("username", etUsername.getText().toString());
                                editor.putString("password", MD5.encrypt(etPassword.getText().toString()));
                                editor.apply();

                                Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
                                Intent in = new Intent(MainActivity.this, ownerhome.class);
                                startActivity(in);
                                finish();
                            } else {
                                Toast.makeText(MainActivity.this, "Login Failed!", Toast.LENGTH_SHORT).show();
                            }


                        }
                    });
            task1.execute("http://carkila.esy.es/authenticate.php");
        }
    });

    tvRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent in = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(in);
            finish();

        }
    });
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    checkFlag = isChecked;
    Log.d(TAG, "checkflag: " + checkFlag);
}


}

Authenticate.php

    <?php 
require 'database-config.php';

session_start();


$username = "";
$password = "";

if(isset($_POST['username'])){
$username = $_POST['username'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
if (isset ($_SESSION['userID'])){
$userID = $_SESSION['userID'];
}


$q = 'SELECT * FROM tbl_user WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));


if($query->rowCount() == 0){
header('Location: Login.php?err=1');
}else{

$row = $query->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['userID'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['roles'];



if( $_SESSION['sess_userrole'] == "renter"){
echo "renter";

echo $_SESSION['sess_user_id'];



}else if ($_SESSION['sess_userrole'] == "owner"){
echo "owner";

echo $_SESSION['sess_user_id'];


}
}
?>          

The listview I wanted to be filtered with who posted it based on who logs in.

ownerhome

public class ownerhome extends AppCompatActivity implements AsyncResponse, AdapterView.OnItemClickListener {
final String TAG = this.getClass().getName();
private ArrayList<Cars> carList;
private ListView lvCars;
private FunDapter<Cars> adapter;
SharedPreferences pref;
SharedPreferences.Editor editor;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ownerhome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ImageLoader.getInstance().init(UILConfig.config(ownerhome.this));


    lvCars = (ListView) findViewById(R.id.lvOnwer);

    pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);

    Log.d(TAG, pref.getString("username", ""));
    Log.d(TAG, pref.getString("password", ""));

PostResponseAsyncTask taskRead = new PostResponseAsyncTask(ownerhome.this, this);

    taskRead.execute("http://carkila.esy.es/user.php");

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent in = new Intent(ownerhome.this, InsertActivity.class);
            startActivity(in);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater findMenuItems = getMenuInflater();
    findMenuItems.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if(id == R.id.action_logout){
        editor = pref.edit();
        editor.clear();
        editor.commit();
        Intent in = new Intent(ownerhome.this, MainActivity.class);
        startActivity(in);
        finish();
    }
    return super.onOptionsItemSelected(item);
}


@Override
public void processFinish(String s) {
    Log.d(TAG, s);


    carList = new JsonConverter<Cars>().toArrayList(s,Cars.class);

    BindDictionary<Cars> dict = new BindDictionary<Cars>();

    dict.addDynamicImageField(R.id.ivImg, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return product.Image;
        }
    }, new DynamicImageLoader() {
        @Override
        public void loadImage(String url, ImageView imageView) {

            ImageLoader.getInstance().displayImage(url, imageView); // Default options will be used

        }
    });
    dict.addStringField(R.id.tvCarModel, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Car Model: " + product.Car_Model;
        }
    });
    dict.addStringField(R.id.tvCarType, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Car Type: " + product.Car_Type;
        }
    });

    dict.addStringField(R.id.tvCapacity, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Capacity: " + product.Capacity;
        }
    });
    dict.addStringField(R.id.tvFuelType, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Fuel Type: " + product.FuelType;
        }
    });
    dict.addStringField(R.id.tvPlateNumber, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Plate Number: " + product.PlateNumber;
        }
    });
    dict.addStringField(R.id.tvPoster, new StringExtractor<Cars>() {
        @Override
        public String getStringValue(Cars product, int position) {
            return "Posted by: " + product.owner;
        }
    });


adapter = new FunDapter<>(
        ownerhome.this, carList, R.layout.layout_list, dict);

lvCars.setAdapter(adapter);
lvCars.setOnItemClickListener(this);

}



@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Cars selectedCars = carList.get(position);
    Intent in = new Intent(ownerhome.this, DetailActivity.class);
    in.putExtra("cars", selectedCars);
    startActivity(in);
}
}

user.php

<?PHP
include_once("connection.php");

session_start();

$query = "SELECT * FROM tbl_cars ORDER BY Car_No DESC "; 

$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
}
echo json_encode($data);

?>

Cars

public class Cars implements Serializable {

@SerializedName("Car_No")
public int Car_No;

@SerializedName("Car_Model")
public String Car_Model;

@SerializedName("Car_Type")
public String Car_Type;

@SerializedName("Capacity")
public  int Capacity;

@SerializedName("Image")
public String Image;

@SerializedName("fuelType")
public String FuelType;

@SerializedName("carPlatenuNumber")
public String PlateNumber;

@SerializedName("owner")
public String owner;

}
douji4223
douji4223 -当然先生,我会发布我的确在这里。:)我会编辑它。
大约 4 年之前 回复
dsj8086
dsj8086 你是如何收到数据的?我假设您拥有当前用户的用户名,但每个帖子是否包含创建它的用户名?你能展示一些代码吗?
大约 4 年之前 回复
douhan4812
douhan4812 -是的先生我正在使用php先生从数据库中获取数据
大约 4 年之前 回复
dougong8012
dougong8012 是否已向服务器端写了一些API请求以从数据库中检索数据?
大约 4 年之前 回复

3个回答



使用 $ GET </ code>进行json过滤。</ p>

  $ where =''; 
if(isset($ _ GET ['owner'])){
$ where =“WHERE owner like'%”。addslashes($ _ GET ['owner'])。“%'” ;
}
$ query =“SELECT * FROM tbl_cars”。$ where。“ORDER BY Car_No DESC”;

</ code> </ pre>

在</ p>

  PostResponseAsyncTask taskRead = new PostResponseAsyncTask(ownerhome.this,this); 
\ ntaskRead.execute(“http://carkila.esy.es/user.php”);
</ code> </ pre>

替换 taskRead.execute(“http:/ /carkila.esy.es/user.php“); </ code>与 taskRead.execute(”http://carkila.esy.es/user.php?“+ pref.getString(”username“, “”)); </ code> </ p>
</ div>

展开原文

原文

Use $GET for the json filtering.

$where = '';
if (isset($_GET['owner'])){
$where = " WHERE owner like '%".addslashes($_GET['owner'])."%'";
}
$query = "SELECT * FROM tbl_cars ".$where." ORDER BY Car_No DESC"; 

And on the

PostResponseAsyncTask taskRead = new PostResponseAsyncTask(ownerhome.this, this);

taskRead.execute("http://carkila.esy.es/user.php");

replace taskRead.execute("http://carkila.esy.es/user.php"); with taskRead.execute("http://carkila.esy.es/user.php?"+pref.getString("username", ""));



如果我没有正确理解你的数据存储,请纠正我,但我假设你的意思是你创造了某种< code> post </ code>对象,它有一个存储数据的位置,并知道是谁发布了它, user_id </ code>。</ p>

假设您要填充列表视图 使用id为 34 </ code>的用户发出的所有帖子。</ p>

通过 user_id <运行查询到服务器过滤 post </ code> / code>应返回该用户的帖子列表。</ p>

IE http:// [你的API的网址] /帖子?user_id = 34 </ code>会返回一个回复,其中包含“user_id”= 34 </ code>的所有帖子。</ p>
</ DIV>

展开原文

原文

Correct me if I'm not understanding your data storage correctly, but I'm assuming you mean you've created some sort of post object which has a place to store data, and knows who posted it, user_id.

Say you wanted to populate a list view with all posts made by user with id 34.

Running a query to your server filtering posts by user_id should return a list of posts by that user.

I.E. http://[url to your API]/posts?user_id=34 would return a response including all posts with "user_id"=34.

doutang2017
doutang2017 I.E. http:// [你的API的网址] /帖子?user_id = 34会返回一个回复,其中包含“user_id”= 34的所有帖子。 是不是正在过滤我的json先生:c
大约 4 年之前 回复
duanju8308
duanju8308 你理解正确的先生。 :D但我使用用户名过滤它们,因为我不能用id做。 用户名在db btw上是唯一的。 :)
大约 4 年之前 回复

There are multiple ways of filtering a Collection. You could even do this server-side if you wanted to. But, since it seems like you want to do it client-side, I will show you how you can filter a list on Android.

Assuming that your carList has a username field, you can create a new ArrayList and populate it with only the Cars that contain the correct username:

String username = pref.getString("username", "");

List<Cars> filteredList = new ArrayList<>();

for(Cars car : carList) {
    if(car.owner == username) {
        filteredList.add(car);
    }
}

Then you can just use this new ArrayList to populate your ListView.

dsjhejw3232
dsjhejw3232 好吧,这意味着你的carList包含空值,或者你没有调用String username = prefs.getString(“username”,“”);.
大约 4 年之前 回复
dqq22391
dqq22391 if(car.owner == username)为空先生。 是的,我在实例化carlist后调用它。
大约 4 年之前 回复
duanke3985
duanke3985 什么对象是null? 确保在实例化carList后调用此方法。
大约 4 年之前 回复
dongting3135
dongting3135 它在for语句先生上给出了NullPointerException。 :(
大约 4 年之前 回复
dongshenyu4638
dongshenyu4638 完全没有,我只是想了解,虽然我觉得我没有多少帮助。 不,BindDictionary应该在循环之后。 而且我相信您会使用filteredList创建一个新的FunDapter,尽管我对您使用的库没有任何经验。
大约 4 年之前 回复
douyicao2199
douyicao2199 我很烦你,我知道先生,我很抱歉呵呵。 我应该把绑定字典放在if语句中吗? 因为它给了我一个NullPointerException
大约 4 年之前 回复
dongtai6741
dongtai6741 是的,只要您想过滤列表。 此代码只会根据用户名获取筛选列表,您可以在有意义的地方使用它。
大约 4 年之前 回复
dougan6402
dougan6402 给cars对象一个getUsername()方法,它从“owner”字段返回String,并将它与你已经拥有的用户名字段进行比较,就像我在上面的代码中所示。
大约 4 年之前 回复
drmcm84800
drmcm84800 好的,所以如果tbl_cars有一个“owner”字段,那么你的Cars对象也应该有一个“owner”字段,不是吗? 因此,您可以使用该字段,并将其与当前用户的用户名进行比较。
大约 4 年之前 回复
doujiepin5547
doujiepin5547 好吧,tbl_cars有“用户名”字段吗?
大约 4 年之前 回复
dongtui2029
dongtui2029 好的,更好的问题,你的数据库中的tbl_cars是“帖子”列表还是那个别的?
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐