Volley and Asynctask response are both slow - android

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.

Related

I can't retrieve data from server to android studio although data is shown in a browser

I have recently made an application in android studio 2.3 to show data from a server the link that I use is working properly in a browser and data is shown successfully in json format. But in my application I can't retrieve these data, I add avolley lib in my app gradle file like this :
compile 'com.mcxiaoke.volley:library:1.0.18'
The code I use in MainActivity is :
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String url = "http://abdulwahid.esy.es/show.php";
TextView txtshow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtshow = (TextView) findViewById(R.id.txtshow);
rq = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarr = response.getJSONArray("allstudents");
for (int i = 0; i < jarr.length(); i++) {
JSONObject res = jarr.getJSONObject(i);
String id = res.getString("id");
String name = res.getString("name");
String info = res.getString("info");
txtshow.append("\n" + id + " - " + name + "\n" + info + "\n" + "------------------" + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
rq.add(jor);
}
The link of php file that I use is executed successfully in a web browser.
How to show data in my application or is there another code or library to use for retrieving data form online ?
you can use StringRequest instead of jsonObject with the new library of volley
compile 'com.android.volley:volley:1.0.0'
Use this code to retrieve data, in string line your data will be appended as a complete string as shown in browser
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abdulwahid.esy.es/show.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
The problem is that the Content-Type header is not set in the response of your server. For Volley to be able to parse it, you will need that header set to application/json.
Add the following line in your show.php:
header('Content-Type: application/json');
Edit
After the above change, the response seems strange...
I can see strange characters in the response, that might be causing parsing issues on the client side.

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.

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

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

How to send JSON string to ASP.NET C#-based web server from Android?

I cannot post or send my JSON string t ASP.NET C# based web server from android.
Here is my code, I have retrieve data from SQLite database using cursor and which I have converted these data into JSONobject and then JSONstring.
Code are given below:
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
But now after that very next line I want to send this JSONstring to C# web Server
Code:
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),
"UTF-8");
entity.setContentType("application/json;charset=UTF-8");// text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
}
I have call my function from sub menu like this:
calling Function code:
case R.id.submenu1_1:
if (item.isChecked())
item.setChecked(false);
else {
item.setChecked(true);
// Export Online
try {
new ExportDatabaseOnline().execute();
} catch (Exception ex) {
Log.e("Error in ActivityB", ex.toString());
}
}
// Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .1",
// Toast.LENGTH_SHORT).show();
return true;
Now the full function code which I have told you earlier in partial. So my full function code is:
public class ExportDatabaseOnline extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
// private HttpResponse response;
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait...");
this.dialog.setTitle("Exporting Database To Online");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),"UTF-8");
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
} catch (Exception e) {
Log.e("ActivityB", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(MainActivity.this, "Export successful!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Export failed",
Toast.LENGTH_SHORT).show();
}
}
}
This code is not working, it shows successful message but doesn't post any JSON string to the website.

Categories

Resources