How to post data from an android application to a wamp server? - android

I am trying to POST data using an http request method from an Android application to a Wamp server.
When I run the application a success message is shown on the Android app, but there is no data inserted in the table of the Wamp server. There is no error shown on logcat. What am I doing wrong?
public class MainActivity extends Activity {
private EditText editTextName;
private EditText editTextAdd;#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
}
public void insert(View view) {
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://ip address of my system/Employee3/create_product.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);}
}

For the Http debugging, I suggest you firstly use some tools to test the interface, such as curl or postMan. Make sure the post/get method work correct in these tools, then test the interface in Android

Related

Submit The Form Via POST Method

While sending the message I got application error and the app stops. I wanted to submit the form using POST method. Please help me to correct the code as i am new to android.
I have taken code reference from http://www.onlymobilepro.com/2013/03/16/submitting-android-form-data-via-post-method/
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
You are doing network operation on Main Thread , it needs to be done in seperate Thread .
Do something like this:
To know how to use AsyncTask and set its parameters, see this :
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v) {
//get message from message box
String msg = msgTextField.getText().toString();
if (!msg.isEmpty()) {
new PostData().execute(msg);
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(), "All fields are required", Toast.LENGTH_SHORT).show();
}
}
public class PostData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", params[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");//The response you get from your script
return op;
} catch (IOException e) {
e.printStackTrace();
}
//reset the message text field
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
msgTextField.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}

asynctask sqlite doesnt update

I am making a register screen for my project. After register data is sent to web database I want the app also update local sqlite database so that the next time user opens the app, he/she doesn't need to do the same operations if the register is successfull. My app is updating the web database with no problem but when I try to do sqlite update with a second asynctask it doesn't update sqlite, what am I missing? :(
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText vmail=(EditText) findViewById(R.id.editText1);
final EditText vpassword=(EditText) findViewById(R.id.editText2);
final EditText vnickname=(EditText) findViewById(R.id.editText3);
Button button2=(Button) findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mail=vmail.getText().toString();
password=vpassword.getText().toString();
mynickname=vnickname.getText().toString();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mail",mail));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("mynickname",mynickname));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("wwwmysite.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
reverseString = response;
} catch (ClientProtocolException e) {
Log.e("log_tag", "Error converting result " + e.toString());
} catch (IOException e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
if (reverseString.contains("success")){
new AsyncTaskClass2().execute();
}else{
Toast.makeText(getApplicationContext(), reverseString, Toast.LENGTH_LONG).show();
}
}
}
class AsyncTaskClass2 extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
startActivity(new Intent(registergame.this, (mygamescreen.class)));
}
}
private void KayitEkle(String nick, String mail, String password){
SQLiteDatabase db = users.getWritableDatabase();
ContentValues veriler = new ContentValues();
veriler.put("nick", nick);
veriler.put("mail",mail);
veriler.put("password",password);
db.insertOrThrow("ogrenciisim", null, veriler);
}
}
Put a debugger to see if it is actually calling AsyncTaskClass2 doInBackground() method. If it does, then check the value returned by method insertOrThrow(). If return value is -1 then you need to check for that. This link will give you some insight
You declared your nameValuePairs-variable only in your doInBackground-Method of your 1st AsyncTask:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
You could simply solve it, if you use your class-attribute nameValuePairs:
nameValuePairs = new ArrayList<NameValuePair>();
But as a general aspect, I do not see any cause why you should use a 2nd AsyncTask. Why don't you call the method
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
in the doInBackground-Method of your 1st AsyncTask?

httppost method of android doesnt work with namevalue pairs

The code below creates a form whose results are to be posted to server(request to a server)... i tried the same form using html with same form fields it works but here it does not work and redirects to the home page of the website.....
public class MainActivity extends Activity {
Button submit,fpass;
EditText wbpasswd,wblogid;
TextView loginid,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wblogid = (EditText) findViewById(R.id.wblogid);
wbpasswd = (EditText) findViewById(R.id.wbpasswd);
submit = (Button) findViewById(R.id.submit);
fpass = (Button) findViewById(R.id.fpass);
loginid = (TextView) findViewById(R.id.loginid);
password = (TextView) findViewById(R.id.password);
fpass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "You have clicked the fpass button",
Toast.LENGTH_SHORT).show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.ebharatgas.com/ebgas/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}).start();
//Toast.makeText(getBaseContext(), "You have clicked the fpass button",
//Toast.LENGTH_SHORT).show();
}
});
}
}
Also please tell me how can i display the response from the server on my android activity... and i am a beginner of android programming... please help me.... thanks in advance..
give it a try like this:
private class JsonResponse extends AsyncTask {
String response = "";
protected void onPreExecute()
{
}
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
}
}
protected String doInBackground(final String... args)
{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
} //Formatting & Code setting required

Connecting and getting data through web API in android

Can anybody please help me with this one. I am trying to get information in a server through web API, I believe, in my code below that I can already connect to the server (because no error appear). But when I am trying to display information that that I get, it display null value. I'm not sure where a forgot something or if my way of parsing it is right.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewFirstName = (TextView) findViewById(R.id.textViewFirstName);
textViewLastName = (TextView) findViewById(R.id.textViewLastName);
display = (TextView) findViewById(R.id.display);
spn_Display = (Spinner)findViewById(R.id.spn_Display);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
in = null;
DoPOST mDoPOST = new DoPOST(MainActivity.this, editTextSearchString.getText().toString());
Toast.makeText(getApplicationContext(), editTextSearchString.getText().toString(), 6).show();
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
public class DoPOST extends AsyncTask<String, Void, Boolean>
{
Context mContext = null;
String strNameToSearch = "";
//Result data
String strFirstName;
String strLastName;
int intAge;
int intPoints;
Exception exception = null;
DoPOST(Context context, String nameToSearch){
mContext = context;
strNameToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "admin"));
nameValuePairs.add(new BasicNameValuePair("Password", "admin123"));
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://examplesvr4.sample.com:1217/api/subbrands");
HttpGet httpget = new HttpGet("http://examplesvr4.sample.com:1217/api/subbrands");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("SubBrandId");
strLastName = jsonObject.getString("SubBrandName");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewFirstName.setText("First Name: " + strFirstName);
textViewLastName.setText("Last Name: " + strLastName);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}

Fail to display server's respond

Here I am trying to retrieve the response from the server and display it, but I am failed to do so, the response text does not appear in my text view, insetead the default value of the string does, may I ask how can I achieve my goal. And why my code cannot finish the task.
Here is my android program:
public class Chico extends Activity {
GrabURL grab;
TextView mRespond;
String line;
#Override
public void onCreate(Bundle savedInstanceState) {
//create the activity
super.onCreate(savedInstanceState);
//set up the layout
setContentView(R.layout.activity_chico);
mRespond = (TextView) findViewById(R.id.Respond);
mRespond.setVisibility(View.GONE);
grab = new GrabURL();
line = "line";
//set up the button for check in
Button btnin = (Button) findViewById(R.id.inbutton);
btnin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//set the values
grab.onPreExecute("TechID", Build.SERIAL);
grab.onPreExecute("Type", "Checkin");
//set the destination and send the request
grab.execute(new String[]{"http://192.168.1.150/Me/testing.php"});
//close the activity
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
//finish();
}
});
}
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
#Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
}
And here is the php file, it just prints a line:
<?php
print "testing";
?>
Move this code to your AsyncTask's onPostExecute():
...
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);

Categories

Resources