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.
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 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();
}
I am trying to implement Dropbox Sync API in my Android Application. I want to do the Syncing manually on Click Events. I have written this code:,br/>
private class BackgroundSyncManager extends AsyncTask<String, String, String>
{
private boolean isSynced = false;
private ProgressDialog pd;
public BackgroundSyncManager(Context ctx)
{
pd = new ProgressDialog(ctx);
pd.setTitle("Downlaoding in Progress...");
pd.setCancelable(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
sync_Button.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pd.setProgress(Integer.parseInt(values[0]));
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
pd.show();
mDbFileSystem.syncNowAndWait();
isSynced = true;
}
catch(Exception e)
{
isSynced = false;
Log.e(TAG, "Error Occured While Syncing !, Error = "+e.toString());
}
return "";
}
}
But, it is throwing me an Error, Here is what my Logcat Says:
12-10 11:34:23.311: E/Main Activity(15464): Error Occured While Syncing !, Error = java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Am i doing the Manual Syncing Wrong, or is there some problem in this implementation ?
Any help is highly appreciated, thanks.
Hi everyone i am facing problem in showing loading box on pressing send button using send_Schedule() function. I have the following code.
#Override
public void onClick(View arg0) {
pdialog.setCancelable(true);
pdialog.setMessage("Loading ....");
pdialog.show();
send_Schedule();
}
In send_Schedule() function i am putting delay of 3 secs like this in the following code. but dialog box always shows up after completion of loop.
send_Schedule(){
for(int i=0;i<100;i++){
Log.d("TAG",""+i)
try {
Thread.sleep(3000);
Log.e("----------------", "-----------------");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pdialog.dismiss();
}
I want to show dialog box while sending data...
Try this..
private class YourTaskLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(YourActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Importing Messages...!");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Write you back ground logic here
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
Invoke like in your Activity
new YourTaskLoader().execute();
Check this more info AsyncTask
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