How to Reload a Page while clicked on Button? - android

In my Application I want to retrieve a data from the database. But the problem I am facing is that, the data is fetched from database but it is not displaying at a time when I reopen the page at that time the data is displaying. I want to reload a page when I click on Button.
Here the code is as follow :-
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new InTimeInsert().execute();
}
});
private class InTimeInsert extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_intime,"GET", params);
//ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
time_fetch.add(jsonobject.getString("at_itime"));
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+delivery_fetch);
}
}
private class AllAtendence extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_allatendence,"GET", params);
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
delivery_fetch =jsonobject.getString("at_date");
lunch=jsonobject.getString("at_litime");
rejoin=jsonobject.getString("at_lotime");
out=jsonobject.getString("at_otime");
Log.d("at_line",json.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+delivery_fetch);
rejoina.setText(""+lunch);
luncha.setText(""+rejoin);
outa.setText(""+out);
if(ina.getText().toString().equals(""))
{
Btngetdata.setVisibility(View.VISIBLE);
inti.setVisibility(View.GONE);
}
else
{
Btngetdata.setVisibility(View.GONE);
}
if(luncha.getText().toString().equals(""))
{
ltime.setVisibility(View.VISIBLE);
luncht.setVisibility(View.GONE);
}
else
{
ltime.setVisibility(View.GONE);
}
if(rejoina.getText().toString().equals(""))
{
rtime.setVisibility(View.VISIBLE);
rejoint.setVisibility(View.GONE);
}
else
{
rtime.setVisibility(View.GONE);
}
if(outa.getText().toString().equals(""))
{
otime.setVisibility(View.VISIBLE);
outt.setVisibility(View.GONE);
}
else
{
otime.setVisibility(View.GONE);
}
}
}

If you fetch only one data than you can use this to solve your problem..
And use log to see if there is any err on fetching data... on catch block..Good luck.
private class InTimeInsert extends AsyncTask<Void, Void, Void> {
String fetched_data = "";
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_intime,"GET", params);
//ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
this.fetched_data = jsonobject.getString("at_itime");
}
} catch (Exception e) {
Log.d("fetch err", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+this.fetched_data);
}
}

//put your code in onResume methods
#Override protected void onResume() {
super.onResume();
// call here
new InTimeInsert().execute();
}

Add .get();, while calling AsyncTask.
Like:
new InTimeInsert().execute().get();
It waits for the result of AsyncTask.
By doing this, will execute the AsyncTask first and then continues with the control flow.

Related

Can't solve notifyDataSetChanged error in view Pager?

I have a View Pager in my App. The View pager gets the Imagepath from the JSON & shows in a ImageView. The View pager works for the first time. But when the values are changed, it returns a error.
But I have notified the PagerAdapter about the notifyDataSetChanged.
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 1, found: 0 Pager id: com.hello.hello:id/pager Pager class: class com.hello.hello.utils.ImageViewTouchViewPager Problematic adapter: class com.hello.hello.utils.ZoomAdapter
ASYNCTASK 1
public class FetchPromo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList = new ArrayList<String>();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Neighbouring store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.101.126.31/mobileapp/gps/api.php?rquest=get_promotions&latitude=" + userLocation.getLatitude() + "&longitude=" + userLocation.getLongitude();
Log.d("Path", url);
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
store_name = jsonObject.getString("store_name");
JSONArray promo_path = jsonObject.getJSONArray("image_path");
Log.d("Path", store_name);
for (int i = 0; i < promo_path.length(); i++) {
String path = promo_path.getString(i);
promoList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
store.setText(store_name);
if (promoList.isEmpty()) {
promoList.add(placeholder);
}
mZoomAdapter = new ZoomAdapter(getActivity(), promoList);
mViewPager.setAdapter(mZoomAdapter);
mZoomAdapter.notifyDataSetChanged();
new FetchStore().execute();
progress.dismiss();
}
}
AYNCTASK 2 (where the data has to be loaded again)
public class FetchPromoByID extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList.clear();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Choosen store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.121.116.31/mobileapp/gps/api.php?rquest=get_promotions_by_store_id&store_id=" + Choosen_id;
Log.d("FetchPromoByID", url);
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray promo_path = jsonObject.getJSONArray("image_path");
store_name = jsonObject.getString("store_name");
Log.d("Path", store_name);
for (int i = 0; i < promo_path.length(); i++) {
String path = promo_path.getString(i);
promoList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mZoomAdapter = new ZoomAdapter(getActivity(), promoList);
mViewPager.setAdapter(mZoomAdapter);
mZoomAdapter.notifyDataSetChanged();
new FetchStore().execute();
progress.dismiss();
}
}
ADAPTER
public class ZoomAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> IMAGES = new ArrayList<>();
public ZoomAdapter(Context context, ArrayList<String> IMAGES) {
this.IMAGES = IMAGES;
this.context = context;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
String url = IMAGES.get(position);
PhotoView photoView = new PhotoView(container.getContext());
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
Picasso.with(context)
.load(url)
.fit()
.into(photoView);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
FetchStore
public class FetchStore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
storeList = new ArrayList<String>();
storeID = new ArrayList<String>();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.101.116.31/mobileapp/gps/api.php?rquest=get_store";
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray storearray = jsonObject.getJSONArray("stores");
for (int i = 0; i < storearray.length(); i++) {
JSONObject storeobj = storearray.getJSONObject(i);
String store = storeobj.getString("name");
String ID = storeobj.getString("id");
storeList.add(store);
storeID.add(ID);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
choose.setVisibility(View.VISIBLE);
}
}
I have found many similar Questions like this. But none of the solution worked for me. Please guide me.
Thanks in Advance
I think your error is here (Async Task #2)
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList.clear();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Choosen store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
You make promoList.clear() (set the count to 0),which used in ZoomAdapter instance without notifying.
So notify adapter there or make a temporary ArrayList and clear / addAll in onPostExecute

Hashmap size is not constant

I want to retrieve values from a Hash map. When i tried to display the size of a Hashmap in a TextView the size changes in my screen. Any ideas why?
Is there any other way instead of using Hashmap to store the JSONArray so it is more easy to retrieve values?
public void updateJSONdata() {
cafebartablesList = new ArrayList<HashMap<String, Integer>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
cafebartables = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < cafebartables.length(); i++) {
LoadMap ld = new LoadMap();
ld.execute();
JSONObject c =cafebartables.getJSONObject(i);
int tableId = c.getInt(TAG_TABLE_ID);
int tableMarginLeft = c.getInt(TAG_MARGIN_LEFT);
int tableMarginTop = c.getInt(TAG_MARGIN_TOP);
int isFree = c.getInt(TAG_ISFREE);
map = new HashMap<String, Integer>();
map.put(TAG_TABLE_ID, tableId);
map.put(TAG_MARGIN_LEFT, tableMarginLeft);
map.put(TAG_MARGIN_TOP, tableMarginTop);
map.put(TAG_ISFREE, isFree);
cafebartablesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void printMap() {
mapcounter ++;
length_txt =(TextView)findViewById(R.id.length_txt);
length_txt.setText("the size is " +cafebartablesList.size());
}
public class LoadMap extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
printMap();
}
}
You're method is executing an asynctask that's recursively calling itself, which is probably causing some weird behavior.
Try something like this instead. have your print method call your asynctask. Your asynctask calls updateJSONdata, which iterates over the json object and constructs your map. At the end of your asynctask, update your textview with the size of your map.
public void updateJSONdata() {
cafebartablesList = new ArrayList<HashMap<String, Integer>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
cafebartables = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < cafebartables.length(); i++) {
JSONObject c =cafebartables.getJSONObject(i);
int tableId = c.getInt(TAG_TABLE_ID);
int tableMarginLeft = c.getInt(TAG_MARGIN_LEFT);
int tableMarginTop = c.getInt(TAG_MARGIN_TOP);
int isFree = c.getInt(TAG_ISFREE);
map = new HashMap<String, Integer>();
map.put(TAG_TABLE_ID, tableId);
map.put(TAG_MARGIN_LEFT, tableMarginLeft);
map.put(TAG_MARGIN_TOP, tableMarginTop);
map.put(TAG_ISFREE, isFree);
cafebartablesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void printMap() {
LoadMap ld = new LoadMap();
ld.execute();
}
public class LoadMap extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
length_txt =(TextView)findViewById(R.id.length_txt);
length_txt.setText("the size is " +cafebartablesList.size());
}
}
}
Otherwise, you could use something like Gson, create a POJO for your cafebartablesList and call
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyPojo.class, new MyDeserializer())
.build();
MyPojo mp = gson.fromJson(json, MyPojo.class);

Multiple Async Tasks one after another Android

I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.

preference activity from dynamic array

