Android : Display data in listview depending on the session of the user

on Wednesday, July 9, 2014


Is there's a way that get the data from the MySQL server database display in list view in android depending on the session of the user who log in to the application. the data will be sort depending on the user_id of the user.


this is may Login.java



public class Displayloginpage extends Activity {


Button loginbutton;
EditText usernameedittext,passwordedittext;
TextView tv, forgot;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
// Session Manager Class
SessionManager session;

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

// Session Manager
session = new SessionManager(getApplicationContext());


loginbutton = (Button)findViewById(R.id.loginbtn);
usernameedittext = (EditText)findViewById(R.id.usernameet);
passwordedittext= (EditText)findViewById(R.id.passwordet);
tv = (TextView)findViewById(R.id.tv);
forgot = (TextView) findViewById(R.id.forgottext);

forgot.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
alert();
}
});

loginbutton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

dialog = ProgressDialog.show(Displayloginpage.this, "",
"Validating user...", true);

new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});

}

@SuppressWarnings("deprecation")
public void alert() {
AlertDialog alertDialog = new AlertDialog.Builder(
Displayloginpage.this).create();

// Setting Dialog Title
alertDialog.setTitle("Forget Username/Password");

// Setting Dialog Message
alertDialog.setMessage("Please Contact Your School Administrator");

// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.fail);

// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {

}
});

// Showing Alert Message
alertDialog.show();
}


void login(){
try{

httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.168.1.100:80/ihatid/android/Attender/login_user.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>();
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",usernameedittext.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",passwordedittext.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);

ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});

if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Displayloginpage.this,"Login Success", Toast.LENGTH_SHORT).show();
String username = usernameedittext.getText().toString();
String password = passwordedittext.getText().toString();
session.createLoginSession(username, password);
}
});
Displayloginpage.this.finish();
Intent loginintent = new Intent(getApplicationContext(), DrawerMainActivity.class);
startActivity(loginintent);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}

public void showAlert(){
Displayloginpage.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Displayloginpage.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}


}


this is may main.java



@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @SuppressLint("NewApi") public class Main extends Fragment {

public Main(){

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.main, container, false);
new GetUser().execute();

return rootView;
}
class GetUser extends AsyncTask<String, String, String> {

//private ProgressDialog pDialog;
//String row_id = "1";
String result=null;
InputStream is=null;
String line=null;
String user = "user";



/**
* Before starting background thread Show Progress Dialog
* */
/*
@Override
protected void onPreExecute() {
super.onPreExecute();
Fragment myProfileFragment = null;
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading recipe profile. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}


/**
* After completing background task Dismiss the progress dialog
* **/
/*
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}

*/
/**
* Getting product details in background thread
* */


@Override
public String doInBackground(String... arg0) {

// updating UI from Background Thread

//String returnName, returnIngr, returnProc;


runOnUiThread(new Runnable() {


public void run() {
// Check for success tag
//int success;
String id = "1";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",id));


try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.100:80/ihatid/android/Attender/getattenderuser.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", " connection success ");

}
catch(Exception e) {
Log.e("Fail 1", e.toString());
}

try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Toast shit = Toast.makeText(MyProfileFragment.this, result, Toast.LENGTH_LONG);
//shit.show();
Log.e("pass 2", " connection success ");

}
catch(Exception e){
Log.e("Fail 2", e.toString());
}

try {
JSONObject json_data = new JSONObject(result);
Log.d("User details",json_data.toString());
int code;


code=1;

JSONArray userObj = json_data.getJSONArray("user");
if(code==1) {



String up_name = "schoolname";
String up_add = "name";
String up_eadd = "licenseno";

for (int i = 0; i < userObj.length(); i++) {
JSONObject getrecipe = userObj.getJSONObject(i);



TextView txtName = (TextView) getView().findViewById(R.id.register);
TextView txtAdd = (TextView) getView().findViewById(R.id.name);
TextView txtEAdd = (TextView) getView().findViewById(R.id.license);


txtName.setText(getrecipe.getString(up_name));
txtAdd.setText(getrecipe.getString(up_add));
txtEAdd.setText(getrecipe.getString(up_eadd));

}
}
else if(code==0){
//Toast toast = Toast.makeText(MyProfileFragment.this, "Error: code is equal to 0", Toast.LENGTH_LONG);
//toast.show();
}
}catch(Exception e) {
Log.e("Fail 3", e.toString());
//e.printStackTrace();
}
}
});
return null;
}

private void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub

}
}
}


this is my session.



public class SessionManager {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_EMAIL = "username";

// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";

// Constructor
@SuppressLint("CommitPrefEdits")
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}

/**
* Create login session
* */
public void createLoginSession(String username, String password){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);

// Storing name in pref
editor.putString(KEY_EMAIL, username);

// Storing email in pref
editor.putString(KEY_PASSWORD, password);

// commit changes
editor.commit();
}

/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Displayloginpage.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// Staring Login Activity
_context.startActivity(i);
}

}



/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

// user email id
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));

// return user
return user;
}

/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();

// After logout redirect user to Loing Activity
Intent i = new Intent(_context, Displayloginpage.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// Staring Login Activity
_context.startActivity(i);
}

/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}


my liistvier.java



public class Listattendance extends ListActivity {
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> studentList;
SessionManager session;
// url to get all products list
private static String url_all_student = "http://192.168.1.101:80/ihatid/android/attender/allstudent.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_STUDENT = "student";
private static final String TAG_SNO = "studentno";
private static final String TAG_NAME = "name";
private static final String TAG_LAT = "latitude";
private static final String TAG_LONG = "longitude";

// products JSONArray
JSONArray students = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listattendance);

