Asynctask not executing while running but executing in debugging - android

Am executing two AsyncTask in an sequence manner. While debugging its working fine. But while running the app, second AysncTask not executing. Tried with THREAD_POOL_EXECUTOR not helping.below is my code.I don't have any idea about this problem.Below is my complete code.While running headerList.size() tgrowing zero. If the AsyncTask executed correctly, the size will be 2.
public class MainmenuActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
networkCheck(context,rl);
}
private void loadPage(){
// new GetMenu().execute();
GetMenu getMenuTask = new GetMenu();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getMenuTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
getMenuTask.execute();
}
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
Menu menu = navigationView.getMenu();
System.out.println("List Size "+ headerList.size());
for(int i=0;i<headerList.size();i++)
{
String title = headerList.get(i).getMenuName().toString();
GlobalClass.menuId = headerList.get(i).getLangID().toString();
adapter.addFragment(new OneFragment(), title);
menu.add(title);
//viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
}
private void networkCheck(Context context,LinearLayout rl) {
boolean isConnected = NetworkCheck.isNetworkAvailable(context);
if (isConnected) {
if(GlobalClass.languagueSelection.toString().equals("")){
LanguageSelectionDialog languagueDialog =new LanguageSelectionDialog(MainmenuActivity.this);
languagueDialog.show();
}else{
loadPage();
}
} else {
Snackbar snackbar = Snackbar
.make(rl, "No Internet Connection", Snackbar.LENGTH_LONG)
.setDuration(Snackbar.LENGTH_LONG)
.setAction("Retry", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainmenuActivity.this, MainmenuActivity.class);
startActivity(i);
finish();
}
});
}
}
private class GetMenu extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainmenuActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(menuURL);
Log.e(TAG, "Response from MenuURL: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray lanList = jsonObj.getJSONArray("menu");
for (int i = 0; i < lanList.length(); i++) {
JSONObject jsonObject1 = lanList.getJSONObject(i);
String langID = jsonObject1.optString("id");
String menuID = jsonObject1.optString("menu");
headerList.add(new Language(langID,menuID));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainmenuActivity.this, "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainmenuActivity.this,
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
public class LanguageSelectionDialog extends Dialog {
public LanguageSelectionDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.languagueSelection = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.languague_selection_dialog);
getLanguagues = new GetLanguagues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getLanguagues.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
getLanguagues.execute();
} }
private class GetLanguagues extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(languagueURL);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray lanList = jsonObj.getJSONArray("language");
for (int i = 0; i < lanList.length(); i++) {
JSONObject jsonObject1 = lanList.getJSONObject(i);
String id = jsonObject1.optString("id");
String langId = jsonObject1.optString("language");
dashBoardList.add(new LanguagueSelection(id,langId));
lanlist.add(langId);
GlobalClass.langId=id;
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
spnLanguagueSelection.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, lanlist));
getLanguagues.cancel(true);
}
}
}
}
StackTrace while Running:
12-28 07:13:05.294 17448-17468/com.appathon.siva.news E/ContentValues: Response from url: {"language":[{"id":"21","language":"Hindi"},{"id":"20","language":"English"},{"id":"19","language":"Tamil"}]}
12-28 07:13:10.175 17448-17448/com.appathon.siva.news I/Choreographer: Skipped 297 frames! The application may be doing too much work on its main thread.
12-28 07:13:11.616 17448-17448/com.appathon.siva.news I/System.out: List Size 0
12-28 07:13:11.662 17448-17463/com.appathon.siva.news W/EGL_emulation: eglSurfaceAttrib not implemented
12-28 07:13:11.662 17448-17463/com.appathon.siva.news W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3fcd200, error=EGL_SUCCESS
12-28 07:13:11.682 17448-17472/com.appathon.siva.news E/ContentValues: Response from MenuURL: {"menu":[{"id":"14","menu":"Latest News"},{"id":"13","menu":"Top News"}]}
StackTrace while Debugging
12-28 07:27:17.155 17557-17579/com.appathon.siva.news E/ContentValues: Response from url: {"language":[{"id":"21","language":"Hindi"},{"id":"20","language":"English"},{"id":"19","language":"Tamil"}]}
12-28 07:27:17.166 17557-17573/com.appathon.siva.news W/EGL_emulation: eglSurfaceAttrib not implemented
12-28 07:27:17.166 17557-17573/com.appathon.siva.news W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe3873d40, error=EGL_SUCCESS
12-28 07:27:30.429 17557-17583/com.appathon.siva.news E/ContentValues: Response from MenuURL: {"menu":[{"id":"14","menu":"Latest News"},{"id":"13","menu":"Top News"}]}
12-28 07:27:33.836 17557-17557/com.appathon.siva.news I/System.out: List Size 2
List size is printing in different scenarios.

