I want to post data using JSON. But i am not able to achieve this.
This is my java code:
package com.bandapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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 org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class UpcomingShow extends ListActivity {
public static final String TAG_SHOW_TITLE = "show_title";
public static final String TAG_SHOW_VENUE = "show_venue";
public static final String TAG_SHOW_DATE = "show_date";
public static final String TAG_SHOW_TIME = "show_time";
public static String URL = "http://example.com/example/example/mainAPI.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upcoming_show);
new AsyncData().execute();
}
class AsyncData extends AsyncTask<String, Void, Void> {
JSONParser jParser;
ArrayList<HashMap<String, String>> upcomingShows;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(UpcomingShow.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
upcomingShows = new ArrayList<HashMap<String,String>>();
params.add(new BasicNameValuePair("rquest", "={"));
params.add(new BasicNameValuePair("method","band_info"));
params.add(new BasicNameValuePair("body","[{}]}"));
String res = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
res = EntityUtils.toString(response.getEntity());
JSONTokener t = new JSONTokener(res);
JSONArray a = new JSONArray(t);
JSONObject o = a.getJSONObject(0);
String sc = o.getString(TAG_SHOW_TITLE);
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(UpcomingShow.this, upcomingShows, R.layout.upcomingshows_row, new String[] {
TAG_SHOW_TITLE, TAG_SHOW_DATE, TAG_SHOW_TIME, TAG_SHOW_VENUE }, new int[] { R.id.textTitle, R.id.textdate,
R.id.textTime, R.id.textVenue });
setListAdapter(adapter);
}
}
}
Also i am not able to Toast any of the message that i have kept in doInBackground(). Can you please help me solving this please...
You can't toast into doInBackground() because you can't update the UIview during the thread execution ! You should to use 'onProgress' and 'publishProgress'
change :
class AsyncData extends AsyncTask<String, Void, Void>
to:
class AsyncData extends AsyncTask<String, String, Void>
and override onProgress for toast:
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0] != null)
Toast.makeText(UpcomingShow.this, values[0], Toast.LENGTH_SHORT).show();
}
And into doInBackground():
if(sc.equals("1"))
{
publishProgress(sc);
}
else
{
publishProgress("Fail.");
}
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
Remove this code form doInBackground
You can not update your UI on do in background , you can get result in onPostExecute and able to pop up those toast .
I tried sending a post your request through Postman(google extension) and the URL you've provided responded with HTTP Status 200 but without a response message. Problem is, based on the code provided, is that you're expecting a message response from the said url. You should probably check with the server you are connecting with.
While doing AsyncTask<String, Void, Void> Task you can’t achieve Toast display in Main thread, user Log.d(“TAG”,”your-text”);
You can achieve Toast in onPostExecution()
}catch (Exception e)
{
e.printStackTrace();
}
return sc;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if(result.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, result, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
}
Related
I am trying to perse data from my server. I am using HttpClient to get my data. But sometime the data is not fetched and i am shown the error called crlf expected at the end of chunk.I have tried to Change buffer size in jmeter properties following this link but the issue is not solved. I am giving my code below.Cant find the solution. Need help.
FavouriteCategoriesJsonParser.java
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class FavouriteCategoriesJsonParser {
public static ArrayList<String> selectedCategories = new ArrayList<>();
public ArrayList<Category> getParsedCategories() {
String JsonFavouriteCategories = "";
ArrayList<Category> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://xxxxx.com.yy/test_file/get_value.php");
try {
// ServiceHandler jsonParser = new ServiceHandler();
// String json = jsonParser.makeServiceCall(campaign_credit,ServiceHandler.GET,params);
HttpResponse httpResponse = httpClient.execute(httpGet);
JsonFavouriteCategories = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(JsonFavouriteCategories);
for (int i = 0; i < jsonArray.length(); i++) {
Category genres = new Category();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setCateogry_id(MyJsonObject.getString("DOC_CODE"));
genres.setCategory_Name(MyJsonObject.getString("DOC_CODE"));
genres.setCategory_Name2(MyJsonObject.getString("DOC_NAME"));
genres.setSelected(Boolean.parseBoolean(MyJsonObject.getString("SELECTED")));
MyArraylist.add(genres);
if (MyJsonObject.getString("SELECTED").equals("true")) {
selectedCategories.add(MyJsonObject.getString("DOC_CODE"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
FatchData.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.appcompat.app.AppCompatActivity;
import com.myproject.demo.adapter.CategoryAdapter;
import com.myproject.demo.model.Category;
import com.myproject.demo.FavouriteCategoriesJsonParser;
//PcProposalDoc
public class PcProposalDoc extends AppCompatActivity {
Context context;
ArrayList<Category> array_list;
FavouriteCategoriesJsonParser categoryJsonParser;
String categoriesCsv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.proposal_activity_main);
Typeface fontFamily = Typeface.createFromAsset(getAssets(), "fonts/fontawesome.ttf");
Button button = (Button) findViewById(R.id.selectCategoryButton);
context = this;
new asyncTask_getCategories().execute();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
categoriesCsv = FavouriteCategoriesJsonParser.selectedCategories.toString();
categoriesCsv = categoriesCsv.substring(1, categoriesCsv.length() - 1);
if (categoriesCsv.length() > 0) {
new asyncTask_insertUpdatefavouriteCategories().execute();
} else {
Toast.makeText(context, "Please Select Doctor", Toast.LENGTH_SHORT).show();
}
}
});
}
public class asyncTask_getCategories extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("Please wait...");
dialog.setMessage("Loading Doctors!");
dialog.show();
array_list = new ArrayList<>();
categoryJsonParser = new FavouriteCategoriesJsonParser();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = categoryJsonParser.getParsedCategories();
return null;
}
#Override
protected void onPostExecute(Void s) {
ListView mListViewBooks = (ListView) findViewById(R.id.category_listView);
final CategoryAdapter categoryAdapter = new CategoryAdapter(context, R.layout.row_category, array_list);
mListViewBooks.setAdapter(categoryAdapter);
super.onPostExecute(s);
dialog.dismiss();
}
}
public class asyncTask_insertUpdatefavouriteCategories extends AsyncTask<Void, Void, Void> {
String response;
#Override
protected Void doInBackground(Void... params) {
response = InsertUpdateFavouriteCategories.insertUpdateCall(categoriesCsv);
return null;
}
#Override
protected void onPostExecute(Void s) {
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
super.onPostExecute(s);
}
}
}
May be old, Can save some time.....
I got this error where Server is in Python and Clinet is Java.
1st Error from Java Client
Error while sending data over http java.io.IOException: CRLF expected at end of chunk: 79/82
java.io.IOException: CRLF expected at end of chunk: 79/82
2nd Error from Java Clinet
Error while sending data over http java.io.IOException: chunked stream ended unexpectedly
java.io.IOException: chunked stream ended unexpectedly"
Both the errors got resolved by changing the ok response with chunked stream size
One with issues
HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nServer: Jetty(6.1.26)\r\n\r\nDE\r\n"
Resolved with
HTTP/1.1 200 OK\r\nContent-Length: 20000\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nServer: Jetty(6.1.26)\r\n\r\n229\r\n"
Note = nDE is replaced with n229
My Android app got one AsyncTask which gets me data from my server. When I pull a few rows from the database then it's done very fast and I don't need a loading animation while it is getting fresh data.
When I pull 2,3k rows from the database, that might slow things down so I decided to use some indicator (loading animation), so the user knows that data is collecting in the background. I got one activity Fill_in_phone where I call the asyncTask named GetOcitanja.
My code for the AsynTask is:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class GetOcitanja extends AsyncTask<Object, Void, String> {
Activity _context;
String _str_mesg;
String _str_naslov;
public ProgressDialog progress;
public GetOcitanja(Activity context, String str_naslov, String str_message){
this._context = context;
this._str_naslov = str_naslov;
this._str_mesg = str_message;
}
#Override
protected void onPreExecute() {
//super.onPreExecute();
progress = ProgressDialog.show(_context, _str_naslov,
_str_mesg, true);
progress.show();
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
progress.dismiss();
}
#Override
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(Config.url_get_ocitanja_async_taks);
String odg="";
try {
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
odg = EntityUtils.toString(entity, HTTP.UTF_8);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return odg;
}
As you can see, I put a 2 seconds sleep time to simulate a large dataset. I call this AsyncTask in my Fill_in_Data activity:
GetOcitanja asyncTask=new GetOcitanja(Fill_in_phone.this, "a","b");
asyncTask.execute();
String response="";
try {
response= asyncTask.get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
}
I followed a few solutions from SO and nothing helped. What did I do wrong?
response= asyncTask.get();
remove that.
You have already an asyncTask.execute().
Handle the response in onPostExecute().
I asked you before how you called your async task as i supposed you used .get(). You are calling it twice and are only showing that now.
Place your ProgressDialog in onPreExecute, sample code below:
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
https://stackoverflow.com/a/25998219/5202007
public GetOcitanja(Activity context, String str_naslov, String str_message){
this._context = context;
this._str_naslov = str_naslov;
this._str_mesg = str_message;
progressDialog = new ProgressDialog(_context);
progressDialog.setTitle("Progress");
}
can you try create progress dialog inside constructor
Im having trouble in the asynctask. Having fatal error. This is the part where the error occurs. It tells me String success is unused. The whole code is now posted. Help pleaseIm having trouble in the asynctask. Having fatal error. This is the part where the error occurs. It tells me String success is unused. The whole code is now posted. Help pleaseIm having trouble in the asynctask. Having fatal error. This is the part where the error occurs. It tells me String success is unused. The whole code is now posted. Help pleaseIm having trouble in the asynctask. Having fatal error. This is the part where the error occurs. It tells me String success is unused. The whole code is now posted. Help please
package com.example.ram2;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
EditText user, pass;
Button mSubmit, mRegister;
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2/FuckAnd/login.php";
static final String TAG_SUCCESS = "success";
static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
mSubmit = (Button) findViewById(R.id.login);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
public class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
pDialog.dismiss();
finish() ;
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String username = user.getText().toString();
String password = pass.getText().toString();
String success = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
Log.d("Login attempt", json.toString());
success= json.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
//JSONObject json;
// dismiss the dialog once product deleted
pDialog.dismiss();
//if (TAG_SUCCESS == null) {
if (result.equals("success")) {
//if (success.equals(success)) {
//Log.d("Login Successful!", json.toString());
Toast.makeText(Login.this, "Login Successful!", Toast.LENGTH_SHORT).show();
//Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(LoginActivity.this, PortalContents.class);
finish();
//startActivity(i);
//return null;
}
else {
//Log.d("Login Failure!", json.getString(TAG_MESSAGE));
Toast.makeText(Login.this, "Login Fail!", Toast.LENGTH_LONG).show();
//return json.getString(TAG_MESSAGE);
//return json.getString(TAG_MESSAGE);
}
}
}
}
You need to return the type String from the doInBackground as the onPostExecute is expecting that. The return from doInBackground also needs to match the third parameter on the AsyncTask declaration which is the expected type of the onPostExecute (each parameter on the AsyncTask needs to match the onPreExecute, doInBackground, and onPostExecute, respectively; be aware that the first two are arrays of the data type).
So your return null is going to cause an issue with the onPostExecute(String result).
More info about AsyncTasks can be found in the developer guide at http://developer.android.com/reference/android/os/AsyncTask.html.
Try this:
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String username = arg[0];
String password = arg[1];
String success = null; //this keeps getting error
//...
}
And:
new Task().execute(user.getText().toString(),pass.getText().toString());
I want to add progress bar to android project to show upload files. here is my code for upload images to server. postFile() is working fine. How to visible progress bar?
I want to add progressbar here.pleas see this code in the class
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
Here is the class
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
public String DataSendingTo="http://www.mysite.com/receiver.php/Incoming_Data_Receive";
public String txtDescription;
public static String[] FileNameStrings = new String[8];
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... strings) {
try
{
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
private void postFile(){
try{
// the file to be posted
for(int f=0;f <FileNameStrings.length;f++)
{
String textFile = FileNameStrings[f];
if(textFile==null)
{
break;
}
Log.v("Sending", "textFile: " + textFile);
// the URL where the file will be posted
Log.v("Sending", "postURL: " + DataSendingTo);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(DataSendingTo);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("Sending", "Response: " + responseStr);
//wait(1500);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();
}
}
}
Add below code to your AsyncTask
class PostDataAsyncTask extends AsyncTask<String, String, String> {
private ProgressDialog mDialog = null;
public PostDataAsyncTask(Context activityContext) {
mDialog = new ProgressDialog(activityContext);
}
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Wait...");
mDialog.setCancelable(false); // Depends on app behaviour
mDialog.show();
}
#Override
protected String doInBackground(String... strings) {
// Same as your implementation
}
#Override
protected void onPostExecute(String lenghtOfFile) {
if (mDialog != null)
mDialog.dismiss();
}
}
And call this as
PostDataAsyncTask postDataAsyncTask = new PostDataAsyncTask(Youractivity_name.this);
postDataAsyncTask.execute(With_your_params);
you can se ein this example just call progressdialog in onPreExecute() method.,and refer this example.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** Reference to the view which should receive the image */
private final WeakReference imageRef;public DownloadImageTask(ImageView imageView) {
imageRef = new WeakReference(imageView);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
URL url = new URL(params[0]);
// We open the connection
URLConnection conection = url.openConnection();
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
// we convert the inputStream into bitmap
bitmap = BitmapFactory.decodeStream(input);
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
} else
Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show();
}
}
}
I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
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 org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html