session = new SessionManager(getApplicationContext());
session.checkLogin();
// Hashmap for ListView
studentList = new ArrayList<HashMap<String, String>>();

// Loading products in Background Thread




// Get listview
//ListView lv = getListView();
//lv.setOnItemClickListener(new OnItemClickListener() {

//@Override
//public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// getting values from selected ListItem
//String sno = ((TextView) view.findViewById(R.id.studentno)).getText().toString();
//String names = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Starting new intent
//Intent in = new Intent(getApplicationContext(), .class);
// sending pid to next activity
//in.putExtra(TAG_SNO, sno);
//in.putExtra(TAG_NAME, names);

// starting new activity and expecting some response back
//startActivity(in);
// }
//});
new LoadAllstudents().execute();
}

// Response from Edit Product Activity
//@Override
//protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if result code 100
// if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
// Intent intent = getIntent();
// finish();
// startActivity(intent);
// }

//}

/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllstudents extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Listattendance.this);
pDialog.setMessage("Loading Students. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params);

// Check your log cat for JSON reponse
Log.d("All Student: ", json.toString());

try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// products found
// Getting Array of Products
students = json.getJSONArray(TAG_STUDENT);

// looping through All Products
for (int i = 0; i < students.length(); i++) {
JSONObject c = students.getJSONObject(i);

// Storing each json item in variable
//String studentid = c.getString(TAG_SNO);
String name = c.getString(TAG_NAME);

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
//map.put(TAG_SNO, studentid);
map.put(TAG_NAME, name);

// adding HashList to ArrayList
studentList.add(map);
}
} else {


Toast.makeText(Listattendance.this, "No student found", Toast.LENGTH_LONG).show();
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Listattendance.this, studentList,
R.layout.listview_item, new String[] {
TAG_NAME },
new int[] { R.id.name });
// updating listview
setListAdapter(adapter);
}
});

}

}
}


After the user login. all i want is to display the users info on the main.java. by the way i'm using Drawer navigation in my android application. Then, when i click the listActivity button this will direct to the xml that will display the data in listview from the database.


My problem is I don't know how to display the user information and display the data depending on the session of the user. Help pleas...thanks in advance... I'm just a beginner...


my php file...this is for getting the user datails



$response = array();


require_once $_SERVER['DOCUMENT_ROOT'] .'/ihatid/android/Connection/connection.php';
$db = new DB_CONNECT();

$username = $_POST['username'];
$password = $_POST['password'];

// get all products from products table
$result = mysql_query("select a.ATTENDER_NO AS ATTENDERNO,CONCAT(a.FIRSTNAME ',' a.MIDDLENAME ',
' a.LASTNAME) AS NAME, a.LICENSE_NO, s.SCHOOLNAME, a.LICENSE_NO,
s.SCHOOLNAME AS SCHOOLNAME, s.SCHOOL_ID from
attender a, school_admin s, vehicle v, vehicle_sched b
where a.ATTENDER_NO = b.ATTENDER_NO
AND v.PLATE_NO = b.PLATE_NO
AND s.SCHOOL_ID = v.SCHOOL_ID
AND a.USERNAME = '$username'
AND a.PASSWORD = '$password'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["attender"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$attender = array();
$attender["schoolname"]= $row["SCHOOLNAME"];
$attender["attenderno"]= $row["ATTENDERNO"];
$attender["name"] = $row["NAME"];
$attender["licenseno"] = $row["LICENSE_NO"];

// push single product into final response array
array_push($response["attender"], $attender);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No attender/s found";

// echo no users JSON
echo json_encode($response);
}
?>


This is the php for login



<?php

//Login code details
$reponse = array();
require_once $_SERVER['DOCUMENT_ROOT'] .'/ihatid/android/Connection/connection.php';
$db = new DB_CONNECT();

$username = $_POST['username'];
$password = $_POST['password'];

// get user name from users table
$result = mysql_query("SELECT ATTENDER_NO FROM attender where USERNAME = '$username' && PASSWORD = '$password'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
echo "User Found";
} else {
// user name and or password is incorrect
// invalid login
echo "User not Found";
}
?>


this is for the displaying data in the listview



<?php


$response = array();


require_once $_SERVER['DOCUMENT_ROOT'] .'/ihatid/android/Connection/connection.php';
$db = new DB_CONNECT();


$username = $_GET["name"];
$password = $_GET["email"];
// get all products from products table
$result = mysql_query("SELECT student.STUDENT_NO, student.FIRSTNAME,
vehicle.PLATE_NO, CONCAT(attender.FIRSTNAME , attender.MIDDLENAME, attender.LASTNAME) AS NAME,
parent.FIRSTNAME, parent.LATITUDE AS LATITUDE, parent.LONGITUDE AS LONGITUDE
FROM student, vehicle, vehicle_sched, attender, student_has_parent, parent
WHERE student.PLATE_NO = vehicle.PLATE_NO
AND vehicle.PLATE_NO = vehicle_sched.PLATE_NO
AND vehicle_sched.ATTENDER_NO = attender.ATTENDER_NO
AND student.STUDENT_NO = student_has_parent.STUDENT_NO
AND student_has_parent.PARENT_NO = parent.PARENT_NO
AND attender.FIRSTNAME = '$usename'
AND student.ENROLL_STATUS = 'active'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["student"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$student = array();
$student["studentno"]= $row["STUDENT_NO"];
$student["name"] = $row["NAME"];
$student["latitude"] = $row["LATITUDE"];
$student["longitude"] = $row["LONGITUDE"];



// push single product into final response array
array_push($response["student"], $student);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No student/s found";

// echo no users JSON
echo json_encode($response);
}
?>

0 comments:

Post a Comment