i am using asynchronous task for doing some background operation as xml parsing on do in back ground, it works well , but on changing the origination of android device it causes force close , i Google on it , but don't any accordingly or can say unable to explore my self , please any one have idea about this share to me..i will be thankful of u ..
#Override
protected void **onPreExecute()** {
if(refreshFlage)
{
Log.i("refreshFlage","refreshFlage");
dialog = new ProgressDialog(ReplyForm.replyform);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
else
{
dialog = new ProgressDialog(QuestionScreen.questionscreen);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
#Override
protected void **onPostExecute**(final Boolean success) {
dialog.cancel();
try {
java.lang.System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}else {
try{
}
}
catch (NullPointerException e) {
// TODO: handle exception
}
}
}
#Override
protected Boolean **doInBackground**(final String... args) {
getQuestionsMethod();
return null;
}
private void getQuestionsMethod() {
// TODO Auto-generated method stub
HttpResponse response = null;
InputStream is = null;
JSONObject jsonObj = new JSONObject(result);
JSONObject jobj = jsonObj.getJSONObject("question");
group_subject = jobj.getString(TAG_SUBJECT);
question_id = jobj.getString(TAG_QUESTIONID);
author_name = jobj.getString(TAG_AUTHORNAME);
lastpost_date = jobj.getString(TAG_LASTPOSTDATE);
replies = jobj.getString(TAG_REPLIES);
newPost = jobj.getString(TAG_NEWPOST);
userCanReply = jobj.getString(TAG_USERCANREPLY);
poll = jobj.getString(TAG_POLL);
HashMap<String, Object> groupdetailData = new HashMap<String, Object>();
groupdetailData.put(TAG_SUBJECT, group_subject);
groupdetailData.put(TAG_QUESTIONID, question_id);
groupdetailData.put(TAG_AUTHORNAME, author_name);
groupdetailData.put(TAG_LASTPOSTDATE, lastpost_date);
groupdetailData.put(TAG_REPLIES, replies);
groupdetailData.put(TAG_POLL, poll);
groupdetailData.put(TAG_NEWPOST, newPost);
groupdetailData.put(TAG_USERCANREPLY, userCanReply);
int arrayCount = questiondetailarraylist.size();
if (arrayCount > 0) {
questiondetailarraylist.clear();
}
if (poll.equalsIgnoreCase("true")) {
pollmulti = jobj.getString(TAG_POLLMULTI);
pollsubject = jobj.getString(TAG_POLLSUBJECT);
Pollid = jobj.getString(TAG_POLLID);
groupdetailData.put(TAG_POLLMULTI, pollmulti);
groupdetailData.put(TAG_POLLSUBJECT, pollsubject);
groupdetailData.put(TAG_POLLID, Pollid);
//mDbHelper.insertPollfield(questionid, pollmulti, pollsubject, Pollid);
groupdetailData.put("PollTrueData", pollTrueVector);
//System.out.println("after poll method..");
}
//System.out.println(groupdetailData.size());
questiondetailarraylist.add(groupdetailData);
//System.out.println("11111111111111111");
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
answersHashMap.put("vectorArray", vectorArray);
answersHashMap.put("lastUpdateValue", lastUpdateValue);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
User showDialog(id) function for creating dialog, specially when screen orientation changes. More detail is here
On orientation change the activity is destroyed and recreated.
You'll need to handle this by adding the attribute: android:configChanges="orientation" in the AndroidManifest file to your current activity.
Related
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
I am using AsyncTask to call the web service and render the data I got from web service.
this is working fine but sometimes Progress Dialog doesn't get dismissed and not able to see the reason for this in log also.
Example::
I have a web service which is getting called to get the list view data with indexing(for 1 it will return first 5 data and for 2 it will return second 5 data and so on)
once I click page 1 button it returns data and render the same and when I click the page 2 button it starts loading and doesn't dismiss. neither the data is rendered nor the progress dialog is dismissed.
now i closed the app and relaunched again and this time both the situation worked very well.
Any help would be appreciated
thanks in advance
Code for Asynctask :
public class getList extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
String text = null;
JSONObject json;
HttpClient httpclient = new DefaultHttpClient();
//Configuration.empcode.trim()
HttpGet httppost = new HttpGet(ListURL+UserCode+"/"+indexNo);
try {
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if (response != null) {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
// String result = EntityUtils.toString((HttpEntity)
// response);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return text;
}
#Override
protected void onPostExecute(String result)
{
pDialog.dismiss();
if(result!=null)
{
try
{
JSONObject resultObject = new JSONObject(result);
JSONArray resultArray = resultObject.getJSONArray("Table");
for(int i =0;i<resultArray.length();i++)
{
JSONObject resultObjects = resultArray.getJSONObject(i);
Code = resultObjects.getString("Code");
Title = resultObjects.getString("Title");
status= resultObjects.getString("status");
date= resultObjects.getString("date");
TitleList.add(Title);
CodeList.add(Code);
statusList.add(status);
dateList.add(date);
int count = db.getInProgressCount(CourseCode);
if(count==0)
{
db.addInProgress(new InProgressTable(Code,Title,status,date));
}
else
{
db.updateInProgress(new InProgressTable(Code,Title,status,date));
}
}
adapter = new CustomInProgressList(getActivity(),TitleList,CodeList,statusList,dateList);
//adapter.setCustomButtonListner(Catalog_Activity.this);
list.setAdapter(adapter);
scrollMyListViewToBottom(resultArray.length());
int count = db.getAllInProgressCount();
if (adapter.getCount()<1 && count<1){
list.setVisibility(View.GONE);
noRes.setVisibility(View.VISIBLE);
}else {
list.setVisibility(View.VISIBLE);
noRes.setVisibility(View.GONE);
}
if (resultArray.length()<5);
loadMore.setVisibility(View.GONE);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Alert");
builder.setMessage("Data is not available, Please try again later");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
I have used multiple Asynctask in my application.
Is that a Problem??
ok here is your problem -
pDialog as I understand is declared in activity. Lets see the situation with 2 requests.
when you started first one, and immediately start another - your pDialog is now new dialog (it points to another dialog) and first one exists without point to it, and it's not closed! this is why you have not closed dialog.
this will be caused in situation when:
1) first request started;
2) second request started before first request ended;
you must handle one dialog in all your requests or close dialog before it's reinitialisation.
I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}
I am trying to create an Android library which provides AsyncTask operations. I created my AsyncTask as below. However, I don't know how to access library's resources. The context field is set by the activity who uses that library. I used to access the resources by calling getActivity().getResources(). But this AsyncTask's context comes from the project that uses it and I don't know how to access the library's resources. How can I achieve that?
public class CheckBalanceAsyncTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
String json;
JSONObject jsonObject,jsonObjResult;
JSONArray jsonArray;
String message,balance;
ProgressDialog progress;
public CheckBalanceAsyncTask (Context context){
mContext = context;
//progress = new ProgressDialog(mContext);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// progress.setCancelable(false);
// progress.setMessage("please wait");//getString(R.string.pleasewait));
// progress.setTitle("waiting");//getString(R.string.loading));
// progress.setIcon(R.drawable.ic);
// progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// progress.setProgress(0);
// progress.setMax(100);
// progress.show();
}
#Override
protected Void doInBackground(Void... params) {
String aliasNo = "";
PackageInfo pinfo = null;
try {
pinfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String versionName = pinfo.versionName;
String cardServiceUrl = "blabla";
Log.e("LOGGGGG", cardServiceUrl);
try {
json = JSONParser.getJSONFromUrl(cardServiceUrl);
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser",
"Error creating json object" + e.toString());
}
jsonArray = jsonObject.getJSONArray("cardlist");
jsonObjResult = jsonObject.getJSONObject("result");
message = jsonObjResult.get("message").toString();
Log.e("MESSAGE", "" + message);
JSONObject row = jsonArray.getJSONObject(0);
balance = row.optString("balance");
}
catch (JSONException e) {
Log.e("json", "doInBackground2");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//progress.dismiss();
try {
if (jsonObjResult.get("message").toString()
.equalsIgnoreCase("ok")) {
Toast.makeText(mContext, balance+" TL", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ressources are automatically merged with the main application then, no need to do something specific to access string, drawable, layout, etc...
getActivity().getResources() will work fine.
I have an Async task class which gets the name of a web method and run it and I have to wait for the result of that web method, so I used task.execute.get() method which is freezing my UI. the problem is that I want to show a loading dialog when task is executing but when I'm trying to call this method 10 times for 10 web methods, the UI freezes and after executing 10 web methods, loading dialog appears for 1 second.
What can I do to show loading without moving all of my codes into doInBackground? I want to have a class which gets web method info and returns the result. this is my class code:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
And this is the way I'm calling web methods using this class:
public void doSync(String method){
xLog.position();
AsyncCallWs t;
ArrayList<ServiceParam> serviceParams = new ArrayList<ServiceParam>();
String result="";
Settings settings = new Settings(activity);
PublicVariable.pGuid = Login(settings.getValue("Username"), settings.getValue("Password"));
xLog.info("pGuid in doSync is:" + PublicVariable.pGuid);
serviceParams.add(new ServiceParam("pGuid", PublicVariable.pGuid, String.class));
if (method=="all" || method=="person"){
try {
t = new AsyncCallWs(activity,"GetPersonInfo",serviceParams);
result = t.execute().get();
xLog.info("Sync Person=>"+ result);
String fields[] = result.split(PublicVariable.FIELD_SPLITTER);
Person person = new Person(activity,fields);
person.empty();
person.insert();
settings.update("PersonId",String.valueOf(person.getId()));
PublicVariable.personId = person.getId();
xLog.info("Person inserted...");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
if (method=="all" || method=="personImage"){
try {
t = new AsyncCallWs(activity,"GetPersonImage",serviceParams);
result = t.execute().get();
if (!result.equals("Nothing")){
settings.update("picture", result);
xLog.info("Picture updatted...");
}
else
xLog.error("NO PERSON IMAGE FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="lawyers"){
try {
t = new AsyncCallWs(activity,"GetLawyers",serviceParams);
result = t.execute().get();
xLog.info("Sync Lawyer=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Lawyer lawyer= new Lawyer(activity);
lawyer.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
lawyer = new Lawyer(activity, fields);
lawyer.insert();
}
xLog.info("Lawyers inserted...");
}
else
xLog.error("NO LAWYER FOUND!");
}catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="news"){
try {
t = new AsyncCallWs(activity,"GetNews",serviceParams);
result = t.execute().get();
String fields[];
Log.d("Ehsan","Sync News=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
News news = new News(activity);
news.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
news= new News(activity,fields);
news.insert();
}
xLog.info("News inserted...");
}
else
xLog.error("NO NEWS FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="messages"){
try {
t = new AsyncCallWs(activity,"GetMessagesInbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Inbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Inbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
try {
t = new AsyncCallWs(activity,"GetMessagesOutbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Outbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Outbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="requests"){
try {
t = new AsyncCallWs(activity,"GetAllRequests",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync share buy sell requests=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Share share = new Share(activity);
share.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
share= new Share(activity,fields);
share.insert();
}
xLog.info("Shares inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="financials"){
try {
t = new AsyncCallWs(activity,"GetFinancials",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync Financials=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Financial financial = new Financial(activity);
financial.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
financial= new Financial(activity,fields);
financial.insert();
}
xLog.info("Financials inserted...");
}
else{
Log.e("Ehsan", "NOT FINANCIALS FOUND!");
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
Here
result = t.execute().get(); //<<< calling get method
as in doc AsyncTask.get() :
Waits if necessary for the computation to complete, and then retrieves
its result.
so to avoid freezing of Main UI Thread during execution of doInBackground start AsyncTask without calling get method as|:
t.execute();
I want to have a class which gets web method info and returns the
result
For this you should implement callback with AsyncTask which report to Activity. see following examples :
android asynctask sending callbacks to ui
How to implement callback with AsyncTask