First_Explorer
First_Explorer

Reputation: 43

Post data from edittext to php script using httppost

How do I pass user input (Edittext) to a php script on a server? I'm trying to get this working locally first through wamp. I have allowed all connections in the wamp conf file and created an alias to the folder I am using within my www folder. My code is as follows:

public class GetItemsActivity extends FoodSearchActivity {

public void postData(View v) {

    //get food from edit text box
    String food = txtFoodSearch.getText().toString();
    System.out.println(food);                               //see if user input is being picked up



    if(food.length()>0) {

    // Create a new HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("000.000.000.00/SlimandSave/test.php");  //use address of local web server


     try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Food", "food"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpclient.execute(httppost);

        txtFoodSearch.setText(" "); //reset the message text field


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} else {
    //display message if text field is empty
    Toast.makeText(getBaseContext(),"All fields are     required",Toast.LENGTH_SHORT).show();   

}
}
 }

for now I just want to be able to post the data over so my php is just going to output the search text to a text file;

    file_put_contents("myfile.txt", print_r( $_POST, true ));

?>

I have been looking at some questions on here and i'm now not sure whether I should be using asynctask, or if I am missing something obvious. Maybe it's the php? I appreciate any tips/advice.

Edit: i've just discovered that if I leave the edit text field blank the app still crashes when i click search so not sure where to look now

Further edit: I've also just discovered i never added the activity to the manifest for the button click, so the app is no longer hanging and crashing after the button click.

I am getting this from the logs now,

02-13 15:39:16.826: E/EditText(26019): bread
02-13 15:39:16.876: E/AndroidRuntime(26019): FATAL EXCEPTION: main
02-13 15:39:16.876: E/AndroidRuntime(26019): java.lang.RuntimeException: Unable to       instantiate activity ComponentInfo{com.college.slimandsave/com.college.slimandsave.GetItemsActivity}: java.lang.ClassCastException: com.college.slimandsave.GetItemsActivity cannot be cast to android.app.Activity
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2024)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.os.Looper.loop(Looper.java:137)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread.main(ActivityThread.java:4898)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at java.lang.reflect.Method.invokeNative(Native Method)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at java.lang.reflect.Method.invoke(Method.java:511)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at dalvik.system.NativeStart.main(Native Method)
02-13 15:39:16.876: E/AndroidRuntime(26019): Caused by: java.lang.ClassCastException: com.college.slimandsave.GetItemsActivity cannot be cast to android.app.Activity
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.Instrumentation.newActivity(Instrumentation.java:1057)
02-13 15:39:16.876: E/AndroidRuntime(26019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2015)
02-13 15:39:16.876: E/AndroidRuntime(26019):    ... 11 more

FINALLY got this to work. In the code above I had to use txtFoodSearch.getText().toString() rather than just food, and I was just using the ip of my wamp server, I needed to add http:// to the ip address, thanks for any suggestions.

Upvotes: 0

Views: 1425

Answers (1)

meda
meda

Reputation: 45500

whether I should be using asynctask, or if I am missing something obvious. Maybe it's the php?

Of course you should use it, as network operation are not allowed on main Thread.

Maybe it's the php? I appreciate any tips/advice.

Here are my advices:

You would do something along the following lines:

 private class SearchFoodTask extends AsyncTask<Void, Void, Void> {
     protected void doInBackground(Void... params) {
      //here you execute the post request
      // You can call postData() here
     }

     protected void onPostExecute() {
       //onPostExecute is called when background task executed
       //this is the place to update the interface

       txtFoodSearch.setText(" ");
     }
 }
  • Debug

Use logcat, log things to the screen or console, you have to know where there is an issue. Also dont just catch exeption , you have to use them print the stack trace to logcat otherwise it's pointless.

} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
  • Server Side

Keep things simple I like that you are writing to a file. I personaly like to use error_log() even though it might be for another purpose. You can improve the script by adding more checks:

 <?php
 // use file_put_contents, fwrite or error_log whichever you prefer

 //If this gets written to the log file it means
 //Android was able to reach
 error_log("script got called from");

 if(isset($_POST)){

    error_log("Post value is set".var_dump($_POST));

    if(isset($_POST['Food'])){
        error_log("Post food value is set".$_POST['Food']);
    }else{
        error_log("Post food value is not set");
    }

 }else{
    error_log("Post array not set");
 }

?>

If nothing gets logged then most likely the issue is the application.

If you follow these procedure you should never have to wonder Maybe it's the php? you will know exactly where the issue is.

Upvotes: 1

Related Questions