posting data resulting in error - java

I am trying to do a very simple POST from an android application to a php script that will update a database. Unfortunately, this is giving me a debugger error (eclipse) on line 52. Below is the code:
package com.example.testhttppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void updateDiscountTable(View view)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/jsonpost.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("shop", "ZARA"));
nameValuePairs.add(new BasicNameValuePair("discount", "20%"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); //Line 52
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
and the PHP script is:
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "dsdsdsv_android";
// PHP variable to store the password
$db_pass = "test1234";
// PHP variable to store the Database name
$db_name = "dsdsdsv_android";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$shopId = $_POST['id'];
$shopName = $_POST['shop'];
$discount = $_POST['discount'];
mysql_query("insert into discounts(id, shop, discount) values ($shopId, $shopName, $discount)");
// mysql_query("insert into discounts(id, shop, discount)values(121, 'sadsdas','dasdasdsa')");
?>
The interface of the application is nothing but a button. This button is linked with the method above defined updateDiscountTable. Thanks and looking forward to replies.

You are performing networking operations on the main application thread probably. You need to move this to a background thread. You can use Asynctask.
You need to Keep your app responsive.

Related

Making the android app connected in one session

I'm making this android app where you user must login to enter the app, I'm connecting my app to the database via web-services
I created the login page successfully, however, my question is, how can the user move into the second page with the same session ID and how can the system retrieve the user details who logged in in other pages
Thats my login.java code
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.HttpsTransportSE;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Login extends ActionBarActivity {
private static final String NAMESPACE = "***"; //WHAT IS A NAMESPACE
private static final String URL = "***"; //removed HTTPS because I'm making a https call below
private static final String METHOD_NAME = "login";
private static final String SOAP_ACTION = NAMESPACE + "/" + METHOD_NAME; //in wsdl it's nothing
EditText usersusername, userspassword;
Button LB;
#Override
protected void onCreate(Bundle savedInstanceState) { // WHAT DOES PROTECTED VOID MEAN? CAN YOU RENAME ANYTHING
//SUCH AS SAVEDINSTANCESTATE OR IS IT ALWAYS LIKE THAT?
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login); //CAN YOU HAVE TWO ACTIVITIES TO ONE LAYOUT?
usersusername = (EditText)findViewById(R.id.editusername);
userspassword = (EditText)findViewById(R.id.editusername);
LB = (Button) findViewById(R.id.loginbutton);
LB.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
usersusername = (EditText)findViewById(R.id.editusername);
userspassword = (EditText)findViewById(R.id.editusername);
String user_Name = usersusername.getText().toString();
String user_Password = userspassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // Declare the version of the soap request
envelope.setOutputSoapObject(request);
HttpTransportSE aht = new HttpTransportSE(URL);
try {
//URL = www.servicedeskattach.datacom.co.nz/axis/services/USD_R11_WebService?wsdl
aht.call(SOAP_ACTION, envelope); //this is the actual part that calls the web service
String requestDumpString = aht.requestDump;
String responseDumpString = aht.responseDump;
//Get the soapresult from the envelope body
// SoapObject result = (SoapObject)envelope.bodyIn;
SoapPrimitive response =(SoapPrimitive)envelope.getResponse();
String status = response.toString(); // Result string
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
if(status.equals("Success!"))
{
Intent intent = new Intent(Login.this,Dashboard.class);
intent.putExtra("username",usersusername.getText().toString());
startActivity(intent);
}
else
{
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
}
catch (Exception e){
}
}
}
This is a great example of persisting data across activities. To do this, the most common example is to use "Preferences" files. If you don't want the data to persist very long you either control it server-side (expire a cookie or session ID):
How do I get the SharedPreferences from a PreferenceActivity in Android?
Passing the data using intents is not bad, but if a phone call comes in and the app moves to the background, Android may kill and then restart your app causing a loss of data. That may sound "secure" but the situation could also be that the phone simply rings or the user responds to a text message, and if this happens often, your user may be irritated.
A database is typically overkill, unless you already have one along with a USER object, etc.

ClassCastException when accessing SOAP based web service from Android

I'm trying to access the web service defined in WSDL from Android activity. The expected output is json formatted string.
At the first step my aim is to print this string to a text view in Android. So I used following code :
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String NAMESPACE = "XXXXXXXXXXXXXXX";
private final String URL = "XXXXXXXXXXXXXXXXX";
private final String SOAP_ACTION = "XXXXXXXXXXXX";
private final String METHOD_NAME = "XXXXXXXXXXXXXXXXX";
private String webResponse = "";
private TextView textView;
private Thread thread;
private Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
startWebAccess();
}
public void startWebAccess() {
thread = new Thread() {
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
webResponse = response.toString();
Log.d("TAG", webResponse);
}
catch (Exception e) {
e.printStackTrace();
}
handler.post(createUI);
}
};
thread.start();
}
final Runnable createUI = new Runnable() {
public void run() {
Log.d("TAG", webResponse);
textView.setText(webResponse);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
But when I'm trying to run the code I can see following error in log cat (And no output in Text view):
java.lang.ClassCastException: java.util.Vector
Here is the complete log cat out put :
08-06 09:57:11.792: D/dalvikvm(953): GC_FOR_MALLOC freed 771 objects / 322464 bytes in 130ms
08-06 09:57:13.252: D/dalvikvm(953): GC_FOR_MALLOC freed 3182 objects / 473904 bytes in 41ms
08-06 09:57:13.252: D/NativeCrypto(953): Freeing OpenSSL session
08-06 09:57:13.293: W/System.err(953): java.lang.ClassCastException: java.util.Vector
08-06 09:57:13.293: W/System.err(953): at org.sahana.peoplelocator.MainActivity$2.run(MainActivity.java:56)
What can be the error ? please help me I'm stuck here.
Thank you in advance!
Try the below
Replace this
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
By
SoapObject response=(SoapObject) envelope.bodyIn;
I tried your code this is the result i got
ClassCastException is thrown when you try to cast invalid types. For example, let's say you have an ArrayList v. If you do String s=(String)v, it will throw an exception because you can't convert an ArrayList to a String. In this case, the only casting you're doing is SoapPrimitive response = (SoapPrimitive) envelope
.getResponse(); Which means that envelope.getResponse() does not return a SoapPrimitive. It probably returns a java.util.Vector, based on the error message.
I've never used whatever libraries you're using, so I can't give you a definite answer. However, envelope.getResponse() ClassCastException on google gives me a lot of results. Try that, and good luck!

Android VMD MySQL insert and showing dialog

I am trying to do a simple insert from an Android application. I can run my php script from the browser by concatenating ?entry="Sample value from browser", but when I run the application from Android, I get no insert.
Here is where I am calling the insert class that uses JSON and implements AsyncTask:
package us.jtaylorok.android.sqlite.first;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class RemoteInsert extends AsyncTask<Void, String,String >{
protected String TAG;
protected Context context;
protected String input;
protected ProgressDialog progressDialog;
public RemoteInsert(String i,Context c){
this.input = i;
this.context = c;
}
protected void onPreExecute() {
//ProgressDialog progressDialog; // = new ProgressDialog(context);
//progressDialog=ProgressDialog.show(,"Please Wait..","Sending data to database", false);
progressDialog=ProgressDialog.show(context,"Please Wait..","Sending data to database", false);
}
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost("http://localhost/index.php");
//HttpPost httppost = new HttpPost("http://10.253.8.88/patient_data/patient_data.php");
HttpPost httppost = new HttpPost("http://10.100.205.72/patient_data/patient_data.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("entry", "Input from Android"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
} catch(Exception e) {
Log.e(TAG, "Error: "+e.toString());
}
return "";
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();
}
}
And here is my PHP script:
<?php
// mysql_connect("host","username","password");
mysql_connect("localhost","user1","mypassword");
mysql_select_db("test");
$entry_value = $_REQUEST["entry"];
$query = "INSERT INTO patientdata (entry) values (".$entry_value.");";
if( !mysql_query($query) ) {
/*insert failed*/
}
mysql_close();
?>
Again, this works perfectly if I call it from the browser, but it throws an exception before implementing AsyncTask.
I do get the AVD to display the add and remove, but when I do that there is no request in my apache2 access_log or error_log. Any suggestions?
I think you have stored php script on local server. So use this 10.0.2.2 while initializing HttpPost instead of your machine's ip address. Its localhost equivalent in android Virtual device.
That was not the issue for this particular problem. The issue was a magic quotes setting in the php.ini

How can I read MYSQL Database from Android?

I want to read a data from MYSQL database via PHP, JSON from Android.
I've been trying many different examples, but my Android phone wasn't able to read any data.
When I run the application my phone doesn't do anything after loading the application :(
MYSQL db info
Data Base Name : PeopleData
Table Name : people
Table has : id, name, sex, birthyear
PHP source : I tested index.php, and the result was correct.
-index.php
<?php
mysql_connect("127.0.0.1","root","");
mysql_select_db("PeopleData");
$q=mysql_query("SELECT * FROM people WHERE birthyear>1980");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Android java file for fetching database
package com.json;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class JSON extends Activity {
TextView resultView;
HttpClient client;
JSONObject json;
// the year data to send
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
resultView = (TextView) findViewById(R.id.tvjson);
client = new DefaultHttpClient();
new Read().execute("text");
}
public JSONObject RedData() throws ClientProtocolException,IOException,JSONException {
HttpPost httppost = new HttpPost("http://127.0.0.1/series/database/index.php");
HttpResponse r = client.execute(httppost);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray jArray = new JSONArray(data);
JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
return last;
} else {
Toast.makeText(JSON.this, "error", Toast.LENGTH_LONG);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = RedData();
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
// TODO Auto-generated method stub
resultView.setText(data);
}
}
}
xml
<TextView
android:id="#+id/tvjson"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
manifest
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".JSON"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Console
[2012-02-22 16:19:58 - json] Android Launch!
[2012-02-22 16:19:58 - json] adb is running normally.
[2012-02-22 16:19:58 - json] Performing com.json.JSON activity launch
[2012-02-22 16:19:58 - json] Automatic Target Mode: Unable to detect device compatibility. Please select a target device.
[2012-02-22 16:19:59 - json] Uploading json.apk onto device '01499EF80D00D009'
[2012-02-22 16:19:59 - json] Installing json.apk...
[2012-02-22 16:20:01 - json] Success!
[2012-02-22 16:20:01 - json] Starting activity com.json.JSON on device 01499EF80D00D009
[2012-02-22 16:20:02 - json] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.json/.JSON }
device
doing nothing
I don't know what I can do anymore. Please anybody help me.
Thank you.
This should work
package com.Online.Test;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class OnlineTestActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
HttpClient client;
JSONObject json;
String Dat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView) findViewById(R.id.tvjson);
client = new DefaultHttpClient();
try {
json = RedData();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dat = json.toString();
new Read().onPostExecute(Dat);
}
public JSONObject RedData() throws ClientProtocolException, IOException, JSONException {
HttpPost httppost = new HttpPost("//link.php");
HttpResponse r = client.execute(httppost);
// int status = r.getStatusLine().getStatusCode();
//if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray jArray = new JSONArray(data);
JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
return last;
// } else {
// Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG);
// return null;
//}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = RedData();
//Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG);
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
// TODO Auto-generated method stub
resultView.setText(data);
}
}
}
Have a look to the points
The IP address 127.0.0.1 refers to the local device, so for one the
HTTP request is not leaving the device/emulator.
At your Server Side Script (here PHP), set
header('content-type:application/json;charset=utf-8');
At doInBackground's Try block, check whether your ReadData() null or
not.
At JSONArray jArray = new JSONArray(data); check whether jArray null
or not
The following tutorials may help you
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
http://appinventor.blogspot.com/2011/09/android-mysql-connectivity-via-json.html
Cannot parse JSON data from MySQL Database
Make sure your computer is tethered in the same network as your phone.
replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a :
"ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac
then run your app, this should worj....if still you dont get any data, replace your code, and specifically here:
Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray
Make sure your computer is tethered in the same network as your phone.
replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a :
"ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac
then run your app, this should worry you..if still you dont get any data, replace your code, and specifically here:
Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray

How to assign the result of execution of http client to 2 different variables ANDROID

I apologize as this might be a very basic question. when i execute this code, the query in the php file is getting executed twice. This is because once the http client is executed and assigned to http response variable and second time to get the data from the php file .
please see the highlighted code.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class NfcRegisterationActivity extends Activity {
/** Called when the activity is first created. */
TextView t;
Button submit;
EditText name,address, email,phone;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=(TextView)findViewById(R.id.textView2);
name =(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.address);
email=(EditText)findViewById(R.id.email);
phone =(EditText)findViewById(R.id.phone);
submit =(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/customersInsert.php");
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("name", name.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("phone",phone.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("address", address.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String res = httpclient.execute(httppost, responseHandler);
t.setText("Response from PHP :"+ res);
}catch (Exception e) {
// TODO: handle exception
System.out.println("Exception : " + e.getMessage());
}
}
});
}
}
Have you considered the following?:
response=httpclient.execute(httppost);
ResponseHandler responseHandler = new BasicResponseHandler();
String res = responseHandler.handleResponse(response);
t.setText("Response from PHP :"+ res);
No need to call the execute function twice when you can declare your handler and call it's handleResponse function. Not sure why you need two variables if you're just trying to get the response text as a string. If you only need the response as text, you could do:
ResponseHandler responseHandler = new BasicResponseHandler();
String res = httpclient.execute(httppost, responseHandler);
t.setText("Response from PHP :"+ res);
According to the HttpClient documentation, if the the execute function is provided with a response handler it will return the response as the data type returned by the response handler.
Hope this helps.

Categories

Resources