J. Shmoe J. Shmoe - 3 months ago 5
MySQL Question

How to filter ListView from the user that is logged in?

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;

}

Answer

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", ""));

Comments