1

UPDATE 3

Everything is working now. I used this and this, instead of what i was using for POST.

UPDATE 2

I've just noticed that if I place my updates on descending order, it seems better organized.

I edited my code in my OP (down below) added a few comments and replaced the inputstream reader with ReadHttpResponse(String url) from here. This made me separate my PHP script into update.php and get.php instead of updateandget.php.

It turns out that the get.php is working fine, in the limited sense that it is just querying data, (not posting any values). The update.php or the Java code handling the connection to that url is messing up somehow.

At least I've identified that I'm not Posting correctly. I also updated OP to show update.php.

OP

This is my code running the doInBackground() of an AsyncTask

 try{
         //HttpURLConnection<-url.openConnection()
    URL url = new URL(address);
    HttpURLConnection conn =(HttpURLConnection) url.openConnection(); //remember to close
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(false);
    // Write data to Server
        //exctract parameters
    String username = (String)arg0[0];
    String lastLong = (String)arg0[1];
    String lastLat = (String)arg0[2];
        //encode parameters
    String data  = URLEncoder.encode("username", "UTF-8")+ "=" + URLEncoder.encode(username, "UTF-8");
    data += "&" + URLEncoder.encode("lastLong", "UTF-8")+ "=" + URLEncoder.encode(lastLong, "UTF-8");
    data += "&" + URLEncoder.encode("lastLat", "UTF-8")+ "=" + URLEncoder.encode(lastLat, "UTF-8");
        //Build outputstream handler (socket?)
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 
        //write,flush,close
    wr.writeBytes( data ); 
    wr.flush(); 
    wr.close();
        // Read Server Response
    //BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    //StringBuilder sb = new StringBuilder();
    //String line = null;
    //String returnmessage="";
    //while((line = reader.readLine()) != null)
    //{
    //  returnmessage="There is something at least";
    //   sb.append(line);
    //   break;
    //}
    //reader.close();
    conn.disconnect();

    //return returnmessage;
    return ReadHttpResponse("http://www.pixeldonut.com/testing/tutorial/get.php");
 }catch(Exception e){
    return new String("Exception: " + e.getMessage());
 }

No problems reading, (or with ReadHttpResponse). Problems with everything else apparently.

update.php:

    <?php //lastknownlocation updateandget
//open con
$con=mysqli_connect("details");
if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
   die();
}
//=========================================================statistics snippet
            if(array_key_exists('REMOTE_ADDR', $_SERVER)){
                $ip=$_SERVER['REMOTE_ADDR'];
                $address=$_SERVER['SERVER_ADDR'];
                if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
                    $ip2=$_SERVER['HTTP_X_FORWARDED_FOR'];
                }else{
                    $ip2="_";
                }
                $query="INSERT INTO statistics (ip,ip2,address) VALUES (";
                $query.="'$ip','$ip2','$address'";
                $query.=")";//echo $query;
                $db_return=mysql_query($query);
                if(!$db_return){
                    //echo "Your entry was unsuccessfully logged.";
                }else{
                    //echo "Your entry was successfully logged.";
                }
            }
            //==============================================================================
    //update-insert
$username = $_POST['username'];
$param1= $_POST['param1'];
$param2= $_POST['param2'];
$query = "UPDATE users SET";
$query .=" param1='$param1'";
$query .=",param2='$param2' ";
$query .="WHERE username='$username'";//echo $query;
$result = mysqli_query($con,$query);
if(!result){
    //couldnt find user, aborting
    die();
}


//close con
mysqli_close($con);
?>

Thank you for your continued support and enthusiasm, Ebichuhamster.

Community
  • 1
  • 1
ebichuhamster
  • 228
  • 1
  • 12
  • 1
    This should be of some help. [sending post request in java](http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily) – MjZac Feb 05 '14 at 06:25
  • @MjZac I appreciate the link. I am using OutputStreamWriter and the answer on that question suggested DataOutputStream. I'm trying that now. – ebichuhamster Feb 05 '14 at 06:32
  • @MjZac That didn't work :( – ebichuhamster Feb 05 '14 at 06:40
  • @MjZac I also tried writing the parameter string myself as they do in the suggestion, instead of using URLencoder, to no avail. – ebichuhamster Feb 05 '14 at 06:51
  • Would it not be easier to use ion or retrofit? – t0mm13b Feb 05 '14 at 12:00
  • @t0mm13b I have no concept of ease when it comes to android. I've been on this project for less than a month and I've hit so many roadblocks it's not even funny. I will read up on those libraries to see if I can understand what you mean. – ebichuhamster Feb 05 '14 at 17:01
  • Point am making is why are you going down the route in crafting a `HttpURLConnection` and re-inventing the wheel. Despite you saying that you *hit so many roadblocks its not even funny* There's plenty of resources, with a bit of research and google-fu.. just saying ;) – t0mm13b Feb 05 '14 at 17:08
  • @t0mm13b my roadblocks have been of a more personal nature, combined with my unfamiliarity of the android environment. For example, my phone seems to be damaged and i cannot debug on it. Right now I have no wifi, so my 4g-less nexus is still very useful (because it still outputs logcat), but if it had internet connection I could do all my debugging there. I understand how not reinventing the wheel is important, but I also want to learn how to move without the wheel, so I get to a point where I need the wheel. :) Does this make sense? – ebichuhamster Feb 05 '14 at 17:32
  • 1
    So you're new to Android dev, of course, I recommend you read up Commonsware by taking out a subscription to get you up to speed ;) – t0mm13b Feb 05 '14 at 17:39

2 Answers2

1

I see some points which could be the reason for the problem. Or at least they are worth to look at to avoid problems in the future:

Java

The implementation looks quite good. I'd add some code the check the HTTP status code of your request and add more code to be sure connections and streams are closed even if errors happen. I recommend using an abstraction library instead of HttpURLConnection. If you chose DavidWebb, your code would look like this and you can be sure that all streams are closed, the right headers are set and a few other things:

String username = "scott";
String lat = "47.49706";
String lng = "12.63244";

Webb webb = Webb.create();

Response<String> response = webb
        .post("http://my-server:8888/updateandget.php")
        .param("username", username)
        .param("param1", lng)
        .param("param2", lat)
        .readTimeout(10000)
        .connectTimeout(15000)
        .asString();

if (response.isSuccess()) {
    String json = response.getBody();
    // go on
} else {
    // handle error
    if (response.getStatusCode() >= 500) {
        // a server error, in case of "503 Service Unavailable" retry later?
    }
}

PHP

In your logging snippet, you output echo "Your entry was unsuccessfully logged.";. This produces incorrect JSON. As you only get <br/> this is not your problem now.

The update statement seems correct, though it could be a security issue since it's open for SQL injection.

The statement to get the result has probably 2 issues:

"SELECT username,param1,param2FROM table WHERE username!='$username'";
  • Between param2 and FROM must be a space
  • You will probably not want to return all the rows not owned by the user, do you? (Once again danger of SQL injection)

Find a Solution

I suggest you first try to check whether your PHP script is reached by changing it to something that does absolutely nothing but return some static JSON content (you know the structure). If that works, you can add more and more statements and see if it works.

hgoebl
  • 12,637
  • 9
  • 49
  • 72
0

Also have same problem and I tried using:

DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

and it worked. previously I used just OutputStream and it give me empty $_POST when sending request form my android app to my mysql server (local).

Clay
  • 4,700
  • 3
  • 33
  • 49
Vonragz
  • 1
  • 1