Related

interface between fragment and activity not working

I want pass my String json from fragment to another activity so make interface between fragment and activity but when lunch app get null exception from this line from my fragment :adapterCalljson.MethodCallbackjson(jsonStr);
this is my try so far :
interface class :
public interface AdapterCalljson {
void MethodCallbackjson(String jsonn);
}
fragment :
public class maghalat extends Fragment {
private View myFragmentView;
private RecyclerView recyclerView;
private DataAdapter adapter;
private String TAG = MainActivity.class.getSimpleName();
public ProgressDialog pDialog;
List<jsonContent> listcontent=new ArrayList<>();
public int dog=1;
public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
public int id;
AdapterCalljson adapterCalljson;
public String json;
public String jsonStr;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
adapterCalljson.MethodCallbackjson(json);
asyncRun();
return myFragmentView;
}
public void asyncRun(){
if(isNetworkConnected()) {
new GetContacts().execute();
} else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
jsonContent.content=c.getString("content");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
jsonContent.curpage=dog;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() {
#Override
public void MethodCallbackgo(String data) {
Integer s=null;
try {
s= Integer.valueOf(data);
}catch (NumberFormatException e)
{
}
if (s!=null && s>=1 && s<=id)
{
dog= Integer.parseInt(data);
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else
{
Toast.makeText(getActivity().getApplicationContext(),"صفحه پیدا نشد",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbacknext() {
if (dog<id)
{
dog += 1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else {
Toast.makeText(getActivity().getApplicationContext(),"این آخرین صفحه است",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbackprev() {
if (dog!=1)
{
dog-=1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else{
Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setAdapter(adapter);
json=jsonStr;
}
}
You haven't assigned an object to adapterCalljson. Assuming you're implementing AdapterCalljson in the host activity, assign it from the context onAttach:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
Firstly, your Activity containing the Fragment must implement that interface.
public class MainActivity implements AdapterCalljson {
#Override
void MethodCallbackjson(String jsonn) {
doSomethingWithJson(jsonn);
}
private void doSomethingWithJson(String json) {
}
// onCreate...
}
Next, I would recommend you create the RecyclerView outside the AsyncTask. You don't need to save the myFragmentView variable.
Additionally, you can't call the callback yet. There is no data.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maghalat, container, false);
// recyclerView = rootView.findViewById
// adapter = ...
// recyclerView.setAdadpter...
asyncRun(); // This happens in the background. There is no JSON yet
return rootView;
}
Then, perhaps you should have doInBackground return the JSON string so you don't have to store it as a class variable.
The last argument is the return type.
public class GetContacts extends AsyncTask<Void, Void, String>
So, then it is public String doInBackground(Void params...) {} and public void onPostExecute(String result) {}.
In other words, don't just return null from doInBackground
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
// Parse JSON more...
return jsonStr;
}
And then you should be able to use your callback.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}

Progress dialog dismisses before the view is displayed in the gridview

I start my progress dialog in oncreate method of fragment before is initiate my web request call. In the web request call, if I fetch the response and if its success I call the notifydatasetchanged method to refresh the adapter . But the dialog gets dismissed lot before the view is updated . Please help .
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pd = ProgressDialog.show(getActivity(), "Loading...", "Please Wait...");
getProducts(highPrice, lowPrice, isLowtoHigh);
}
private void getProducts(String highPrice,String lowPrice,String isLowtoHigh) {
// loadingDialog.loading();
APIRequst.getProductsCategory(getActivity().getApplicationContext(), isLowtoHigh, lowPrice, highPrice, new APIRequestListner() {
#Override
public void onSuccess(String response) {
if (response == null || response.isEmpty()) {
Log.e("orderhistory", "success but empty");
} else {
Log.e("products", response);
try {
JSONObject mainObj = new JSONObject(response);
boolean result = mainObj.has("is_success") && mainObj.getBoolean("is_success");
String resultMessage = mainObj.getString("message");
if (resultMessage.equalsIgnoreCase("Success")) {
if (result) {
productItems.clear();
adptProductItems.clear();
JSONArray jsonOrderList = mainObj.has("categories") ? mainObj.getJSONArray("categories") : null;
if (jsonOrderList != null) {
for (int i = 0; i < jsonOrderList.length(); i++) {
JSONObject jsonObj = jsonOrderList.getJSONObject(i);
ProductListItem newItem = (new Gson()).fromJson(jsonObj.toString(), ProductListItem.class);
productItems.add(newItem);
}
adptProductItems.notifyDataSetChanged();
pd.dismiss();
}
}
} else {
if (resultMessage.equalsIgnoreCase("No Value")) {
if (pd.isShowing())
pd.dismiss();
productItems.clear();
adptProductItems.notifyDataSetChanged();
Toast.makeText(getActivity(), "Sorry no prducts to display", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adapter.notifyDataSetChanged();
}
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
});
}
try to move " pd.dismiss();" below onFailure()
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
pd.dismiss();
and
adptProductItems.notifyDataSetChanged();
//pd.dismiss(); remove fromhere
may it will help as I did in my case..

My AsyncTask not getting cancelled android

I am working on a task that calls my AsyncTask , once the async task is executed , I wait for 20 seconds to get the data from server , if it is still loading I am cancelling it (handling timeout)
public void handleServerTimeOut() {
getStore = new GetStore();
getStore.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
boolean result = getStore.cancel(true);
Log.e(TAG, " handleServerTimeOut() reached 20 seconds");
Log.e(TAG, "" + result);
}
}
}, 20000);
}
AsyncTask
class GetStore extends AsyncTask<Void, Void, String> {
String status, message;
JSONArray jsonArray;
String buildingIdGuest, buildingIdUser, finalBuildingID;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isCancelled()) {
return;
} else {
buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
finalBuildingID = buildingIdGuest;
} else {
finalBuildingID = buildingIdUser;
}
error_flag = 0;
gridView.setVisibility(View.VISIBLE);
error_layout.setVisibility(View.INVISIBLE);
img_no_internet.setVisibility(View.INVISIBLE);
img_no_results.setVisibility(View.INVISIBLE);
img_server_error.setVisibility(View.INVISIBLE);
progressDialog.setMessage("Getting nearby stores ...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
if (NetworkCheck.isNetworkAvailable(getActivity())) {
try {
jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);
Log.e(TAG, jsonObj.toString());
status = jsonObj.getString("status");
message = jsonObj.getString("message");
if (status.equalsIgnoreCase("success")) {
jsonArray = jsonObj.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
gridModel = new GridModel();
gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
gridListData.add(gridModel);
}
Log.e(TAG, "****** = " + gridListData.toString());
} else if (status.equalsIgnoreCase("invalid parameters")) {
error_flag = 2;
Log.e(TAG, "invalid parameters");
} else if (status.equalsIgnoreCase("no stores")) {
error_flag = 3;
Log.e(TAG, "No Data");
}
Log.e(TAG, "****** status " + status);
return String.valueOf(jsonObj);
} catch (Exception e) {
error_flag = 1; // Handling server timeout.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
return;
}
});
Log.e(TAG, e.toString());
}
} else {
Log.e(TAG, "Network Error");
error_flag = 1;
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e(TAG, " **** error **** " + error_flag);
if (error_flag == 1) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_internet.setVisibility(View.VISIBLE);
} else if (error_flag == 2) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_server_error.setVisibility(View.VISIBLE);
txtError.setVisibility(View.VISIBLE);
txtError.setText(message);
} else if (error_flag == 3) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_results.setVisibility(View.VISIBLE);
}
gridAdapter = new GridAdapter(getActivity(), gridListData);
gridView.setAdapter(gridAdapter);
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I also wanted to cancel my AsyncTask when the user cancels the ProgressDialog
You are checking isCancelled() only once in your AsyncTask - in the onPreExecute() method. At the time you call cancel() on your task instance, this check has already been evaluated and this is why the async task is still completing and updating the UI.
To deal with the issue, I suggest you include more checks for cancellation, using the isCancelled() method. One obvious place to include such a check is in the onPostExecute() method, right before you update the UI. You could also include a check before making the actual request to the server, after receiving the response, etc.

Can not run multi Asynctask at one time

I'm writting an application which use Android phone like client and connect to java server via TCP Socket.
My problem is: I used a service to send/receiver message to java server with asynctask to keep connection, but when i need to send request and wait for respone from server, i use another asynctask to do this, but the second asynctask can not run.
Here my code
Asynctask in Server (Connect - Keep receiver message)
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
Log.d(TAG1,"connectTask - in asycn task- 3");
//we create a TCPClient object and
mmTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
Log.d(TAG1,"connectTask - in asycn task- 4");
publishProgress(message);
}
});
if (LocalData.isConnectsuccess == false)
{
try {
Log.d(TAG1,"connectTask - in asycn task- 5");
mmTcpClient.run("172.16.10.37", 44444);
Log.d(TAG1,"Services started - in asycn task- 6");
}
catch (Exception e)
{
Log.e(TAG1,""+e);
}
}
return null;
}
#Override
protected void onProgressUpdate(final String... values) {
super.onProgressUpdate(values);
Log.e(TAG1,"Onprogressupdate" + values[0]);
LocalData.strreceiver = values[0];
Intent intt = new Intent(ConnectService.this, Customdialog.class);
intt.putExtra("mess", LocalData.strreceiver);
intt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intt);
}
}
And the second asynctask which use for Login Activity
class ASlogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SigninActivity.this);
pDialog.setMessage("Logging in");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Log.d(Tag2, "pdialog show");
}
/**
* getting All products from url
* */
protected String doInBackground(String... message) {
// Building Parameters
Log.d(Tag2, "Doinbackground");
try {
if (LocalData.isConnectsuccess == true) {
Log.d(Tag2, "Send-1");
JSONObject jslogin = new JSONObject();
try {
jslogin.put("tag","login");
jslogin.put("email", edtEmailSignIn.getText().toString());
jslogin.put("password", edtPasswordSignIn.getText()
.toString());
Log.d(Tag2, "Put Json-2");
} catch (JSONException e) {
Log.e(Tag2, "JSON failed" + e);
}
mTcpClient.sendMessage(jslogin.toString());
Log.d(Tag2, "JsonString: " + jslogin.toString());
}
else {
Log.e(Tag2, "Connect not success" + LocalData.isConnectsuccess);
}
} catch (Exception e) {
Log.e(Tag2, "Fail parse Json" + e);
}
return null;
}
#Override
protected void onProgressUpdate(String... message) {
super.onProgressUpdate(message);
pDialog.dismiss();
OJResponsive strreturn = new OJResponsive();
try{
strreturn = JSonparse.getrespon(LocalData.strreceiver);
}
catch (Exception e)
{
alertmess("Login fail" + e);
Log.e(Tag2,"Json parse failed"+e);
}
if (strreturn.getResult()=="success")
{
Toast.makeText(SigninActivity.this, "Login success", Toast.LENGTH_SHORT).show();
Intent inhctr = new Intent(SigninActivity.this,HomeControlActivity.class);
startActivity(inhctr);
finish();
}
else alertmess("Login fail");
Log.e(Tag2,"Login fail"+e);
}
}
the Second asycntask just run at onPreExecute() and stop at showprocessdialog.
So any help for me ? or any better solutions in this case ?
Thanks you.
Try to use
AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
instead
AsyncTask execution is handled differently in different versions of android.
Have a look a this answer: fetching data in parallel

