Android JSON Fetch Record of particular column - android

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();

Related

Android JsonArray into ListView

Im trying to parse json array data into listview!I searched the whole internet and always was on one point! Json aray must have header something like this
"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
Where by my understanding the "emp_info" is the header file by which i must search for rest data inside it in android!My College pretending that i can accept and parse the same data into listview without that header name,but every bit of code where i searched to parse json in android was a single line like this!
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("emp_inf");
where i just have to put the jsonarray header file as you can see in this piece of code!So please help me is that possible to accept json array without this code?because if i try to remove this code i get nullpointer in my code!Will be very happy if you could at least say yes or no!
Posting Full Codes!
Here is the android class which gets the Json and loads it into List View
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://54.148.41.171/server/index/dompy");
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
String outPut = name + "-" + number;
employeeList.add(createEmployee("data", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employee no" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
And by this json array im successfully able to fetch the json which type is the next!
{"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
And here is the json array which my college pretends that i must accept!
{"data":"123"}
And im Saying that its not possible to load this json into list view just because it dont have header file like mine the emp_info,but hes saying its not matter i just MUST accept!We just on same project and i just cant understand is it even possible to do what he says?
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
How can you get the data by "etc." tag I could not understand it firstly. It should return "" instead of employee number.

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.

Sending ArrayList from Android to PHP script using JSON

What is the Scenario
I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.
What I Have Done Successfully
I have Successfully send single value and Multiple Values from Android to PHP script using JSON
i have Received single and Multiple Records from mysql database to android using JSON
Here is the Code for inserting and getting value from server
class TeacherLogin1 extends AsyncTask<Void, Void, Void> {
String name,pass;
Context contextt;
int idofteach = 0;
int codee = 0;
TeacherLogin1(String pass1,String name1,Context context)
{
name = name1;
pass = pass1;
contextt = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
codee = Authenticate(name,pass);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(codee!=0)
{
Intent teachers = new Intent(context,TeachersView.class);
teachers.putExtra("TID", codee);
teachers.putExtra("TNAME", TeachName);
teachers.putExtra("sub1", subj1);
teachers.putExtra("sub2", subj2);
teachers.putExtra("sub3", subj3);
teachers.putExtra("sub4", subj4);
startActivity(teachers);
}
else
Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
codee = 0;
}
}
public int Authenticate(String name,String Pass)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pass",Pass));
try
{
HttpClient httpclient = new DefaultHttpClient();
ScriptsFilePath a = new ScriptsFilePath();
HttpPost httppost = new HttpPost(a.TeacherAuthen);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try {
JSONObject jsonResponse = new JSONObject(result);
if(jsonResponse != null)
{
JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
code = jsonChildNode.optInt("ID");
TeachName= jsonChildNode.optString("Name");
subj1= jsonChildNode.optString("subject1");
subj2= jsonChildNode.optString("subject2");
subj3= jsonChildNode.optString("subject3");
subj4= jsonChildNode.optString("subject4");
}
}
} catch (JSONException e) {
// Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
return code;
}
and the TeacherAuthen.php script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$uname="root";
$pwd='';
$db="examsystem";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
if(isset($_REQUEST)){
$name=$_REQUEST['name'];
$pass=$_REQUEST['pass'];}
$flag['code']=0;
$name1['code1'] = "sdf";
$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?>
where i am stuck
I dont no how to send ArrayList from android to PHP Script.
For Example I want to send these arraylists to php script =
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
and then in the PHP script i want to insert like this
"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "
if i am able to send even a single arrayList then i think i can make a way to do the above
and Thanks for you Time
This is your Array: you can create more as required in your example.
ArrayList<String> contact = new ArrayList<String>();
Then, create a JSONcontacts variable of type JSONObject to store this array in this object
JSONObject JSONcontacts = new JSONObject();
Now, loop through all elements in that contact array and store it in the JSONcontacts
//Loop through array of contacts and put them to a JSONcontact object
for (int i = 0; i < contact.size(); i++) {
try {
JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()
JSONObject EverythingJSON = new JSONObject();
and now put all your contact array and other arrays into it, right you loop through them as described above:
EverythingJSON.put("contact", JSONcontacts);
EverythingJSON.put("something", JSONsoemthing);
EverythingJSON.put("else", JSONelse);
now this is your AsynchTask to send them to your PHP server:
new AsyncTask() {
//String responseBody = "";
#SuppressWarnings("unused")
protected void onPostExecute(String msg) {
//Not Needed
}
protected Object doInBackground(Object... params) {
//Create Array of Post Variabels
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
//Add a 1st Post Value called JSON with String value of JSON inside
//This is first and last post value sent because server side will decode the JSON and get other vars from it.
postVars.add(new BasicNameValuePair("JSON", EverythingJSON.toString());
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.OnlineAPI);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
}.execute(null, null, null);
Now on the PHP server side, you can loop through this JSON as such:
FIrst of all, get that JSON from POST and store it in a var:
//Receive JSON
$JSON_Received = $_POST["JSON"];
Now decode it from JSON:
//Decode Json
$obj = json_decode($JSON_Received, true);
And this is the loop to go through the array of contacts and get he Key and Value from it:
foreach ($obj['contact'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
}
you can repeat this loop for other Arrays you have sent :) Good Luck!
You cant send Arraylist to server,its an object. The best way to solve your problem is
user JSON , you need to do something like that -
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
JsonArray jArr1= new JsonArray();
for(String data:A1)
{
jArr1.add(data);
}
JsonArray jArr2= new JsonArray();
for(String data:A2)
{
jArr2.add(data);
}
//convert each array list to jsonarray
JsonArray jArraySet = new JsonArray();
jArraySet.add(jArr1);
jArraySet.add(jArr2);
//add each json array to jArraySet
// then send the data via
HttpClient httpclient = new DefaultHttpClient();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("all_arraylist",jArraySet.toString()));
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
note: dont forget to do it in asynctask
in php section ,do the following
<?php
$all_arraylist = $_POST['all_arraylist'];
$all_arraylist= json_decode($all_arraylist,TRUE); //this will give you an decoded array
print_r($all_arraylist); // display the array
// after seeing the array , i hope you will understand how to process it.
?>
Very simple. you should parse your JSON in php and get array of objects that you have sent. Here is solution
$JSON_Received = $_POST["json"];
$obj = json_decode($JSON_Received, true);
$array_1st_name = $obj[0];
$array_2nd_name = $obj[1];
and so on you will get all array of object.

Integration of android app with backend

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

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