Send data from java android to web server using post method

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

This is my code for the 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 to the manifest:

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

      

But the application was stopped after starting. I don't know where the error is.

+3


source to share


2 answers


Try to do your job in ASyncTask so that your network is not done on UIThread, I guess this is why your crash

something like that

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: all your views and what doesn't happen will call the doinbackground method for PreExecute and OnpostExecute to start and stop working with UIOperations

+1


source


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 to login.

script.php is a PHP file that processes POST values ​​(username and password) and sends a confirmation message.

0


source







All Articles