I am using Progress Bar that only shows up at the time of loading data using Volley but my progress bar freezes till the data loads. Please help. Below is the code that is working fine except the progress bar freezes.
private class GetValue extends AsyncTask<String, String, String> {
ProgressDialog progressDialog=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Loading Data...", "Please Wait");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
assignValues(mnyr ,mnyr1);
return null;
}
}
private void assignValues(String s1, String s2) {
// TODO Auto-generated method stub
//C.progressStart(context, "Loading Data...", "Please Wait");
final String s = s1;
final List<List<String>> values = new ArrayList<List<String>>();
datas = new ArrayList<CustomData>();
RequestQueue queue = Volley.newRequestQueue(this);
String val = s1 + "/" + s2;
final StringRequest request = new StringRequest(Method.GET, C.EVENTS + val,
new Listener<String>() {
#Override
public void onResponse(String arg0) {
// TODO Auto-generated method stub
JsonParser parent = new JsonParser(arg0);
if(parent.getValue("data") == null){
int length = parent.getArrLength(arg0);
ProgressDialog progressDialog=null; // inside asynTask method
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(uractivity.this, "Wait", "Downloading...");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
Related
I am doing socket programming and getting JSON response. Everything is working perfectly but the only thing that is getting me in trouble is that I start another activity before getting response but I want to get all response and after that start another activity.
Here is my code.
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
In my above code I am sending JSON data to server and getting JSON object in response. But before getting the response I am being sent to another activity. So I first want response and then start activity. Help me with some pseudo code.
Thanks
Create an AsyncTask class
public class GetJSONResult extends AsyncTask<String, Void, Void>
{
ProgressDialog pd ;
private Context _context;
public GetJSONResult(Context c)
{
_context = c;
}
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(_context);
pd.setTitle("Getting JSON details");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
jsonobject1.put("username", params[0]); // params[0] is the value passed i.e edittext value
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4")
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
}
catch (Exception e)
{
if (pd.isShowing())
pd.dismiss();
}
return null;
}
protected void onPostExecute(Void v)
{
super.onPostExecute(v);
try
{
if (pd.isShowing())
pd.dismiss();
}
catch(Exception e)
{
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
}
Form your MainActivity call the AsyncTask like this
public MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// First get the reference to EditText using findViewById, then
String s = edt.getText().toString();
// Call the AsyncTask
new GetJSONResult(MainActivity.this).execute(s); // pass the edittext value to doInBackGround method.
}
}
private class getResponse extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
#Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
and for executing new getResponse().execute();
I want to download stock from web using Web Service. Created Sync to delete current stock
new ResetStock().execute();
Here is ResetStock Async:
private class ResetStock extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd=new ProgressDialog(FrmMainMenu.this);
pd.setMessage("Please Wait. We are Downloading the Catalogue...");
pd.show();
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatabaseHandlerStock dbc=new DatabaseHandlerStock(FrmMainMenu.this);
dbc.deleteallstock();
dbc.close();
new AsyncStock(FrmMainMenu.this).execute();
return null;
}
}
Now I Called Another Async to download and xml and insert into my database
here is Asyncstock
List<Stock> mystocks = null;
Context mcontext;
int x=0;
public AsyncStock(Context context) {
super();
this.mcontext = context;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try{
URLConnection conn = new URL("http://192.168.1.2/mob2server.asmx/GetStock").openConnection();
mystocks = SAXXMLParser.parse(conn.getInputStream());
DatabaseHandlerStock dbc;
dbc=new DatabaseHandlerStock(mcontext);
String category, make, model, productcode, productname, smallimages, largeimages, description, mrp, unit, pkg;
for(Stock in :mystocks)
{
x++;
category=in.getCategory();
make=in.getMake();
model=in.getModel();
productcode=in.getProductcode();
productname=in.getProductname();
smallimages=in.getSmallimages();
largeimages=in.getLargeimages();
description=in.getDescription();
mrp=in.getMrp();
unit=in.getUnit();
pkg=in.getPkg();
dbc.addContact(new Catalogue(category.replace("$","&"), make.replace("$","&"), model.replace("$","&"), productcode, productname.replace("$","&"), smallimages, largeimages, description.replace("$","&"), mrp, unit, pkg));
}
dbc.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(mcontext, "Total " + x + " Models Imported!", Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
My First dialog is cancel before the stock is inserted into stock.
I want my dialog to be there until stock is inserted into my database.
Create another class and pack your second asynctask stuff in it. You can than call this new class in your first asynctask. Also use the progress update to see what is going on. In this way you will have only one progress bar but will keep you informed.
There are two Activities. The first Activity is having the list view to see what is being shared and the second activity has an edit text box (to input inorder to share) and a button. On clicking the button, it returns me the string which is the json response and I need to add this in the previous activity.
Now the problem is, when I refresh the first page fully hitting the server it gets the response but this is not what I want. It should not go back to the server. It should simply add in the list view adapter.
I have commented the code in the PostExecute(). I have tried the everyway but it is not reflecting. I am also posting my code for your reference.
public class ShareAsyncTask extends AsyncTask<String, Void, ArrayList<EventsStreamBean>> {
public ProgressDialog pd = new ProgressDialog(EventStreamActivity.this);
String success_share_val;
#Override
protected ArrayList<EventsStreamBean> doInBackground(
String... result) {
// TODO Auto-generated method stub
JSONObject jsonobj = new JSONObject(result[0].toString());
success_share_val = jsonobj.getString(Constants.SUCCESS);
//checks the success value
if(success_share_val.equalsIgnoreCase("1")) {
JSONArray events_stream_share_array = jsonobj.getJSONArray("streamArray");
if(events_stream_share_array.length() > 0) {
for(int i=0; i<events_stream_share_array.length(); i++) {
EventsStreamBean events_stream_bean = new EventsStreamBean();
JSONObject events_stream_object = events_stream_share_array.getJSONObject(i);
events_stream_bean.setStreamId(events_stream_object.getString(Constants.STREAM_ID));
events_stream_bean.setStreamType(events_stream_object.getString(Constants.STREAM_TYPE));
events_stream_bean.setUserId(events_stream_object.getString(Constants.USER_ID));
events_stream_bean.setUserName(events_stream_object.getString(Constants.USER_NAME));
events_stream_bean.setUserType(events_stream_object.getString(Constants.USER_TYPE));
events_stream_bean.setUserAvatar(events_stream_object.getString(Constants.USER_AVATAR));
arraylist_events_stream.add(events_stream_bean);
}
}else {
Log.i("Test", "No Events Streams Available");
}
}
}catch(Exception e) {}
return arraylist_events_stream;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.pd.setMessage("Loading....");
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
this.pd.show();
}
#Override
protected void onPostExecute(final ArrayList<EventsStreamBean> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.pd.isShowing()) {
this.pd.dismiss();
}
Toast.makeText(EventStreamActivity.this, "Post shared successfully", Toast.LENGTH_SHORT).show();
new EventsStreamAsyncTask().execute(temp_val);
/*runOnUiThread(new Runnable() {
public void run() {
//EventStream_Customadapter adapter = (EventStream_Customadapter) list_view.getAdapter();
//adapter.clearData();
adapter.updateData(result);
//adapter = new EventStream_Customadapter(EventStreamActivity.this, arraylist_events_stream);
//list_view.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});*/
}
}
Thank you
Could anyone help me on following questions.
1) onPostExecute - Toast.make while in background i am sending HttpRequest.
0nCraeteBunle - execute() ; startNewActivity
showing error. AsycTask# Runtime Exception .
While commenting Http request in background, no error is showed.
here, how can i know that http Request and reply finished , so that i can start my new Activity.
2) how to get HttpParams. Sending from TIBCO BE (As event with properties)
3) What if i am recieving JSONObject, JAVAObject, Integer other than String in onPostExecute. unable to override .
Try this,
protected class GetTask extends AsyncTask<Void, Void, Integer> {
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"Loading", "Please wait");
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
//call ur HttpRequest
httpRequest();
return 0;
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mHandler.sendEmptyMessage(0);
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message Msg) {
if (Flag) {
//Add ur stuff
}else{
}
And then in ur method set Flag value
public void httpRequest() {
// TODO Auto-generated method stub
String URL ="ADD UR URL";
try {
JSONObject ResponseObject = mAPIService.CallAPI(
YourActivity.this, URL);
String status = ResponseObject.getString("status");
Flag = true;
} catch (Exception err) {
Flag = false;
}
}
I want to load datas from a list to gridview with a loading effect using progressbar.Im getting items from a webservice.The problem i face is im unable to dismiss the progress bar even after showing the gridview.I can see the gridview with items but progress bar is still running .What am i doing wrong here.
private void testAsyncTask() {
Log.e("Im in testAsyncTask()", "");
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
progress_Dialog = ProgressDialog.show(a, "", "Loading");
Log.e("Im in onPreExecute", "");
// super.onPreExecute();
}
#Override
protected Integer doInBackground(Object... params) {
MenuService menuService = new MenuServiceImpl();
PartnerMenuServiceResponse partnerMenu = menuService
.getPartnerMenu();
jewellist = partnerMenu.getMenu().getMenuEntries();
Log.e("Im in doInBackground", "");
System.gc();
return 0;
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
// super.onPostExecute(result);asd
Log.e("Im in onPostExecute", "");
if (progress_Dialog.isShowing()) {
progress_Dialog.dismiss();
}
ShopGridAdapter adapter = new ShopGridAdapter(ShopGridActivity.this, jewellist);
AllJewelgridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//AllJewelgridView.setAdapter(new ShopGridAdapter(
// ShopGridActivity.this, jewellist));
if (AllJewelgridView.getCount() <= 0) {
MyAlertDialog.ShowAlertDialog(ShopGridActivity.this, "",
"No data found.", "OK");
}
progress_Dialog.dismiss();
}
}.execute();
}
#Override
protected void onPreExecute() {
progress_Dialog = new ProgressDialog(context);
progress_Dialog.setMessage("Loading...");
progress_Dialog.show();
}
EDIT :
#Override
protected void onPostExecute(Object result) {
Log.e("Im in onPostExecute", ""); <------ ARE YOU ABLE SEE THIS IN logcat ?
progress_Dialog();
}
It may possible onPostExecute() not called. So to confirm check logcat
You need to put some code in your AsyncTask
ProgressDialog progress=null;
progress=ProgressDialog.show(this,"title","loading..").show();//put this code in onPreExecute()
progress.dismiss();//put this code in onPostExecute()
for more ProgressBar while loading ListView (using AsyncTask)
You can write in onPostExecute method may help you.
if ( progress_Dialog != null) {
progress_Dialog.cancel();
}