根据用户的会话在列表视图中显示数据

时间:2014-07-10 04:29:08

标签: android session android-intent android-fragments

是否有一种方法可以将MySQL服务器数据库中的数据显示在android的列表视图中,具体取决于登录应用程序的用户的会话。数据将根据用户的user_id进行排序。

这可能是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();               
        }
    });
}

}

这可能是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

        }
}
}

这是我的会议。

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);
            }
        });

    }

}
}

用户登录后。我想要的是在main.java上显示用户信息。顺便说一句,我在我的Android应用程序中使用抽屉导航。然后,当我单击listActivity按钮时,这将指向xml,它将从数据库中显示listview中的数据。

我的问题是我不知道如何显示用户信息并根据用户的会话显示数据。请求请求...提前感谢...我只是一个初学者...

我的php文件...这是用于获取用户数据     

$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);
}
?>

这是用于登录的php

<?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";
}
?>

这是用于在列表视图中显示数据

<?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);
}
?>

1 个答案:

答案 0 :(得分:0)

实施此步骤有几个步骤。我不打算详细描述如何实施这些步骤 - 我只想向您概述您应该/需要做什么。

  1. 我看到你正在使用JSON,这很棒。但是,您应该创建一个名为Student的类,并将相同的字段添加到您的JSON中。然后,您应该使用JSON数据填充每个学生对象。

    这样做会让您的生活变得更轻松 - 您所做的任何拼写错误都会导致编译错误,并且您的代码将更易于维护。

  2. 获得Student个对象的ArrayList后,您需要创建ArrayAdapter。 Android为ListViews广泛使用ArrayAdapter类;在继续之前,你一定要很好地理解它们的工作原理。

    我强烈建议您按照本教程进行操作:http://www.vogella.com/tutorials/AndroidListView/article.html

  3. 完成ArrayAdapter设置后,可以非常轻松地更新ListView的数据。只需致电notifyDataSetChanged()