简体   繁体   中英

Comparing values from textviews and JSONArray

Sorry for the (seemingly) lazy question, but i've been looking for a solution with no luck (in other words, I haven't found a solution that i understand).

I want to have users log in to an app by way of entering a username and password, this username and password has to match a username and password from the jsonarray which i've retrieved from a phpmyadmin database. The username and password have to be in the same row.

Here's the function I use to retrieve my jsonarray:

private void getData(){

JSONArray json;
try{
    user = editText1.getText().toString();
    password = editText2.getText().toString();

    json = readJsonFromUrl("http://localhost/indextest.php?function=getdata");

       Thread.sleep(1000);
  } catch (Exception e) {
    Log.e("BACKGROUND_PROC", e.getMessage());
  }

}

I just need to know how to search the jsonarray for the values that i retrieve from my textviews.

If possible I would like to retrieve a value that I can easily assign to an if statement like such:

public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button1:

                if  ( editText1 != null && editText1.length() != 0 && editText2 != null && editText2.length() != 0){    
                    getData();
                    m_ProgressDialog = ProgressDialog.show(HomeScreen.this,    
                              "Please wait...", "Checking Details...", true);
                        m_ProgressDialog.setCancelable(true);

                      if ( /*username and password match*/){
                      Intent i = new Intent(this, Afterlog.class);
                      startActivity(i);     
                      }

                    else{
                        Toast.makeText(HomeScreen.this, "The username and password did not match any in our database...", Toast.LENGTH_SHORT).show();   
                    }
                }
                else {
                    Toast.makeText(HomeScreen.this, "Please enter a user name AND a password...", Toast.LENGTH_SHORT).show();
                }
                break;

}
}

Two things:

  • Take a look at GSON . It is a Google Library for encoding objects into json and then decoding json into objects. In essence, you can define a class that has the same structure as the data you are receiving in JSON and then use GSON to read the JSON and create an object of your class with the appropriate fields filled in. Your code would look something like this:

First, define your class structure for the data you are sending as JSON:

public class LoginData {
    public String Username; //These identifiers must match the JSON structure
    public String HashedPassword;

    public LoginData(String username, String hashedPass) {
        Username = username;
        HashedPassword = hashedPass;
    }
}

Then, once you receive the JSON, you can parse the information like this:

LoginData login = mGson.fromJson(json, LoginData.class);
  • It sounds like you are storing usernames and passwords in raw text and retrieving them from your database in raw text. This is a VERY BAD IDEA! Passwords should always be stored in an encrypted form (ie hashed). When the user provides their password to log in, you encrypt the provided password and compare the encrypted versions (ie compare the hash of the provided password to the stored hash from your database). This prevents people who might be listening to your network traffic from being able to capture your passwords. Instead, if they were watching your network traffic they would see the hashed password, and without knowing exactly the algorithm used to hash the passwords, they would not be able to calculate the original password.

Your code needs to run in an asyncTask because it is performing a network request:

Here is an example:

class LoginTask extends AsyncTask<String, String, JSONObject>
{
    protected JSONObject doInBackground(String... urls)
    {

        return readJsonFromUrl(urls[0]);
    }

    protected void onPostExecute(JSONObject result)
    {

      try {
        //this assumes that the response looks like this:
        //{"username" : "john" , "password" : "Bsd6578" }
         String responseUsername = result.getString("username");   
         String responsePassword = result.getString("password"); 

         if (user.equals(responseUsername) && password.equals(responsePassword)){
            Intent i = new Intent(this, Afterlog.class);
            startActivity(i);     
         }else{
            Log.d("mylog", "username and password dont match");
         }

       } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
    }
}

Your button is should be responsible for running that task:

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button1:
          user = editText1.getText().toString();
          password = editText2.getText().toString();
          new LoginTask().execute()
        break;
    }
}

Found a very simple and to the point tutorial here:

http://www.coderzheaven.com/2012/04/22/create-simple-login-form-php-android-connect-php-android/

Thanks for all the help @meda :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM