Integration of android app with backend - android

i am developing an android app which i have to integrate with backend(developed in java and spring). Which will be the best way to integrate either WebServices or through http(JSON)..?
Thanks in advance.

To get a JSON Response in Android/Java you need to do this:
Create a custom API Connector class
Declare a method that will return a JSON Array
Create a AsyncTask class (optional)
Decode JSONArray
1.
public class CustomAPIConnector {
public final String URL = "http://10.0.2.2/your-project-url/"; // 10.0.2.2 goes to computer localhost if you put localhost, it will go to the devices localhost which should not exist
2.
public JSONArray getUserInfo(String username, String password) {
HttpEntity httpEntity = null;
// Add your POST variables to receive on your backend
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL + "login.php"); // have split up URL and page so you can redirect to different links easier if the URL changes
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = null;
if(httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
3.
private class AvailableUser extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableUsername(etusername.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableUsername(jsonArray);
}
}
private class AvailableEmail extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableEmail(etemail.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableEmail(jsonArray);
}
}
4.
private void checkAvailableEmail(JSONArray jsonArray) {
String s = "";
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = new JSONObject();
json = jsonArray.getJSONObject(i);
if(!json.getString("count").isEmpty()) {
if(json.getString("count").equalsIgnoreCase("0")) {
status.setText("");
passedemail = true;
return;
} else {
status.setText("Email Taken");
passedemail = false;
return;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
status.setText("Failed - checkAvailableEmail");
}
}
Please note that this is actual code I have in one of my apps that registersa user, the getUserInfo gets all information from the user, and the Available email asynctask class is separate from the getUserInfo, it is the registering part, that checks if the email is available.
From here on, you can copy the code and change what you need to.

JSON as name says java script object notation would help you to exploit OOPS , POST/GET and js at backend .
I use JSON , its easy to code , parse and handle

Related

Showing values of multiple columns in database via android

I have an app that should send a the phone number and retrieve a value from the database, now I change the query and my code should retrieve values of multiple columns, So where changes should be in my code.
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.97:89/Derdeery/bankOsman.php";
private AsyncCallback asyncCallback;
public JSONTransmitter(Context context) {
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data)
{
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
String resFromServer = "";
try {
StringEntity se = new StringEntity("json=" + json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return resFromServer;
}
public static interface AsyncCallback {
void onResponse(String res);
}
}
Here is something to consider:
First, in your php code (server-side), query your data perhaps separately. So for instance, you can get those that match column A and then query for those that match column B.
Generate Json for each (A and B accordingly)
Then create a single JSON object that contains the two sets of data like this:
{
"DataFromColumnA" : {},
"DataFromColumnB" : {}
}
Once you have made your HTTP request in your android code, you can get the specific data by getting "DataFromColumnA" json Object and B respectively.
I hope this helps you get your problem solved!

Volley and Asynctask response are both slow

Problem
I am about to finish a big project and I found out that my app is slow on 3G when it comes to downloading data from a server and displaying it. I read about Volley last week, and I soon implemented it to see if it's faster than Asynctask. Not exactly. The response from both methods are very slow on 3G (fast on WIFI), and when I say very slow, I mean users need to wait 0.8-3.5s till the data is displayed.
So I checked the code and found that the problem is with the response. After the response has been received on Android side, ListView population and display of data happens under 0.3s, but till the response is received, users need to wait.
I am using a VPS with HTTPS connection.
What I tried
I tried setting
HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
and
httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
based on this post.
I tried removing the whole db connection and query and just posting the response in php meaning the whole content was the script was this:
echo "[[{...content of the query }]]
and in this case the response was much faster (but I cannot say 100%)!
I tried putting the response (try No. 2) on a HTTP shared server (so not the query, because I didn't want to mock with databases), and I don't know if that means anything but the response was about 0.8s in both HTTP and HTTPS server.
Here's my code
With Asynctask
public class DownloadBucket extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected void onPostExecute(ArrayList<String> result) {
myadapter = new MyAdapter(BucketUsers.this, arr_users_id, arr_users_username, arr_users_firstname, arr_users_lastname, arr_users_photo, arr_users_followed);
lv.setAdapter(myadapter);
}
actionBar.show();
#Override
protected void onPreExecute() {
actionBar.hide();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
try{
HttpParams httpparams = new BasicHttpParams();
//HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
Log.i("At bucketid", bucketid + "");
Log.i("At session_userid", session_userid + "");
nameValuePairs.add(new BasicNameValuePair("session_userid", session_userid));
nameValuePairs.add(new BasicNameValuePair("bucketid", bucketid));
nameValuePairs.add(new BasicNameValuePair("start", params[1]));
nameValuePairs.add(new BasicNameValuePair("finish", params[2]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("error", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
Log.i("sb", sb + "");
Bresult=sb.toString();
Log.i("Bresult", Bresult + "");
}catch(Exception e){
Log.e("error", "Error converting result "+e.toString());
}
ArrayList<String> result = new ArrayList<String>();
try {
jArray = new JSONArray(Bresult);
for(int i=0;i<jArray.length();i++){
JSONArray innerJsonArray = jArray.getJSONArray(i);
for(int j=0;j<innerJsonArray.length();j++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
arr_users_id.add(jsonObject.getString("ID"));
arr_users_username.add(jsonObject.getString("USERNAME"));
arr_users_firstname.add(jsonObject.getString("NAME"));
arr_users_lastname.add(jsonObject.getString("NAME2"));
arr_users_photo.add(jsonObject.getString("PHOTO"));
arr_users_followed.add(jsonObject.getString("DO_I_FOLLOW_HIM"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
With Volley
private void makeJsonArrayRequest(final String list, final String start, final String finish) {
StringRequest postReq = new StringRequest(Method.POST, loadusers, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
//Here we are already at 0.8-3.5 seconds!
//Everything after this happens very fast
if (response.length() > 10) {
try {
jArray = new JSONArray(response);
for(int i=0;i<jArray.length();i++){
JSONArray innerJsonArray = jArray.getJSONArray(i);
for(int j=0;j<innerJsonArray.length();j++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
arr_users_id.add(jsonObject.getString("ID"));
arr_users_username.add(jsonObject.getString("USERNAME"));
arr_users_firstname.add(jsonObject.getString("NAME"));
arr_users_lastname.add(jsonObject.getString("NAME2"));
arr_users_photo.add(jsonObject.getString("PHOTO"));
arr_users_followed.add(jsonObject.getString("DO_I_FOLLOW_HIM"));
}
}
pb.setVisibility(View.GONE);
loading_ll.setVisibility(View.GONE);
llMain.setVisibility(View.VISIBLE);
if (arr_users_id.size() < 31) {
myadapter = new MyAdapter(BucketUsers.this, arr_users_id, arr_users_username, arr_users_firstname, arr_users_lastname, arr_users_photo, arr_users_followed);
lv.setAdapter(myadapter);
} else {
myadapter.notifyDataSetChanged();
}
actionBar.show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
all_items_downloaded = true;
lv.removeFooterView(loadMoreView);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// System.out.println("Error ["+error+"]");
Log.i("VOLLEY_ERROR", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("session_userid", session_userid);
params.put("bucketid", bucketid);
params.put("start", start);
params.put("finish", finish);
return params;
}
};
postReq.setShouldCache(false);
AppController.getInstance().addToRequestQueue(postReq);
}
PHP
<?php
require_once($_SERVER['SERVER_ROOT'].'mysecretdbdata.php');
$response = array();
try {
$conn = new PDO("mysql:host=$host;dbname=$database", $dbusername, $dbpassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response = '0';
[QUERY]
print(json_encode($output));
?>
Is this normal? Are there any ways to speed things up? I don't know how it works, but e.g. with Pinterest when you click on an object, the image and the data is displayed immediately. Users make their expections based on top apps and even I don't like using my own app when it's slow.

Android JSON Fetch Record of particular column

I want to fetch the record of particular column using JSON Parsing.Here is my screen shot of PHP MySql which is included some data.
Here is above i want to fetch all the record of cat_id = 2 in My Android Application in spinner .But i can't understand how to do this.Can some one help me please . Thanks in advanced.
create a PHP code to get the rows and print it in JSON fromat
$res=mysql_query("select * from table_name where cat_id = '2'") or die(mysql_error());
$assInfo = array();
$num=mysql_num_rows($res);
if($num>0){
$obj=mysql_fetch_array($res);
$assInfo["first"]=$obj["column_name"];
$assInfo["second"]=$obj["another_column"];
array_push($response["info"], $assInfo);
}else{
$response["success"] = 0;
}
echo json_encode($response);
and in android start an Asynctask to grab printed text in background.
public class gettingData extends AsyncTask<Void, Void, Void> {
private String jsonResult;
public gettingData() {
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("canpass", "herevalue"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
Log.v("jr", jsonResult);
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (jsonResult != null) {
try {
if (jsonResponse.optString("success").matches("0")) {
//your code for no rows selected
}else{
JSONArray jsonMainNode = jsonResponse.optJSONArray("info");
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
String first = jsonChildNode.optString("first");
String second = jsonChildNode.optString("second");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Connection Time Out", Toast.LENGTH_LONG)
.show();
}
}
Execute this class in you activity -
new gettingData().execute();

Resuse of Async task code in my various file

I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}

android http post asynctask

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")

Categories

Resources