简体   繁体   中英

correct a java code in eclipse android development

Fellow Coders, i have wrote a java code in eclipse that can login to an account using localhost phpmyadmin database the checklogin is working, if the account is registered it let me login but if i typed the account wrong android emulator tell me that the application has crashed i want someone to help me .. all i want to do if the information typed are wrong a message will be shown telling that the username or password are wrong hope that someone can help me

Here's my code :

public class user extends Activity  implements OnClickListener {
EditText etUser , etPass;
Button bLogin;

String username, password ;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> nameValuePairs ;

HttpResponse response;
HttpEntity entity;

public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);

    initialise();
    }

    private void initialise() {
      // TODO Auto-generated method stub
      etUser = (EditText) findViewById(R.id.editText2);
      etPass = (EditText) findViewById(R.id.editText1);
      bLogin = (Button) findViewById(R.id.button1);
      bLogin.setOnClickListener(this);
    }

    public void onregister(final View button) {
    final Intent intent = new Intent();
    intent.setClass(this, register.class);
    startActivity(intent);

    }

    public void onClick(final View v) {

    httpclient = new DefaultHttpClient();
    httppost = new HttpPost("http://10.0.2.2/android/database.php");

    username = etUser.getText().toString();
    password = etPass.getText().toString();

    try {
      nameValuePairs = new ArrayList<NameValuePair>();

      nameValuePairs.add(new BasicNameValuePair("username", username));
      nameValuePairs.add(new BasicNameValuePair("password", password));

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      final Thread a = new Thread(new Runnable() {

        public void run() {
          try {
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

          runOnUiThread(new Runnable() {

            @Override
            public void run() {
              // TODO Auto-generated method stub
              if (response.getStatusLine().getStatusCode() == 200) {

                entity = response.getEntity();

                if (entity != null) {

                  InputStream instream = null;
                try {
                    instream = entity.getContent();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                  JSONObject jsonResponse = null;
                try {
                    jsonResponse = new JSONObject(convertStreamToString(instream));
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                  String retUser = null;
                try {
                    retUser = jsonResponse.getString("username");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  String retPass = null;
                try {
                    retPass = jsonResponse.getString("password");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                  if (username.equals(retUser) && password.equals(retPass)) {

                    SharedPreferences sp = getSharedPreferences("logindetails", 0);

                    SharedPreferences.Editor spedit = sp.edit();

                    spedit.putString("username", username);
                    spedit.putString("password", password);

                    spedit.commit();

                    Toast.makeText(getBaseContext(), "Succes!", Toast.LENGTH_SHORT).show();

                  } else {

                    Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();

                  }
                }
              }
            }
          });
        }
      });
      a.start();
    } catch (Exception e) {

        Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();

    }

    }

    private static String convertStreamToString(final InputStream is) {

    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (final IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
    }}

Most likely if you provide incorrect USERNAME and PASSWORD you will get Exception at line

response = httpclient.execute(httppost);

something like "401 unauthorized access". So you can catch it and show Toast. And also create some variable if you could wrap next work with HttpResponse into condition in the case that you provide incorrect input data.

Pseudocode:

response = httpclient.execute(httppost); // here you catch error
// and in catch block initialise your variable incorrect = true
if (incorrect) {
   // show Toast
}
else (
  // do your work with JSON
)

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