android AsyncTask - can't execute onPostExecute method

I have wrote an app to run an AsyncTask and part of the code is listed as follow. The problem is when the AsyncTask start by execute the code - "new AddImageTask().execute();" in the thread handler, the task will start and everything seems right. However, eventually the app will stay in "doInBackground" method after all code in "doInBackground" method has been executed. The task can't go to "onPostExecute" method. (i.e. can't dismiss the dialog...) What get wrong?
Thanks for the help......
private Handler handleFetchResult = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
Log.d(TAG, "Start handle fetch result");
try {
JSONArray ja = new JSONArray(fetchResult);
Log.d(TAG, "JSON Array Length = " + ja.length());
JSONObject jo = new JSONObject();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
PhotoURLs.add(PAT_url + jo.getString("filePath"));
Log.d(TAG, PhotoURLs.get(i));
}
} catch (JSONException e) {
Log.d(TAG, "Fetch result error: " + e.getLocalizedMessage());
e.printStackTrace();
}
//TODO: display thumbnail
new AddImageTask().execute();
}//void handleMessage
};//Handler handleFetchResult
class AddImageTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadThumbnailDialog.show(SitePhotoGallery.this, "Fetch thumbnails from server",
"Loading...", true, true);
Log.d("AddImageTask.onPreExecute","onPreExecute");
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
for (String url : PhotoURLs) {
String filename = url.substring(url.lastIndexOf("/") + 1, url.length());
String thumburl = url.substring(0, url.lastIndexOf("/")+1);
imgAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
publishProgress();
}
Log.d("AddImageTask.doInBackground","doInBackground");
return null ;
}
#Override
protected void onProgressUpdate(Void... unused) {
super.onProgressUpdate();
imgAdapter.notifyDataSetChanged();
Log.d("AddImageTask.onProgressUpdate","OnProgressUpdate");
}
protected void onPostExecute(Void... unused) {
super.onPostExecute(null);
loadThumbnailDialog.dismiss();
Log.d("AddImageTask.onPostExecute","onPostExecute");
}
}
I think it's because onPostExecute() should take a Void parameter and not a Void... parameter. (You should also specify #Override as Soxxeh pointed out in his/her comment above.)

Categories

Resources