getting data from webservices but values not getting out of async class,
public class Settings extends PreferenceActivity{
ListPreference lst1;
public static String[] batcharr;
public static String[] streamarr;
public Settings(){
// TPGetListone getlist = new TPGetListone();
// getlist.execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings);
lst1 = (ListPreference) findPreference("prefStream");
TPGetListone getlist = new TPGetListone();
getlist.execute();
lst1.setEntries(batcharr);
lst1.setEntryValues(batcharr);
}
public class TPGetListone extends AsyncTask<String, Void, Void> {
String datax = "";
JSONArray array;
List<String> lstbatch;
List<String> lststream;
private String LogStr = "Panchratna";
#Override
protected Void doInBackground(String... params) {
DataHelper gd = new DataHelper("http://xxxx.com/EventGetter","http://xxxx.com/EventGetter.asmx?wsdl","http://xxxx.com/EventGetter/GetCourseList","GetCourseList");
datax = gd.GetData("query","SELECT batch, stream FROM batch");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.i(LogStr, "onPostExecuteCATALOG");
try {
array = new JSONArray(datax);
} catch (JSONException e) {
e.printStackTrace();
}
lstbatch = new ArrayList<String>();
lststream = new ArrayList<String>();
for(int i = 0; i < array.length(); i++){
try {
lstbatch.add(array.getJSONObject(i).getString("batch"));
lststream.add(array.getJSONObject(i).getString("stream"));
} catch (JSONException e) {
e.printStackTrace();
}
}
batcharr = new String[lstbatch.size()];
streamarr = new String[lststream.size()];
for (int i=0;i<lststream.size();i++){
lststream.toArray(batcharr);
lstbatch.toArray(streamarr);
}
}
#Override
protected void onCancelled(Void aVoid) {
super.onCancelled(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
i know this is not a proper way,
i m using webservices to fetch json values and convert it to list<>
by debugging, values do come in List which is lstbatch and lststream,
and array batcharr and streamarr ,
but when the task executes , in on create method , batcharr and streamarr is showing error,
same method worked last time on an Activity
Please help ,
Thank You
Move this code above the Async and it will be accessible
List<String> lstbatch;
List<String> lststream;
public class TPGetListone extends AsyncTask<String, Void, Void> {
String datax = "";
JSONArray array;
//--> Remove to Up -->List<String> lstbatch;
//--> Remove to Up -->List<String> lststream;
private String LogStr = "Panchratna";
EDIT
for (int i=0;i<lststream.size();i++){
batcharr[i]=lststream.get(i);
streamarr[i]=lstbatch.get(i);
}
put this code
lst1.setEntries(batcharr);
lst1.setEntryValues(batcharr);
in
PostExecute method
protected void onPostExecute(Void aVoid) {
Log.i(LogStr, "onPostExecuteCATALOG");
try {
array = new JSONArray(datax);
} catch (JSONException e) {
e.printStackTrace();
}
lstbatch = new ArrayList<String>();
lststream = new ArrayList<String>();
for(int i = 0; i < array.length(); i++){
try {
lstbatch.add(array.getJSONObject(i).getString("batch"));
lststream.add(array.getJSONObject(i).getString("stream"));
} catch (JSONException e) {
e.printStackTrace();
}
}
batcharr = new String[lstbatch.size()];
streamarr = new String[lststream.size()];
for (int i=0;i<lststream.size();i++){
lststream.toArray(batcharr);
lstbatch.toArray(streamarr);
}
===> lst1.setEntries(batcharr);
===> lst1.setEntryValues(batcharr);
}

Toast in Asyntask is not showed properly

Toast is showed around of 2 times, and Json is returning fine 6 objects.
Idk if its problem of RunOnUiThread (I know that is not good for use in asyntask) or otherthing.
what other way can I use for my variable "mensaje" every time that for put a string in that I can show a Toat, maybe in OnPostExecute.
class asyncMensaje extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String user = params[0];
ArrayList<NameValuePair> envioDato = new ArrayList<NameValuePair>();
envioDato.add(new BasicNameValuePair("rut", user));
JSONArray jdata2 = post.getserverdata(envioDato, URL_connectFechas);
if (jdata2 != null && jdata2.length() > 0) {
JSONObject json_data; // creamos un objeto JSON
for (int i = 0; i < jdata2.length(); i++) {
try {
json_data = jdata2.getJSONObject(i);
mensaje = json_data.getString("mensaje");
Log.e("Info: ", "" + mensaje);
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
protected void onPostExecute(String result) {
}
}
The ideal solution in your case is to use onProgressUpdate together with sequencing of Toasts. Refer to this answer for doing the latter.
class asyncMensaje extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
//....
for (int i = 0; i < jdata2.length(); i++) {
//..
publishProgress(mensaje);
}
}
#Override
protected void onProgressUpdate(String... progress) {
//code for showing Toast
}
}
Use onPostExecute method for processing data after getting from webservice in doInBackground instead of using runOnUiThread in doInBackground which run on different Thread. do it as:
#Override
protected String doInBackground(String... params) {
String user = params[0];
ArrayList<NameValuePair> envioDato = new ArrayList<NameValuePair>();
envioDato.add(new BasicNameValuePair("rut", user));
JSONArray jdata2 = post.getserverdata(envioDato, URL_connectFechas);
return jdata2.toString();
}
#Override
protected void onPostExecute(String result) {
JSONArray jdata2=new JSONArray(result);
// parse JSONArray here and show Toast...
}

Categories

Resources