3

I want to send data from Java Android to mysql php server.

This is my code for button click:

public void loginPost(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      String result="";

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
      try {
          List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("UserName", username));
          nameValuePairs.add(new BasicNameValuePair("PassWord", password));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

          HttpResponse response = httpclient.execute(httppost);
          HttpEntity entity = response.getEntity();

          if (entity != null) {
              StringBuilder sb = new StringBuilder();
              String line;
              InputStream instream = entity.getContent();
              BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
              while ((line = bf.readLine()) != null ) {
                  sb.append(line).append("\n");
              }
              result = sb.toString();
              Log.i("Read from server", result);
          }

      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      status.setText(username);

      //Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
      //startActivity(intent);
}

This is my code in login.php:

<?php 
    include("connect.php");

    //define $myusername and $mypassword
    $myusername = $_POST['UserName'];
    $mypassword = $_POST['PassWord'];

    //to protect mysql injection
    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);
    $myusername = mysql_real_escape_string($myusername);
    $mypassword = mysql_real_escape_string($mypassword);

    $mypassword = $mypassword;

    $sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
    echo $sql;
    $result = mysql_query($sql);    


    //mysql_num_row is counting table row
    $count = mysql_num_rows($result);
            echo "<script> alert('".$count."')</script>";

    if($count == 1)
    {
        session_start();
        $row = mysql_fetch_array($result);
        //$_SESSION['login'] = $myusername;
        $_SESSION['id_member'] = $row['id_member'];

            header('Location: login.php');
    }
    else
    {
        header('Location: default.php');
    }
?>

I add this permission in manifest:

<uses-permission android:name="android.permission.INTERNET" />

But the application was stopped after i run it. I don't know where is the error.

7
  • did you try to call session_start() at the first line of your php just to test ? Commented Dec 30, 2014 at 1:38
  • are you doing the networking from a background thread, if you do networking on the UI Thread it will crash? Commented Dec 30, 2014 at 1:44
  • Make sure you're using <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> Commented Dec 30, 2014 at 1:46
  • @scraaappy No, i didn't call it Commented Dec 30, 2014 at 1:50
  • @JRowan I do it in activity class. How to do it in background thread? Commented Dec 30, 2014 at 1:52

2 Answers 2

1

Try doing your networking in an ASyncTask so that your networking isnt done on the UIThread, i think thats why your crashing

something like this

class TheTask extends AsyncTask<Void,Void,Void>
{



      protected void onPreExecute()
      {           super.onPreExecute();

      } 

       protected Void doInBackground(Void ...params)
      {  


       loginPost();//View view); // View view replace
                             // i think even having view as a parameter will crash 
                             // doinbackground method you have to change it i think

      } 

       protected void onPostExecute(Void result)
      {     

                super.onPostExecute(result);

                    // Back to UIThread, i think handle status.setText(username);
                    // from here and take it out of your loginPost() method UI operations will 
                    // crash doInBackground(Void ...params)


      } 
}

then call it in your code like this

new TheTask().execute();

EDIT: well all of your views and whatnot will crash doinbackground method use on PreExecute and OnpostExecute for begining and ending with UIOperations

Sign up to request clarification or add additional context in comments.

4 Comments

I try it, it's not crash. But, i don't know what should be the parameter in php if the login is successful. Because the code above is when user use login in pc/not mobile.
i have no clue about php, sorry
it looks like your on the right track with the Logging though
AsyncTask works however there is just way too much ceremony for my liking. I would use a library like Volley for network activity.
0

You need to use AsyncTask.

        public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
             protected String doInBackground(ArrayList<String>... userdata) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.website.com/script.php");

                String result = null;
                try{
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
                    nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);
                    InputStream is = response.getEntity().getContent();
                    String line = "";
                    StringBuilder total = new StringBuilder();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                    while ((line = rd.readLine()) != null) { 
                        total.append(line); 
                    }
                    result = total.toString();
                }
                catch(NoHttpResponseException e){
                    Log.d("resultLoginError", e.getMessage());
                }
                catch(Exception e){
                    Log.d("resultLoginOther", e.toString());
                }
                return result;
             }
             @Override
            protected void onPreExecute() {
            super.onPreExecute();
            }
             protected void onPostExecute(String result) {
                 Log.d("resultOnLogin", "LOGGED?");
                 }
         }

    public String Login(String user, String pass) throws InterruptedException, ExecutionException{
        ArrayList<String> userdata = new ArrayList<String>();
        userdata.add(user);
        userdata.add(pass);

        return new UserLogin().execute(userdata).get();
    }

This is what I personally use for login.

script.php is a PHP file that handles POST values (Username and password) and sends back confirmation to app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.