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>";
}

?>
Keroro Chan
  • 99
  • 10
  • you might be doing some mistakes on your client side try to check error_log on server side – eLemEnt Jul 28 '16 at 11:20
  • have you logged params values, or it has null! – U.Swap Jul 28 '16 at 11:20
  • What is the response string that you get? Please always provide complete information. – Sufian Jul 28 '16 at 14:06
  • @U.Swap, you mean backgroundTask.execute(user_name_s,user_ac_s,user_pw_s);? – Keroro Chan Jul 28 '16 at 14:50
  • @KeroroChan please use `@` before username if you want to notify the user about the comment. – Sufian Jul 28 '16 at 14:51
  • No one can tell you without having access to your server. What you should do is check your response string. – Sufian Jul 28 '16 at 14:52
  • @Sufian you mean I should do inputstream to see the output. I do not do it causes the error(getSlotFromBufferLocked: unknown buffer: 0x7f7d9eaad530) comes out – Keroro Chan Jul 28 '16 at 14:54
  • @KeroroChan something like `String contentAsString = readIt(is, len);` as seen here https://developer.android.com/training/basics/network-ops/connecting.html – Sufian Jul 28 '16 at 14:56
  • @Sufian I try something similar. The error getSlotFromBufferLocked: unknown buffer: 0x7f7d9eaad530 comes out. – Keroro Chan Jul 28 '16 at 15:11

3 Answers3

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();
    }
Arshak
  • 2,799
  • 1
  • 23
  • 30
  • You input the name of teset to test it? – Keroro Chan Jul 28 '16 at 14:39
  • @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!!! – Sufian Jul 28 '16 at 15:24
  • @Sufian Even I call httpURLConnection.connect(), the error still comes out. – Keroro Chan Jul 28 '16 at 15:27
  • @Sufian E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7d9eaad530 – Keroro Chan Jul 28 '16 at 15:30
  • 1
    @KeroroChan please see this question - http://stackoverflow.com/questions/33719149/android-studio-getslotfrombufferlocked-unknown-buffer-error-in-mashmallow 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. – Sufian Jul 28 '16 at 15:34
  • @Sufian I am trying Lollipop. – Keroro Chan Jul 28 '16 at 15:38
  • @KeroroChan I had tested the above code on Marshmallow, Lollipop, Kitkat, & Jelly Bean devices. It's working fine in those devices. It seems that there might be errors in your register.php file. – Arshak Jul 28 '16 at 15:46
  • @Arshak Which device you used? Is it the Nexus 5 having problems? – Keroro Chan Jul 28 '16 at 15:50
  • @KeroroChan I had tested on Xperia M4, Nexus 4, Nexus 5, Samsung s5. – Arshak Jul 28 '16 at 15:55
  • @KeroroChan Check this [link](http://stackoverflow.com/questions/32561479/android-studio-getslotfrombufferlocked-unknown-buffer-error) for solution to E/Surface error : – Arshak Jul 28 '16 at 15:57
  • @Arshak I saw your record. – Keroro Chan Jul 28 '16 at 15:57
  • @KeroroChan I tested it again on Postman, Just to make sure whether your php is working or not. – Arshak Jul 28 '16 at 16:01
  • @Arshak I've already checked. I've used Nexus 5(Lollipop) and it doesn't work. – Keroro Chan Jul 28 '16 at 16:02
  • @KeroroChan Could you post your register.php file, so as to check where it is going wrong? – Arshak Jul 28 '16 at 16:04
  • @Arshak it means that the php has no problems – Keroro Chan Jul 28 '16 at 16:05
  • @KeroroChan Does your php file take input in the form of JSON? – Arshak Jul 28 '16 at 16:07
  • @Arshak I've posted the register.php . – Keroro Chan Jul 28 '16 at 16:09
  • @KeroroChan I have updated the above code, I have added `Log` to see the response from server (`Check Logcat to see response`). It is working fine. The error that you are receiving is pertaining to something else. – Arshak Jul 28 '16 at 16:36
  • @Arshak The "fromInputStream" in messageFromServer=fromInputStream(httpURLConnection.getInputStream()); are underlined with red line. – Keroro Chan Jul 29 '16 at 00:54
  • @Arshak I modify your code as int responseCode=httpURLConnection.getResponseCode(); if (responseCode==200) { return "send!"; } And, the data is sent. How come? – Keroro Chan Jul 29 '16 at 01:21
  • 1
    @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. – Arshak Jul 29 '16 at 04:30
  • @Arshak I think the data is not sent completely when the httpURLConnection.disconnect(); is call, isn't it? – Keroro Chan Jul 29 '16 at 05:13
  • @KeroroChan Data is sent completely when these methods are called: `OS .writeBytes(data); OS .flush(); OS.close();` So u needn't worry. `httpURLConnection.disconnect();` Releases this connection so that its resources may be either reused or closed. – Arshak Jul 29 '16 at 05:18
  • @Arshak But, I add getSlotFromBufferLocked: unknown buffer: 0x7f7d9eaad530 without getting the responsecode. It is very strange. Btw, why do you use StringBuilder? Why don't you use simple string to store like string_got = string_got + string_temp; ? – Keroro Chan Jul 29 '16 at 05:23
  • @KeroroChan You could use those as well. But I prefer StringBuilder for server response. Read [this](http://stackoverflow.com/a/3069442/5744335) for better understanding. – Arshak Jul 29 '16 at 05:29
  • @Arshak StringBuilder is better when there are a lot of substrings. – Keroro Chan Jul 29 '16 at 07:02
  • 1
    @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. – Arshak Jul 29 '16 at 09:03
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.

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.

Sufian
  • 5,997
  • 14
  • 60
  • 111
fmpsagara
  • 385
  • 3
  • 15