Error while sending a GET Request to a servlet from android - java

after searching around im able to retreive a response from my servlet , but i cant send a parameter (a username and a password parameter) from android to a servlet! My logcat shows this error:
04-0java.lang.ClassCastException: org.apache.http.client.methods.HttpGet cannot be cast to org.apache.http.HttpResponse
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:76)
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
and i cant understand why!
Here it is my android main activity:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
nameValue =URLEncoder.encode(name.getText().toString(), "UTF-8");
passValue =URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
List<NameValuePair> postParameters =
new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user",nameValue));
postParameters.add(new BasicNameValuePair("pass",passValue));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
((HttpResponse) httpGet).setEntity(formEntity);
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
Does anyone have any idea?
UPDATE:
now i have changed my android code like this:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
String nameValue ="user="+URLEncoder.encode(name.getText().toString(), "UTF-8");
String passValue ="&pass="+URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web?"+nameValue+passValue;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
this time runs without logcat errors but the parameters does not come to the servlet!

Looking at the stack trace, I guess your problem is at this line.
((HttpResponse) httpGet).setEntity(formEntity);
Why are you casting it to HttpResponse?
OK. You want to send user/pass parameters using HTTP GET. For HTTP GET, all parameters are part of the URL. Maybe this can give you some help on how to perform a HTTP GET and pass parameters in. But in general, URL would look like this
http://www.blah.com/servlet?user="1234"&pass="password"
The stuff after the ? in the URL contains all the parameters. But there is a length limit in the URL, if you exceed that length, you'll have to use HTTP POST.
Try this link to see if it can help you
http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88

i have modified the activity and the problem was that the URL and nameValue and passValue was declared on the wrong section of the code ! Here it is the right android code:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
content.setText("Vendosni Perdoruesin dhe Fjalekalimin");
Button button=(Button)findViewById(R.id.but);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameValue="&user="+name.getText().toString();
passValue ="&pass="+pass.getText().toString();
URL = "http://10.0.2.2:8080/login/web2?activitetiNR=1"+nameValue+passValue;
AsyncTaskRunner runner = new AsyncTaskRunner();
Log.i("url",URL);
Log.i("url",nameValue);
Log.i("url",passValue);
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}

Related

Late-enabling -Xcheck:jni Android studio logs

I am trying to run a simple app that extracts html from a page and displays it in the logs.
Here is the Java code:
package com.example.khkr.jsondemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class DownloadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
URL url;
String result = "";
try {
url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data!=-1)
{
char current = (char)data; result+=current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content",weatherInfo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is I don't see any errors in the code , but when I try to run the app, I get the following Logs which never make sense to me. Here are the logs:
https://gist.github.com/khkr/d96396ff6f8e34b3e9a430a805b735a7

How to import class from another file in java in Android Studio?

I'm trying to call the function getUrlContents(string) inside my seismic_text.java file to my MainActivity.java file. How can I call the function from anywhere in the file? Any information or tip is appreciated. I include my files down below.
This is my MainActivity.java:
package bt.alfaquake;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.NotificationManager;
import android.content.Intent;
import android.view.View;
import android.app.PendingIntent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.NotificationCompat;
import bt.alfaquake.seismic_text;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
}
}
This is my seismic_text.java:
package bt.alfaquake;
import java.net.*;
import java.io.*;
public class seismic_text {
public static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
}
You can call seismic_text.getUrlContents(url); but it will cause NetworkOnMainThreadException
Just wrap this call to Simple AsynkTask.
class MyTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return seismic_text.getUrlContents(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO handle result here
}
}
And call it from your code:
new MyTask().execute();
Simply call this in your MainActivty.java:
seismic_text.getUrlContents(url);

setListAdapter unable to be resolved

