0

I'm trying conect android with mysql using php for include params into tables.

I maked the php code that works. But I not understand why don's work the android's code. I don't receive errors in logcat.

MainActivity:

...
boton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sendMessage("mensaje");
            }
        });
    }


    public void sendMessage(String t){

        ServerRequests serverRequests = new ServerRequests(this);
        serverRequests.fetchUserDataAsyncTask(t);{
            Log.d("", "sendMessage: "+t);
        };
    }
...

ServerRequest

> public class ServerRequests {
> 
>     URL url;
>     HttpURLConnection conn;
>     ProgressDialog progressDialog;
>     String mensaje;
> 
>     public ServerRequests(Context context) {
>         progressDialog = new ProgressDialog(context);
>         progressDialog.setCancelable(false);
>         progressDialog.setTitle("Authenticating...");
>         progressDialog.setMessage("Please wait...");
>     }
> 
>     public void fetchUserDataAsyncTask(String mensaje) {
>         progressDialog.show();
>         new fetchUserDataAsyncTask(mensaje,"hola").execute();
>     }
> 
>     public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, String> {
> 
>         String returnedUser;
> 
> 
>         public fetchUserDataAsyncTask(String mensaje, String returnedUser) {
> 
>         }
> 
>         @Override
>         protected String doInBackground(Void... params) {
> 
>             try {
> 
>                 url = new URL("http://gclimb.com/androidphp/index.php");
> 
>                 conn = (HttpURLConnection) url.openConnection();
>                 String param = "mensaje="+mensaje;
>                 conn.setRequestMethod("POST");
>                 conn.setDoInput(true);
>                 conn.setDoOutput(true);
>                 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
>                 conn.setRequestProperty("charset", "UTF-8");
>                 conn.connect();
> 
>                 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
>                 out.write(param);
> 
>                 //No code to receive response yet, want to get the POST working first.
> 
>             }
>             catch (MalformedURLException e) {
>                 e.printStackTrace();
>             } catch (ProtocolException e) {
>                 e.printStackTrace();
>             } catch (IOException e) {
>                 e.printStackTrace();
>             }
>             catch (Exception e) {
> 
>             } finally {
>                 progressDialog.dismiss();
>             }
> 
>             return returnedUser;
>         }
>     }
> 
> }

EDIT

This is the simple index.php file.

The php file:

<?php

$mensaje = $_POST['username'];
$mensaje2 = $_POST['password'];
$bo = $mensaje;
$servername = "zzzzzzz";
$username = "zzzzzz";
$password = "zzzzz";
$dbname = "zzzzz";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO AndroidPhp (mensaje) VALUES ('$bo')";
$conn->query($sql);





$sql2="SELECT mensaje FROM AndroidPhp";

$result = $conn->query($sql2);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo $row["mensaje"];
    }
} else {
    echo "0 results";
}

 ?>
Cofeina
  • 41
  • 1
  • 9

3 Answers3

0

Use Volley Library. it's simple.

Samples : Volley Library

you can find my answer too.

Community
  • 1
  • 1
Sathish Kumar J
  • 4,280
  • 1
  • 20
  • 48
  • Hi @Sathish. I try copy code of your answer, but in my case, the dialog say me: "JSON Error", "Server Error..! Try after Some Time..!" – Cofeina May 13 '16 at 11:53
  • kindly modify as per your need. check your url is working or not – Sathish Kumar J May 13 '16 at 12:13
  • Ok, I receive the same dialog, but in mysql are created the line. The code execute php file, but don't pass the params. I don't get nothing with $_POST or with $_GET. see my Edit post please – Cofeina May 13 '16 at 12:54
  • ok, I found my problem but no the solution: http://stackoverflow.com/questions/37212109/error-404-when-receive-post – Cofeina May 13 '16 at 14:31
0

WsHttpPost.java

public class WSHttpPost extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
Context context;
HttpURLConnection httpConnection;
ContentValues values;
public WSHttpPost(Context context, ContentValues values) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.values = values;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    pDialog = new ProgressDialog(context);
    pDialog.setTitle("Connecting...");
    pDialog.setMessage("Please Wait...");
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    String result = "";
    try {
        URL url = new URL(params[0]);
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Accept", "application/json");
        //httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConnection.setReadTimeout(10000);
        httpConnection.setConnectTimeout(15000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(String.valueOf(values));
        writer.flush();
        writer.close();
        os.close();

        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream iStream = httpConnection.getInputStream();
            InputStreamReader isReader = new InputStreamReader(iStream);
            BufferedReader br = new BufferedReader(isReader);
            String line;
            while ((line = br.readLine()) != null) {
                result += line;
            }
        }
    } catch (java.net.SocketTimeoutException e) {
        Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Log.e("Error : ", e.toString());
    }
    return result;
}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    pDialog.dismiss();
    try {
        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
      }
   }
}

Calling

boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues cv = new ContentValues();
            cv.put("mensaje",mensaje);
            WsHttpPost httpPost = new WsHttpPost(MainActivity.this,cv);
            httpPost.execute("http://gclimb.com/androidphp/index.php");
          }
       });
   }

And Dont forget to add permission in Manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
Rushvi
  • 113
  • 1
  • 7
  • I try with your code. when click to button only have this message in logcat: sendUserActionEvent() mView == null, and a empty toast in screen. – Cofeina May 13 '16 at 11:34
  • Do you check your response in rest control ? – Rushvi May 13 '16 at 12:13
  • i checked there & i get error over there of html code response – Rushvi May 13 '16 at 12:14
  • & by the way sendUserActionEvent() mView == null is not any kind of problem there.You can refer http://stackoverflow.com/questions/18028666/senduseractionevent-is-null for your confirmation.... I used this code always and it works great......... First of all you have to check your response in any rest client... Like PostMan.. – Rushvi May 13 '16 at 12:16
  • The problem is with my... server? other? see this post http://stackoverflow.com/questions/37212109/error-404-when-receive-post – Cofeina May 13 '16 at 14:32
0

The problem I can see is you are not holding response returned from server. You are returning returnedUser but have you checked what this variable contains?

you can see below method or you can use any library to communicate to server.

You can user RetroFit or Volley for this.

See these examples:

http://www.truiton.com/2015/04/android-retrofit-tutorial/

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

public String executePost(String targetURL, String urlParameters) {
    URL url;
    HttpURLConnection connection = null;
    StringBuffer response = new StringBuffer();
    try {
        // Create connection

        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(urlParameters.getBytes().length));

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);


        // Send request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(urlParameters);

        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        //Log.v("JSON ", " " + response.toString());
        return response.toString();

    } catch (SocketTimeoutException ex) {
        ex.printStackTrace();

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        //  Log.v("JSON ", " " + response.toString());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        //  Log.v("JSON ", " " + response.toString());
    } catch (IOException ex) {

        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        e.printStackTrace();
        //   Log.v("JSON ", " " + response.toString());
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}
Ashish Tiwari
  • 2,168
  • 4
  • 30
  • 54