I am building an app in which a client log in and see their transaction base on their customer code ,I would like to know if it's possible to retrieve data from a table just for the user that logged in and display it? and i would like to know how to do it.
Transaction.php
include 'DatabaseConfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT transaction_num, customer_code FROM tbl_order_of_payment";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
DatabaseConfig.php
<?php
//Define your host here.
$HostName = "localhost";
//Define your database username here.
$HostUser = "root";
//Define your database password here.
$HostPass = "";
//Define your database name here.
$DatabaseName = "customer_portal_epayment";
?>
connection.php
$host = "localhost";
$user_name = "root";
$user_password= "";
$db_name = "customer_portal_user";
$conn = mysqli_connect($host,$user_name,$user_password,$db_name);
?>
Login.php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password_hash = $_POST['password_hash'];
require_once 'connect.php';
$sql = "SELECT * FROM user WHERE username='$username'";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1){
$row = mysqli_fetch_assoc($response);
if( password_verify($password_hash, $row['password_hash'] )){
$index['username'] = $row['username'];
$index['email'] = $row['email'];
$index['cust_code'] = $row['cust_code'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
<?php
HttpServicesClass.java
public int responseCode;
public String message;
public String response;
public ArrayList<NameValuePair> ArrayListParams;
public ArrayList <NameValuePair> headers;
public String UrlHolder;
public String getResponse()
{
return response;
}
public String getErrorMessage()
{
return message;
}
public int getResponseCode()
{
return responseCode;
}
public HttpServicesClass(String url)
{
HttpServicesClass.this.UrlHolder = url;
ArrayListParams = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
ArrayListParams.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void ExecuteGetRequest() throws Exception
{
String MixParams = "";
if(!ArrayListParams.isEmpty())
{
MixParams += "?";
for(NameValuePair p : ArrayListParams)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(MixParams.length() > 2)
{
MixParams += "&" + paramString;
}
else
{
MixParams += paramString;
}
}
}
HttpGet httpGet = new HttpGet(UrlHolder + MixParams);
for(NameValuePair h : headers)
{
httpGet.addHeader(h.getName(), h.getValue());
}
executeRequest(httpGet, UrlHolder);
}
public void ExecutePostRequest() throws Exception
{
HttpPost httpPost = new HttpPost(UrlHolder);
for(NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
if(!ArrayListParams.isEmpty())
{
httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8));
}
executeRequest(httpPost, UrlHolder);
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try
{
httpResponse = httpClient.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
response = convertStreamToString(inputStream);
inputStream.close();
}
}
catch (ClientProtocolException e)
{
httpClient.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
httpClient.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is)
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
SessionManager.java
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "LOGIN";
private static final String LOGIN = "IS_LOGIN";
public static final String EMAIL = "EMAIL";
public static final String CUST_CODE = "CUST_CODE";
public static final String USERNAME = "USERNAME";
public SessionManager(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String email, String username, String cust_code){
editor.putBoolean(LOGIN, true);
editor.putString(EMAIL, email);
editor.putString(USERNAME, username);
editor.putString(CUST_CODE, cust_code);
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checklogin(){
if (!this.isLoggin()){
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((HomeActivity)context).finish();
}
}
public HashMap<String, String> getUserDetail(){
HashMap<String, String> user = new HashMap<>();
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
user.put(USERNAME, sharedPreferences.getString(USERNAME, null));
user.put(CUST_CODE, sharedPreferences.getString(CUST_CODE, null));
return user;
}
public void logout(){
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((HomeActivity) context).finish();
}
}
Transaction.java
ListView MobileDetailsListView;
ProgressBar MobileProgressBar;
SessionManager sessionManager;
String HttpUrl = "http://192.168.2.231/android_register_login/TransactionData.php";
List<String> MobileList = new ArrayList<String>();
ArrayAdapter<String> MobileArrayAdapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_epayment);
sessionManager = new SessionManager(this);
sessionManager.checklogin();
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(R.drawable.logocopy);
MobileDetailsListView = (ListView)findViewById(R.id.listview1);
MobileDetailsListView.setEmptyView(findViewById(R.id.empty));
MobileProgressBar = (ProgressBar)findViewById(R.id.progressBar);
new Epayment.GetHttpResponse(Epayment.this).execute();
MobileDetailsListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),ShowDetailsActivity.class);
intent.putExtra("ListViewValue", MobileList.get(position).toString());
startActivity(intent);
}
});
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
public GetHttpResponse(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
MobileList.add(jsonObject.getString("transaction_num").toString());
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
MobileProgressBar.setVisibility(View.GONE);
MobileDetailsListView.setVisibility(View.VISIBLE);
// Start code for remove duplicate listview values.
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(MobileList);
MobileList.clear();
MobileList.addAll(hashSet);
//End code here for remove duplicate values.
MobileArrayAdapter = new ArrayAdapter<String>(Transaction.this,android.R.layout.simple_list_item_2, android.R.id.text1, MobileList);
MobileDetailsListView.setAdapter(MobileArrayAdapter);
}
HashMap<String, String> user = sessionManager.getUserDetail();
String mUsername = user.get(sessionManager.USERNAME);
String mEmail = user.get(sessionManager.EMAIL);
String mCust_code = user.get(sessionManager.CUST_CODE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
Login.java
private EditText username, password_hash;
private Button btn_login;
private TextView link_regist;
private ProgressBar loading;
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static String URL_LOGIN = "http://192.168.2.231/android_register_login/login.php";
SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(this);
loading = findViewById(R.id.loading);
username = findViewById(R.id.username);
password_hash = findViewById(R.id.password_hash);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mUsername = username.getText().toString().trim();
String mPass = password_hash.getText().toString().trim();
if (!mUsername.isEmpty() || !mPass.isEmpty()) {
Login(mUsername, mPass);
} else {
username.setError("Please insert username");
password_hash.setError("Please insert Password");
}
}
});
}
private void Login(final String username, final String password_hush) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String username = object.getString("username").trim();
String email = object.getString("email").trim();
String cust_code = object.getString("cust_code").trim();
sessionManager.createSession(username,email,cust_code);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
intent.putExtra("cust_code", cust_code);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this,"Username and Password don`t match" , Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this,"Email and Password don`t match", Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password_hash", password_hush);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}