a real amateur developer here in dire need of some assistance. I've been trying to parse JSON data and turn it into a list of items, but I am having difficulties attempting to use the setListAdapter method despite importing it into the class. Any help would be massively appreciated.
Here is my main activity, error is in the onPostExecute method
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class JSON extends Activity {
// Coordinates used for centering the Map
private final static String UNAME = "aporter";
private final static String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
+ UNAME;
public static final String TAG = "MapsEarthquakeMapActivity";
// Set up UI and get earthquake data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new HttpGetTask().execute(URL);
}
private class HttpGetTask extends
AsyncTask<String, Void, List<GeonameRec>> {
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<GeonameRec> doInBackground(String... params) {
HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();
try {
// Get Earthquake data in JSON format
// Parse data into a list of EarthQuakeRecs
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}
return null;
}
#Override
protected void onPostExecute(List<GeonameRec> result) {
if (null != mClient)
mClient.close();
setListAdapter(new ArrayAdapter<String>(
JSON.this,
R.layout.listitem, result));
}
}
}
}
And here is my class where I format the JSON response.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONResponseHandler implements
ResponseHandler<List<GeonameRec>> {
#Override
public List<GeonameRec> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<GeonameRec> result = new ArrayList<GeonameRec>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray earthquakes = object.getJSONArray("earthquakes");
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject tmp = (JSONObject) earthquakes.get(i);
result.add(new GeonameRec(
tmp.getDouble("lat"),
tmp.getDouble("lng")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
setListAdapter method is available in ListActivity not in Activity.
to do so in an Activity sub class, you should define your ListView and call listView.setAdapter

errors in extracting json object

I have to retrieve json object from json file from this url.
My code is throwing java.lang.RuntimeException in doInBackground() and string to jsonObject conversion exception.
Can anyone help me at this? I am new to Android programming.
package course.examples.networkingearthquake;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
public class HttpActivity extends ActionBarActivity {
TextView mTextView;
EditText etInput;
TextView input;
String number;//edited
int num;//edited
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
mTextView = (TextView)findViewById(R.id.text1);
input = (TextView)findViewById(R.id.input);
etInput = (EditText)findViewById(R.id.etInput);
input.setText("Input");
//number = etInput.getText().toS();
final Button btDisplay = (Button)findViewById(R.id.btDisplay);
btDisplay.setText("DISPLAY");
btDisplay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new HttpGetTask().execute();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
private static final String TAG = "HttpGetTask";
private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params){
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
// ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
return mClient.execute(request,responseHandler);
}catch(ClientProtocolException exception){
exception.printStackTrace();
}catch(IOException exception){
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
if(null != mClient)
mClient.close();
mTextView.setText(result);
}
}
private class JSONResponseHandler implements ResponseHandler<String>{
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
String result = null;
String JSONResponse = new BasicResponseHandler().handleResponse(response);
JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3);
num = Integer.parseInt(number);// edited
try {
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
JSONArray features = responseObject.getJSONArray("features");
JSONObject retObject = (JSONObject)features.get(num);//edited
// JSONObject geometry = (JSONObject)retObject.get("geometry");
result = retObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
The JSON returned by the URL you specify containts eqfeed_callback() which needs to be stripped in order to make it valid JSON.
It seems like you have done this in your response handler, but you are cutting off one character too much at both the start and the end.
Try this:
JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2);

Inserting data into MySQL using http-post and AsyncTask doesn't work

I am making an app that needs to post some data in MySQL database. The code doesn't show any errors, but no data is sent. My php file and HttpPost seem to work fine - I tried changing the php file so that it already included the data and then it worked. Here's my php:
<?php
$username = "user";
$password = "password";
$hostname = "mysql.xxx.com";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("myapp_xxx_com",$dbhandle)
or die("Could not select examples");
//retrieve the data
$street = $_POST['Street'];
$house = $_POST['House'];
$city = $_POST['City'];
$comment = $_POST['Comment'];
mysql_query ("INSERT INTO Address (Street, Number, City, Comment, TimeOrdered) VALUES('$street', '$house, '$city', '$comment', NOW())");
mysql_close($dbhandle);
?>
And here's my java code:
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.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class OrderSummary extends Activity implements OnClickListener {
private EditText editStreetText, editNumberText, editCityText, editCommentText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
editStreetText = (EditText) findViewById(R.id.summary_street);
editNumberText = (EditText) findViewById(R.id.summary_house);
editCityText = (EditText) findViewById(R.id.summary_city);
editCommentText = (EditText) findViewById(R.id.summary_comment);
button = (Button)findViewById(R.id.button_post_data);
button.setOnClickListener(this);
#Override
public void onClick(View v) {
String streetValue = editStreetText.getText().toString();
String numberValue = editNumberText.getText().toString();
String cityValue = editCityText.getText().toString();
String commentValue = editCommentText.getText().toString();
new SummaryAsyncTask().execute(streetValue, numberValue, cityValue, commentValue);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public void postData(String street, String number, String city, String comment)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Street", street));
nameValuePairs.add(new BasicNameValuePair("House", number));
nameValuePairs.add(new BasicNameValuePair("City", city));
nameValuePairs.add(new BasicNameValuePair("Comment", comment));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
private class SummaryAsyncTask extends AsyncTask<String, Void, Void>{
protected Void doInBackground(String... params){
postData(params[0], params[1], params[2], params[3]);
return null;
}
}
}
}
I based the code on this tutorial http://mobiledevtuts.com/android/android-http-with-asynctask-example/ . I hope someone can help me with this.
You got an error in the PHP: '$house must be '$house'
Java code tested and working I just changed it a little bit
import android.os.Bundle;
import android.app.Activity;
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.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class OrderSummary extends Activity {
String streetValue;
String numberValue;
String cityValue;
String commentValue;
private EditText editStreetText, editNumberText, editCityText, editCommentText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
editStreetText = (EditText) findViewById(R.id.summary_street);
editNumberText = (EditText) findViewById(R.id.summary_house);
editCityText = (EditText) findViewById(R.id.summary_city);
editCommentText = (EditText) findViewById(R.id.summary_comment);
button = (Button) findViewById(R.id.button_post_data);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
streetValue = editStreetText.getText().toString();
numberValue = editNumberText.getText().toString();
cityValue = editCityText.getText().toString();
commentValue = editCommentText.getText().toString();
new SummaryAsyncTask().execute((Void) null);
}
});
}
class SummaryAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String street, String number, String city,
String comment) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Street", street));
nameValuePairs.add(new BasicNameValuePair("House", number));
nameValuePairs.add(new BasicNameValuePair("City", city));
nameValuePairs.add(new BasicNameValuePair("Comment", comment));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
#Override
protected Boolean doInBackground(Void... params) {
postData(streetValue, numberValue, cityValue, commentValue);
return null;
}
}
}
Do not forget the Internet permission on android manifest
<uses-permission android:name="android.permission.INTERNET"/>
You can put the permission after <uses-sdk /> tag
public class RefreshChildren extends AsyncTask{
WebService service;
Helper helper;
RefreshChildren(){
service =new WebService();
helper =new Helper(null);
}
#Override
protected String doInBackground(String... params) {
refreshChildren();
return null;
}
private void refreshChildren() {
Log.d("Refresh", "children started");
List<ChildrenInstallBeen> childrenList=new ArrayList<ChildrenInstallBeen>();
childrenList=service.getChildrenListRefresh();
Iterator<ChildrenInstallBeen> iterator=childrenList.iterator();
while (iterator.hasNext()) {
ChildrenInstallBeen been = (ChildrenInstallBeen) iterator
.next();
Log.d("refresh children : ", ""+been.getFirst_name());
}
}
}

Categories

Resources