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
Related
I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}
There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again
I want to update my listview during every new item add to my arraylist during progress dialog showing this is my code
public class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
// do tracks loading process here, don't update UI directly here
// because there is different mechanism for it
//FlowableBookViewer.webview.loadUrl("javascript:(function(){var txt = window.getSelection();window.name= txt;window.cpjs.sendToAndroid(window.name);})()");
for (int i = 0; i < Globals.currenHtmlList.size(); i++) {
try {
String pageText = FunctionsClass
.readTextFromHtml(Globals.currenHtmlList.get(i));
if (pageText.toLowerCase().contains(
Globals.SelectedText.toLowerCase())) {
String pagename = new File(
Globals.currenHtmlList.get(i)).getName();
SearchItem sitem = new SearchItem();
sitem.setTargetList(Globals.currenHtmlList.get(i));
sitem.setPageNumber(i);
if (pagename.endsWith("html")) {
pagename = pagename.substring(0,
pagename.length() - 5);
} else if (pagename.endsWith("htm")) {
pagename = pagename.substring(0,
pagename.length() - 4);
} else if (pagename.endsWith("xhtml")) {
pagename = pagename.substring(0,
pagename.length() - 6);
}
sitem.setTitleList("Page " + pagename);
founded.add(sitem);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(SearchList.this, R.layout.itemview,
founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
}
in this code the listview items appears after the complete of the for loop which add all the items of sitem object to founded list i want to update listview at every item added to founded .
many thanks
1) Create the adapter before you call the AsyncTask
Move this to your activity/fragment onCreate method:
m_adapter = new OrderAdapter(SearchList.this, R.layout.itemview,
founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
2) After you add an item in your ArrayList call the onProgressUpdate from the AsyncTask
In your doInBackground method add:
founded.add(sitem);
publishProgress();
3) In the onProgressUpdate method call the notifyDatasetChanged method from your adapter
#Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate(v);
m_adapter.notifyDataSetChanged();
}
You can read more about notifyDataSetChanged here.
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.
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 am developing an app based off fragments. A lot of the content of these fragments is collected from a database utilizing an AsyncTask. As such I'm trying to externalize the 'getting data' class so it can be reused. My fragment is as follows:
public class LocalFragment extends SherlockListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.execute();
}
}
My LoadDataFromURL class is as follows:
class LoadDataFromURL extends AsyncTask<String, String, String>{
String our_url;
ListActivity our_context;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray results = null;
List<PubListDetails> pubs = new ArrayList<PubListDetails>();
Handler mHandler;
public void setContext(ListActivity context){
our_context = context;
}
public void setURL(String url){
our_url = url;
}
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler = new Handler();
pDialog = new ProgressDialog(our_context);
pDialog.setMessage("Loading pubs please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(our_url, "GET", params);
Log.d("All Products: ", json.toString());
try {
int success = json.length();
if (success != 0){
results = json;
pubs.clear();
for (int i = 0; i <results.length(); i++){
JSONObject c = results.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String town = c.getString("town");
String county = c.getString("county");
//HashMap<String, String> map = new HashMap<String, String>();
pubs.add(new PubListDetails(id,name,town,county));
//map.put(TAG_PID, id);
//map.put(TAG_NAME, name);
//productsList.add(map);
}
}else{
Intent i = new Intent(our_context,MainMenu.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
our_context.startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
our_context.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
ListAdapter adapter = new PubListAdapter(our_context, pubs);
our_context.setListAdapter(adapter);
}});
}
}
It is giving me errors on the basis that getSherlockActivity does not pass a ListActivity, which setListAdapter requires.
Independent of this, I am feeling more and more that I have conceptually missed the point and this isn't the ideal way to achieve what I want.
Could someone advise how from a fragment I can call an external AsyncTask which will collect data and then populate a ListView with it?
First, you want to set the data on the SherlockListFragment so your business it's not with the Activity .
Independent of this, I am feeling more and more that I have
conceptually missed the point and this isn't the ideal way to achieve
what I want.
Could someone advise how from a fragment I can call an external
AsyncTask which will collect data and then populate a list view with
it..?
Simply implement a callback interface.
public interface OnLoadDataListener {
public onLoadComplete(List<PubListDetails> data);
}
Let your fragment class implement this interface:
public class LocalFragment extends SherlockListFragment implements OnLoadDataListener {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.setListener(this); // you could unite the setContext() method in the listener registration
url_data.execute();
}
#Override
public void onLoadComplete(List<PubListDetails> data) {
ListAdapter adapter = new PubListAdapter(getSherlockActivity(), pubs);
our_context.setListAdapter(adapter);
}
}
And in your AsyncTask:
private OnLoadDataListener mListener
public void setListener(OnLoadDataListener listener){
mListener = listener;
}
and in the onPostExecute you send the data to the listener:
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
if (mListener != null) {
mListener.onLoadComplete(pubs);
}
}