1

When I directly go to the link of PHP by browser, it creates an empty record in the database. However, when I send data using app, it fails.

Java:

protected String doInBackground(String... params) {
    String reg_url = "http://www.minigameserver.square7.ch/register.php";
    String user_name = params[0];
    String user_ac = params[1];
    String user_pw = params[2];
    try {
        URL url = new URL(reg_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");

        httpURLConnection.setDoOutput(true);
        OutputStream OS = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
        String data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"+
                URLEncoder.encode("user_ac","UTF-8")+"="+URLEncoder.encode(user_ac,"UTF-8")+"&"+
                URLEncoder.encode("user_pw","UTF-8")+"="+URLEncoder.encode(user_pw,"UTF-8");
        bufferedWriter.write(data);
        bufferedWriter.flush();
        bufferedWriter.close();
        OS.close();

        httpURLConnection.disconnect();

        return "done!";
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "fail!";
}

When I run the app, the massage "done!" is shown.

So, there are no Exception happening. But, why there are no new record?


I saw someone have tired to register with username of teset. Is he mind to tell who did so that I can trace the post.


When I try the code provided by Arshak. The following error comes out. E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7d9eaad530

register.php:

<?php
require "db_connect.php";

$user_name = $_POST["user_name"];
$user_ac = $_POST["user_ac"];
$user_pw = $_POST["user_pw"];
$user_pw_enc = md5($user_pw);

$sql = "INSERT INTO user(user_name, user_ac, user_pw) VALUES ('$user_name', '$user_ac', '$user_pw_enc')";

$sql2 = "SELECT * FROM user WHERE user_name = '$user_name'";
$result2 = $conn->query($sql2);

$sql3 = "SELECT * FROM user WHERE user_ac = '$user_ac'";
$result3 = $conn->query($sql3);

if($result2->num_rows == 0 && $result3->num_rows == 0){
if ($conn->query($sql) === TRUE)
        echo "Your account is created successfully!\nYou can login now!";
else
    echo "Error: " . $sql . "<br>" . $conn->error;
}
else {
if($result2->num_rows > 0)  
    echo "The user name is used!<br>";
if($result3->num_rows > 0)
    echo "The user account is used!<br>";
}

?>
9
  • you might be doing some mistakes on your client side try to check error_log on server side Commented Jul 28, 2016 at 11:20
  • have you logged params values, or it has null! Commented Jul 28, 2016 at 11:20
  • What is the response string that you get? Please always provide complete information. Commented Jul 28, 2016 at 14:06
  • @U.Swap, you mean backgroundTask.execute(user_name_s,user_ac_s,user_pw_s);? Commented Jul 28, 2016 at 14:50
  • @KeroroChan please use @ before username if you want to notify the user about the comment. Commented Jul 28, 2016 at 14:51

3 Answers 3

1

I have updated your code, see if data gets inserted:

protected String doInBackground(String... params) {
String reg_url = "http://www.minigameserver.square7.ch/register.php";
String user_name = params[0];
String user_ac = params[1];
String user_pw = params[2];
try {
        URL url = new URL(reg_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.connect();
        DataOutputStream OS = new DataOutputStream(httpURLConnection.getOutputStream());
        String data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"+
                URLEncoder.encode("user_ac","UTF-8")+"="+URLEncoder.encode(user_ac,"UTF-8")+"&"+
                URLEncoder.encode("user_pw","UTF-8")+"="+ URLEncoder.encode(user_pw,"UTF-8");
        OS .writeBytes(data);
        OS .flush();
        OS.close();

        int responseCode=httpURLConnection.getResponseCode();
        String messageFromServer;
        if (responseCode==200) {
            messageFromServer=fromInputStream(httpURLConnection.getInputStream());
            Log.v("RegistrationMessage ",messageFromServer);
            httpURLConnection.disconnect();
            return messageFromServer;
        }

        httpURLConnection.disconnect();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "fail!";
}

//Add this method inside your AsyncTask
public String fromInputStream(InputStream stream) throws IOException {
        InputStreamReader streamReader = new
                InputStreamReader(stream);
        BufferedReader bufferedReader = new BufferedReader(streamReader);
        StringBuilder builder = new StringBuilder();
        String tempString = "";
        while ((tempString = bufferedReader.readLine()) != null) {
            builder.append(tempString);
        }
        return builder.toString();
    }
Sign up to request clarification or add additional context in comments.

27 Comments

You input the name of teset to test it?
@KeroroChan I think this should be the correct answer as you aren't calling httpURLConnection.connect() anywhere. It means that the server is not even called!!!
@KeroroChan please see this question - stackoverflow.com/questions/33719149/… I think you should switch to non-Marshmallow device and test again. But calling httpURLConnection.connect() is a must, otherwise you're only trying to fool yourself.
@KeroroChan I forgot to add fromInputStream() method in the above code. I have updated it, check again. Now it will also display message shown in your php file, such as Your account is created successfully!\nYou can login now! , etc. I guess the data got send because, it might be some build issue that you were facing earlier. I'm happy my code helped you, now you can upvote & mark my answer as correct answer.
@KeroroChan Correct & For now you are receiving less amount of data, so it is fine to use string for now. But when you are receiving a lot of data then i'd recommend using StringBuilder instead of String.
|
0
@Override
protected String doInBackground(String... params) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.minigameserver.square7.ch/register.php");

    try {
       //add data
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
       nameValuePairs.add(new BasicNameValuePair("user_name", params[0]));
       nameValuePairs.add(new BasicNameValuePair("user_ac", params[1]));
       nameValuePairs.add(new BasicNameValuePair("user_pw", params[2]));
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
       //execute http post
       HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
}

You can use Volley Android Networking Library to post your data. Official document is https://developer.android.com/training/volley/simple.html.

Comments

0

I tried to test the URL and yes, it was working. Since there are already posts that show some fixes on your codes, I'm just gonna give you a tip.

First is, since you're not sure of what could be the possible exception you'll get. Try to make it general. remove one catch() statement and instead, use:

catch(Exception e){
    e.printStackTrace();
}

In that way, all exceptions will be caught and you'll easily find what's causing issues on your code.

Next is, since you are communicating with a server, so it's gonna be a request-respond procedure. Actually, you're doing the right thing since after sending some requests, I'm able to receive a respond. But to make it efficient, your server should also respond something like a boolean indicator. Let's say it will respond 1 if it has successfully registered and 0 if not. Then your mobile application will handle the result.

Also, most likely you won't be able to get that fail message since it's outside the try-catch.

2 Comments

I have the message for success and failure of registration. And, when I use inputstream, error comes out.
The error E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f55ab21fff0 comes out.

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.