JSON parser can't run - java

My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}

You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}

Related

Why android ViewPager OnTouchListener not called at all

Why my ViewPager OnTouchListener doesn't fire at all !!
Here is my code below:
I'm using ViewPager to automatically slide photos but when i tap on the ViewPager I need to stop the auto sliding but the problem is that my OnTouchListener doesn't fire at all.
JAVA
man_fragment.java
package com.techzone.yallaassouk;
/**
* Created by Yazan on 4/26/2016.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.techzone.yallaassouk.Adapters.Brands_View_Adapter;
import com.techzone.yallaassouk.Adapters.Categories_View_Adapter;
import com.techzone.yallaassouk.Adapters.ImageSlideAdapter;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.DataItems.Brand;
import com.techzone.yallaassouk.DataItems.Category;
import com.techzone.yallaassouk.Utils.CirclePageIndicator;
import com.techzone.yallaassouk.Utils.PageIndicator;
import com.techzone.yallaassouk.Utils.CheckNetworkConnection;
import com.techzone.yallaassouk.json.GetJSONObject;
import com.techzone.yallaassouk.json.JsonReader;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
public class man_fragment extends Fragment {
public static final String ARG_ITEM_ID = "man_fragment";
private static final long ANIM_VIEWPAGER_DELAY = 5000;
private static final long ANIM_VIEWPAGER_DELAY_USER_VIEW = 10000;
private static final int TabNo = 1;
// UI References
ViewPager BandsViewPager;
PageIndicator mIndicator;
RecyclerView brands_Rec_View;
RecyclerView categories_Rec_View;
//lists
List<Band> bands;
List<Brand> brands;
List<Category> categories;
//tasks
RequestBandsTask bands_task;
RequestBrandsTask brands_task;
RequestCategoriesTask categories_task;
AlertDialog alertDialog;
boolean stopSliding = false;
String message;
//lists adapters
Brands_View_Adapter brands_adapter;
Categories_View_Adapter categories_adapter;
//runnables and handlers
private Runnable animateViewPager;
private Handler handler;
//urls
String brandsurl = "http://yazanallahham-001-site1.ftempurl.com/Brands.svc/json/brands/"+TabNo;
String categoriesurl = "http://yazanallahham-001-site1.ftempurl.com/categories.svc/json/categories/"+TabNo+"/0";
String bandsurl = "http://yazanallahham-001-site1.ftempurl.com/bands.svc/json/bands/0";
//activity
FragmentActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.man_fragment, container, false);
findViewById(rootView);
mIndicator.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
stopSliding = true;
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
// calls when touch release on ViewPager
if (bands != null && bands.size() != 0) {
stopSliding = false;
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY_USER_VIEW);
}
break;
case MotionEvent.ACTION_MOVE:
// calls when ViewPager touch
if (handler != null && stopSliding == false) {
stopSliding = true;
handler.removeCallbacks(animateViewPager);
}
break;
}
return false;
}
});
// sendRequest();
//init brands recyclerview
brands_Rec_View.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
brands_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
categories_fragment nextFrag= new categories_fragment();
Bundle args = new Bundle();
Brand clickedBrand = (Brand)brands.get(position);
args.putInt("BrandId", clickedBrand.getId());
args.putInt("TabId", TabNo);
args.putString("BrandName", clickedBrand.getEnName());
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, categories_fragment.ARG_ITEM_ID)
.addToBackStack(categories_fragment.ARG_ITEM_ID)
.commit();
}
})
);
//init categories recyclerview
GridLayoutManager LLM = new GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false){
#Override
public boolean canScrollVertically(){
return false;
}
};
categories_Rec_View.setLayoutManager(LLM);
categories_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
//Log.d("categories","test click" + position);
Items_fragment nextFrag= new Items_fragment();
Bundle args = new Bundle();
Category clickedCategory = (Category)categories.get(position);
args.putInt("CategoryId", clickedCategory.getId());
args.putString("CategoryName", clickedCategory.getEnName());
args.putInt("BrandId", 0);
args.putInt("TabId", TabNo);
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, Items_fragment.ARG_ITEM_ID)
.addToBackStack(Items_fragment.ARG_ITEM_ID)
.commit();
}
})
);
return rootView;
}
private void findViewById(View view) {
BandsViewPager = (ViewPager) view.findViewById(R.id.man_view_pager);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
brands_Rec_View = (RecyclerView) view.findViewById(R.id.brands_RView);
categories_Rec_View = (RecyclerView) view.findViewById(R.id.categories_RView);
}
public void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
public void run() {
if (!stopSliding) {
if (BandsViewPager.getCurrentItem() == size - 1) {
BandsViewPager.setCurrentItem(0);
} else {
BandsViewPager.setCurrentItem(
BandsViewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
}
};
}
#Override
public void onResume() {
if (bands == null) {
sendRequest();
} else {
BandsViewPager.setAdapter(new ImageSlideAdapter(activity, bands,
man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
//Re-run callback
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
super.onResume();
}
#Override
public void onPause() {
if (bands_task != null)
bands_task.cancel(true);
if (handler != null) {
//Remove callback
handler.removeCallbacks(animateViewPager);
}
super.onPause();
}
private void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
bands_task = new RequestBandsTask(activity);
bands_task.execute(bandsurl);
brands_task = new RequestBrandsTask(activity);
brands_task.execute(brandsurl);
categories_task = new RequestCategoriesTask(activity);
categories_task.execute(categoriesurl);
} else {
message = getResources().getString(R.string.no_internet_connection);
showAlertDialog(message, true);
}
}
public void showAlertDialog(String message, final boolean finish) {
alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (finish)
activity.finish();
}
});
alertDialog.show();
}
private class PageChangeListener implements ViewPager.OnPageChangeListener {
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (bands != null) {
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private class RequestBandsTask extends AsyncTask<String, Void, List<Band>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Band> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
bands = JsonReader.getBands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return bands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Band> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
bands = result;
if (result != null) {
if (bands != null && bands.size() != 0) {
//for brands_adapter
BandsViewPager.setAdapter(new ImageSlideAdapter(
activity, bands, man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY);
} else {
}
} else {
}
}
}
}
}
private class RequestBrandsTask extends AsyncTask<String, Void, List<Brand>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBrandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Brand> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
brands = JsonReader.getBrands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return brands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Brand> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
brands = result;
if (result != null) {
if (brands != null && brands.size() != 0) {
//for brands_adapter
brands_adapter = new Brands_View_Adapter(brands);
brands_Rec_View.setAdapter(brands_adapter);// set adapter on recyclerview
} else {
}
} else {
}
}
}
}
}
private class RequestCategoriesTask extends AsyncTask<String, Void, List<Category>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestCategoriesTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Category> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
categories = JsonReader.getCategories(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return categories;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Category> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
categories = result;
if (result != null) {
if (categories != null && categories.size() != 0) {
//for brands_adapter
categories_adapter = new Categories_View_Adapter(categories);
categories_Rec_View.setAdapter(categories_adapter);// set adapter on recyclerview
categories_Rec_View.getLayoutParams().height = (188*(categories_adapter.getItemCount()+1)+328);
} else {
}
} else {
}
}
}
}
}
}
View Pager Adapter
ImageSlideAdapter.java
package com.techzone.yallaassouk.Adapters;
/**
* Created by Yazan on 5/1/2016.
*/
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.ImageView;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.R;
import com.techzone.yallaassouk.TouchImageView;
import com.techzone.yallaassouk.fragment.ProductDetailFragment;
import com.techzone.yallaassouk.man_fragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
public class ImageSlideAdapter extends PagerAdapter {
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
private ImageLoadingListener imageListener;
FragmentActivity activity;
List<Band> bands;
Fragment homeFragment;
public ImageSlideAdapter(FragmentActivity activity, List<Band> bands,
Fragment homeFragment) {
this.activity = activity;
this.homeFragment = homeFragment;
this.bands = bands;
options = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.a1)
.showStubImage(R.drawable.a2)
.showImageForEmptyUri(R.drawable.a3).cacheInMemory()
.cacheOnDisc().build();
imageListener = new ImageDisplayListener();
}
#Override
public int getCount() {
return bands.size();
}
#Override
public View instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vp_image, container, false);
ImageView mImageView = (ImageView) view
.findViewById(R.id.image_display);
imageLoader.displayImage(
((Band) bands.get(position)).getImageURL(), mImageView,
options, imageListener);
container.addView(view);
return view;
}
#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;
}
private static class ImageDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Sorry for being not formatted. I'm new here
I found what was causing the 'ViewPager' not to fire 'OnTouchListener'
In layout XML file :
<com.techzone.yallaassouk.ExtendedViewPager
android:id="#+id/man_view_pager"
android:layout_width="fill_parent"
android:layout_height="137dp" />
<com.techzone.yallaassouk.Utils.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="130dp"/>
the problem was the 'paddingTop' of the 'CirclePageIndicator' it was set to '130dp' which covers the 'ViewPager' and it was receiving the touch events instead of 'ViewPager' itself.
Thank you.

Failing onPostExecute

I have an app I am trying to pass data through an ASYNC task but am getting a null pointer error in my onPosteExecute method. Seems like no matter how I change my code I still get this same fatal error:
10-31 18:43:56.517 1253-1253/com.brianstacks.project1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianstacks.project1, PID: 1253
java.lang.NullPointerException
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:277)
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:247)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity implements MasterFragment.OnListItemClickListener {
final String Tag = "Project 1 test";
EditText myEdit;
Button myButton;
ProgressBar pb;
SerialCustomObject myObject;
// create a reference to the list's needed for data
List<MyTask> tasks;
ArrayList<Places> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((savedInstanceState != null)&& (savedInstanceState.getSerializable("name") != null)) {
Places name = (Places) savedInstanceState.getSerializable("name");
Log.v("name:",name.getName());
}
//initiate my tasks
tasks = new ArrayList<>();
pb = (ProgressBar)findViewById(R.id.progressBar);
myEdit = (EditText)findViewById(R.id.myEditText);
myButton = (Button)findViewById(R.id.myButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void findAndRemoveFragment() {
FragmentManager mgr = getFragmentManager();
DetailFragment frag =
(DetailFragment) mgr.findFragmentByTag(DetailFragment.TAG);
if (frag == null) {
// No fragment found, possibly because the transaction
// hasn't completed yet.
} else {
// Fragment found. You can use it here.
FragmentTransaction trans = mgr.beginTransaction();
trans.remove(frag);
trans.commit();
// When the main thread runs, the fragment will be
// removed from the activity.
}
}
public void deviceStorage() {
// Read in a private file
try {
FileInputStream fis = this.openFileInput("some_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create new or open existing private file
try {
FileOutputStream fos = this.openFileOutput("some_other_file.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void writeToFile(Context _c, String _filename, String _data) {
File external = _c.getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
if(myObject == null) {
myObject = new SerialCustomObject();
}
myObject.setData(_data);
oos.writeObject(myObject);
oos.close();
// Write bytes to the stream
fos.write(_data.getBytes());
// Close the stream to save the file.
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFromFile(String _filename) {
File external = getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileInputStream fin = new FileInputStream(file);
InputStreamReader inReader = new InputStreamReader(fin);
BufferedReader reader = new BufferedReader(inReader);
// Reading data from our file using the reader
// and storing it our string buffer.
StringBuffer buffer = new StringBuffer();
String text = null;
// Make sure a line of text is available to be read.
while((text = reader.readLine()) != null) {
buffer.append(text + "\n");
}
// Close the reader and underlying stream.
reader.close();
// Convert the buffer to a string.
return buffer.toString();
} catch(IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void displayText(String myText) {
DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentByTag(DetailFragment.TAG);
if (frag == null){
frag = DetailFragment.newInstance(myText);
getFragmentManager().beginTransaction()
.replace(R.id.container2,frag,DetailFragment.TAG)
.commit();
}else {
frag.setDisplayInfo(myText);
}
}
//#Override
public void onClick(View _v){
myEdit = (EditText)findViewById(R.id.myEditText);
String newString = myEdit.getText().toString();
Log.v(Tag,newString);
}
// the method for when the button is clicked
public void myClick(View _v){
// create a string to grab the text of the edit text
String myString = myEdit.getText().toString();
// replace the spaces with + to encode into the url
String encodedString = myString.replace(" ","+");
//check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
if (isOnline()){
requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+encodedString+"&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
}else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();
}
// method to get the data from ASYNC task
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
// method to check internet connectivity
protected boolean isOnline(){
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void updateDisplay(ArrayList<Places> placeList){
// get instance of the Master List fragment then replaces container1 and commits it to the activity
MasterFragment frag = MasterFragment.newInstance(placeList);
getFragmentManager().beginTransaction()
.replace(R.id.container1, frag, MasterFragment.TAG).commit();
}
// Async task method to do network action in
private class MyTask extends AsyncTask<String ,String ,String>{
#Override
protected void onPreExecute() {
// add this to the task
tasks.add(this);
}
#Override
protected String doInBackground(String... params) {
return HttpManager.getData(params[0]);
}
#Override
protected void onPostExecute(String result) {
tasks.remove(this);
if(null != result && !result.isEmpty()) {
placeList = JSONParser.parseFeed(result);
updateDisplay(placeList);
}else {
Toast.makeText(MainActivity.this, "Can't connect to API", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(String... values) {
}
}
}
DetailFragment.java
package com.brianstacks.project1.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.brianstacks.project1.R;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class DetailFragment extends Fragment {
public static final String TAG = "DetailFragment.TAG";
public static final String ARG_TAG = "DetailFragment.TAG";
public static DetailFragment newInstance(String myString) {
DetailFragment frag = new DetailFragment();
Bundle args = new Bundle();
args.putString(ARG_TAG, myString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater _inflater, ViewGroup _container,
Bundle _savedInstanceState) {
// Create and return view for this fragment.
return _inflater.inflate(R.layout.detail_layout, _container, false);
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
Bundle args = getArguments();
if(args != null && args.containsKey(ARG_TAG)){
setDisplayInfo(args.getString(ARG_TAG));
}
}
public void setDisplayInfo(String myText){
getArguments().putString(ARG_TAG,myText);
// Get our TextView and set some text to it.
TextView tv;
tv = (TextView)getView().findViewById(R.id.detailText);
tv.setText(myText);
}
}
MasterFragment.java
package com.brianstacks.project1.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.brianstacks.project1.JSONParser;
import com.brianstacks.project1.MainActivity;
import com.brianstacks.project1.Places;
import com.brianstacks.project1.PlacesAdapter;
import com.brianstacks.project1.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class MasterFragment extends ListFragment{
public static final String TAG = "MasterFragment.TAG";
public static final String KEY = "places";
private OnListItemClickListener mListener;
private ArrayList<Places> placeList2;
public static MasterFragment newInstance(ArrayList<Places> placeList) {
MasterFragment masterFragment = new MasterFragment();
Bundle args = new Bundle();
args.putSerializable("places", placeList);
masterFragment.setArguments(args);
return masterFragment;
}
public interface OnListItemClickListener{
public void displayText(String myText);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if (activity instanceof OnListItemClickListener){
mListener = (OnListItemClickListener) activity;
}else {
throw new IllegalArgumentException("Containing Activity must implement the OnListItemClicked");
}
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
if (_savedInstanceState == null){
Bundle args = getArguments();
String myStrings=args.getString("places");
Log.v("Places",myStrings);
/*String[] presidents = getResources().getStringArray(R.array.presidents);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents);
//PlacesAdapter adapter2 = new PlacesAdapter(this.getActivity(),R.layout.item_place,placeList);
//setListAdapter(adapter2);
}
#Override
public void onListItemClick(ListView _l, View _v, int _position, long _id) {
String president = (String)_l.getItemAtPosition(_position);
mListener.displayText(president);
*/
}
}
}
HTTPManager.java
package com.brianstacks.project1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class HttpManager {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
sb.append(line).append("");
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JSONParser.java
package com.brianstacks.project1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class JSONParser {
public static ArrayList<Places> parseFeed(String content) {
JSONObject myObj;
try {
myObj = new JSONObject(content);
JSONArray result = myObj.getJSONArray("results");
ArrayList<Places> placeList = new ArrayList<>();
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
Places place = new Places();
place.setName(obj.getString("name"));
place.setFormatted_address(obj.getString("formatted_address"));
place.setTypes(obj.getString("types"));
//place.setPhotos(obj.getString("photos"));
placeList.add(place);
}
return placeList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Places.java
import java.io.Serializable;
/**
* Created by Brian Stacks
* on 10/22/14
* for FullSail.edu.
*/
public class Places implements Serializable {
private String pName;
private String pTypes;
private String pFormatted_address;
public Places(){
pName ="";
pTypes ="";
pFormatted_address = "";
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getTypes() {
return pTypes;
}
public void setTypes(String types) {
pTypes= types;
}
public String getFormatted_address() {
return pFormatted_address;
}
public void setFormatted_address(String formatted_address) {
pFormatted_address=formatted_address;
}
}
Any help is much appreciated
ALSO was reading this post but to no avail LINK!
I found my solution to this problem, it was I was trying to cast my Objectin my MasterFragment.java as a String when the code was expecting an ArrayList<Places> changed that bit of code and pow there it was, no error.
Old Code
Bundle args = getArguments();
String myStrings=args.getString("places");
New Code
Bundle args = getArguments();
ArrayList myStrings = args.getParcelableArrayList("places");

Can not access SharedPreferences value in another class after restart

I am using csipsimple code and customised it to show brandname by getting json value from webservice . I am using SharedPreferences to store value .
Once the application is force closed , or device restart SharedPreferences are lost . I am using commit and clear but still the values are null .
BasePrefsWizard is the class responsible for pulling web data and DialerFragment is the other class i am calling the BrandName ( it is SavedBrand/ brand in code)
package com.mydial.wizards;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.EditTextPreference;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mydial.api.SipManager;
import com.mydial.api.SipProfile;
import com.mydial.db.DBProvider;
import com.mydial.models.Filter;
import com.mydial.ui.SipHome;
import com.mydial.ui.dialpad.DialerFragment;
import com.mydial.ui.filters.AccountFilters;
import com.mydial.ui.prefs.GenericPrefs;
import com.mydial.utils.AccountListUtils;
import com.mydial.utils.Log;
import com.mydial.utils.PreferencesProviderWrapper;
import com.mydial.utils.PreferencesWrapper;
import com.mydial.utils.AccountListUtils.AccountStatusDisplay;
import com.mydial.utils.animation.ActivitySwitcher;
import com.mydial.wizards.WizardUtils.WizardInfo;
import com.mydial.wizards.impl.Advanced;
import com.worldfone.R;
#SuppressLint("NewApi") public class BasePrefsWizard extends GenericPrefs {
public static final int SAVE_MENU = Menu.FIRST + 1;
public static final int TRANSFORM_MENU = Menu.FIRST + 2;
public static final int FILTERS_MENU = Menu.FIRST + 3;
public static final int DELETE_MENU = Menu.FIRST + 4;
private PreferencesProviderWrapper prefProviderWrapper;
private static final String THIS_FILE = "Base Prefs wizard";
protected SipProfile account = null;
private Button saveButton,cancel;
private String wizardId = "";
private WizardIface wizard = null;
private BroadcastReceiver mReceiver;
IntentFilter intentFilter;
public static final String myData = "mySharedPreferences";
public static String bal = null;
public static String sip = null;
public static String header = null;
public static String date = null;
public static String savedBal="";
public static String savedSip="";
public static String savedBrand="";
public static String webArray[] =new String[6];
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Get back the concerned account and if any set the current (if not a
// new account is created)
Intent intent = getIntent();
long accountId = 1;
//intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
// TODO : ensure this is not null...
// setWizardId(intent.getStringExtra(SipProfile.FIELD_WIZARD));
setWizardId();
account = SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);
super.onCreate(savedInstanceState);
prefProviderWrapper = new PreferencesProviderWrapper(this);
// Bind buttons to their actions
cancel = (Button) findViewById(R.id.cancel_bt);
//cancel.setEnabled(false);
cancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isOnline();
//saveAndFinish();
}
});
saveButton = (Button) findViewById(R.id.save_bt);
//saveButton.setEnabled(false);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//setResult(RESULT_CANCELED, getIntent());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
wizard.fillLayout(account);
loadValue();
}
public void isOnline()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
try
{
String webAccessNumberLink="http://myweblink.info/test/code.php?user=1234";
new webAccessNumber().execute(webAccessNumberLink);
}
catch(Exception e)
{
// System.out.println("exception in basepreference "+e);
}
}
else
{
// display error
showNetworkAlert();
}
}
void showNetworkAlert()
{
new AlertDialog.Builder(this)
.setTitle("Alert")
.setMessage(
"Please make sure you have Network Enabled")
.setNeutralButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*Intent siphome = new Intent(getApplicationContext(),SipHome.class);
startActivity(siphome);*/
}
}).show();
}
public void saveArray(String[] arrayOfweb)
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences =this.getSharedPreferences(myData,
mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
String f1 = arrayOfweb[0];
String f2 = arrayOfweb[1];
String f3 = arrayOfweb[2];
String f4 = arrayOfweb[3];
for(int i=0;i<arrayOfweb.length;i++)
{
}
//byMe added below to make preferences persistant
editor.clear();
editor.putString("balance",f1);
editor.putString("sipp",f2);
editor.putString("brand",f3);
editor.putString("prfx",f4);
editor.commit();
loadValue();
}
private void loadValue()
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences = this.getSharedPreferences(myData,
mode);
savedBal= mySharedPreferences.getString("balance", "");
savedSip = mySharedPreferences.getString("sipp", "");
savedBrand = mySharedPreferences.getString("barnd", "");
}
private boolean isResumed = false;
#Override
protected void onResume()
{
super.onResume();
isResumed = true;
updateDescriptions();
updateValidation();
//byMe
}
#Override
protected void onPause()
{
super.onPause();
isResumed = false;
//this.unregisterReceiver(this.mReceiver);
}
private boolean setWizardId()
{
try {
wizard=Advanced.class.newInstance();
// wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/*if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}*/
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/* if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
*/ return false;
}
//wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
private boolean setWizardId(String wId) {
if (wizardId == null) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
WizardInfo wizardInfo = WizardUtils.getWizardClass(wId);
if (wizardInfo == null) {
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
try {
wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
#Override
protected void beforeBuildPrefs() {
// Use our custom wizard view
setContentView(R.layout.wizard_prefs_base);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(isResumed) {
updateDescriptions();
updateValidation();
}
}
private void resolveStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, 1);
//status.setTextColor(accountStatusDisplay.statusColor);
//status.setText(accountStatusDisplay.statusLabel);
}
/**
* Update validation state of the current activity.
* It will check if wizard can be saved and if so
* will enable button
*/
public void updateValidation()
{
cancel.setEnabled(wizard.canSave());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// menu.findItem(SAVE_MENU).setVisible(wizard.canSave());
return super.onPrepareOptionsMenu(menu);
}
private static final int CHOOSE_WIZARD = 0;
private static final int MODIFY_FILTERS = CHOOSE_WIZARD + 1;
private static final int FINAL_ACTIVITY_CODE = MODIFY_FILTERS;
private int currentActivityCode = FINAL_ACTIVITY_CODE;
public int getFreeSubActivityCode()
{
currentActivityCode ++;
return currentActivityCode;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Save account and end the activity
*/
public void saveAndFinish()
{
//this.registerReceiver(mReceiver, intentFilter);
saveAccount();
Intent intent = getIntent();
setResult(RESULT_OK, intent);
Intent it = new Intent(this,SipHome.class);
startActivity(it);
finish();
}
void updateStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, account.id);
}
/*
* Save the account with current wizard id
*/
private void saveAccount() {
saveAccount(wizardId);
}
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
/**
* Save the account with given wizard id
* #param wizardId the wizard to use for account entry
*/
private void saveAccount(String wizardId) {
boolean needRestart = false;
PreferencesWrapper prefs = new PreferencesWrapper(getApplicationContext());
account = wizard.buildAccount(account);
account.wizard = wizardId;
if (account.id == SipProfile.INVALID_ID) {
// This account does not exists yet
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());
// After insert, add filters for this wizard
account.id = ContentUris.parseId(uri);
List<Filter> filters = wizard.getDefaultFilters(account);
if (filters != null) {
for (Filter filter : filters) {
// Ensure the correct id if not done by the wizard
filter.account = (int) account.id;
getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());
}
}
// Check if we have to restart
needRestart = wizard.needRestart();
} else {
// TODO : should not be done there but if not we should add an
// option to re-apply default params
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
}
// Mainly if global preferences were changed, we have to restart sip stack
if (needRestart) {
Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
sendBroadcast(intent);
}
}
#Override
protected int getXmlPreferences() {
return wizard.getBasePreferenceResource();
}
#Override
protected void updateDescriptions() {
wizard.updateDescriptions();
}
#Override
protected String getDefaultFieldSummary(String fieldName) {
return wizard.getDefaultFieldSummary(fieldName);
}
private static final String WIZARD_PREF_NAME = "Wizard";
#Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return super.getSharedPreferences(WIZARD_PREF_NAME, mode);
}
private class webAccessNumber extends AsyncTask<String, Void, String>
{
//String balance;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
return getAccessNumber(params[0]);
}
#Override
protected void onPostExecute(String result)
{
if(result!=null)
{
try {
System.out.println("value of webAccessNumber "+result);
byte[] decoded = Base64.decode(result,Base64.DEFAULT);
String decodedStr =new String(decoded, "UTF-8");
//System.out.println(decodedStr);
JSONArray arr = new JSONArray(decodedStr);
//loop through each object
for (int i=0; i<arr.length(); i++)
{
JSONObject jsonObject = arr.getJSONObject(i);
bal = jsonObject.getString("balance");
sip = jsonObject.getString("server");
header = jsonObject.getString("brand");
webArray[1]=bal;
webArray[2]=sip;
webArray[3]=barnd;
saveArray(webArray);
saveAndFinish();
progressDialog.dismiss();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(BasePrefsWizard.this);
progressDialog.setMessage("Loading..............");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
public String getAccessNumber(String b) {
String balance = "";
String currency = "USD";
try {
balance = DownloadText(b).trim();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return balance;
}
String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0,
charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return str;
}
InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}//end of webAccessNumber asynchronus
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
isOnline();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should not clear the SharedPreferences in the onDestroy() method, because when you run your activity or your application again, all the saved values and variables in preferences are deleted, ( like you installed your application for the first time).
PS : here is a tutorial about Using SharedPreferences and Storing Data in Android
You are clearing your preferences in your code,
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
//Preferences cleared
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
This is clearing your preferences.
You are clearing the shared prefereence in onDestroy:
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); // <-- Remove this
saveArray(webArray);
}
You delete it in:
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
Also see this http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

String send to web not support utf 8

I try to send some text to web and this is my codes , but it's not support utf8
For example آرین Show ????
how can I delete this problem?!
This is supported English ...
FragmentForm
package com.kamalan.phpandroidapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and LinkManager.java for link to web
public class LinkManager {
private final static String API_FORM = "http://example.com/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://example.com/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
url = url.replaceAll(" ", "%20");
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
Please Help me.
Sry My English is bad.
Try to use urlencoding. like :HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
url is the specific urllink.And If You want to use httppost, encode the entity before setEntity

Android: how to restart a method with a button click

I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources