Having navigation drawer in application, Each drawer represents one Fragment each Fragment is having an AsyncTask to download separate data. I am changing Fragments by these codes
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home_main:
menuItem.setChecked(true);
actionBar.setTitle("Home");
drawerLayout.closeDrawer(GravityCompat.START);
if(getSupportFragmentManager().findFragmentByTag("ranking")==null)
{
getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
new Home(), "ranking").
addToBackStack("ranking").
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
else
{
getSupportFragmentManager().popBackStack("ranking", 0);
}
return true;
case R.id.national_events:
menuItem.setChecked(true);
actionBar.setTitle("National events");
drawerLayout.closeDrawer(GravityCompat.START);
if(getSupportFragmentManager().findFragmentByTag("ranking3")==null)
{
getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
new NationalEvents(), "ranking3").
addToBackStack("ranking3").
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
else
{
getSupportFragmentManager().popBackStack("ranking3", 3);
}
return true;
case R.id.workshops:
menuItem.setChecked(true);
actionBar.setTitle("Workshops");
drawerLayout.closeDrawer(GravityCompat.START);
if(getSupportFragmentManager().findFragmentByTag("ranking4")==null)
{
getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
new Workshops(), "ranking4").
addToBackStack("ranking4").
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
else
{
getSupportFragmentManager().popBackStack("ranking4", 4);
}
return true;
And the code being used for downloading data is
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View home_view = inflater.inflate(R.layout.list_view, container, false);
tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/cool_jazz.ttf");
swipeLayout = (SwipeRefreshLayout) home_view.findViewById(R.id.swipe_container);
swipeLayout.setColorSchemeColors(R.color.md_purple_500,
R.color.md_deep_purple_A400,
R.color.md_pink_500,
R.color.md_red_500);
mRecyclerView = (RecyclerView) home_view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mProgressBar = (ProgressBar) home_view.findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
mDescription=(TextView)home_view.findViewById(R.id.desription);
mDescription.setText(getString(R.string.national_events));
mDescription.setTypeface(tf);
iu1=(TextView)home_view.findViewById(R.id.iu1);
iu1.setTypeface(tf);
iu2=(TextView)home_view.findViewById(R.id.iu2);
iu2.setTypeface(tf);
iu3=(TextView)home_view.findViewById(R.id.iu3);
iu3.setTypeface(tf);
iu4=(TextView)home_view.findViewById(R.id.iu4);
iu4.setTypeface(tf);
iu5=(TextView)home_view.findViewById(R.id.iu5);
iu5.setTypeface(tf);
iu6=(TextView)home_view.findViewById(R.id.iu6);
iu6.setTypeface(tf);
internet=(RelativeLayout)home_view.findViewById(R.id.internet_unavailable);
internet.setVisibility(View.GONE);
Senturl = "http://javatechig.com/?json=get_recent_posts&count=45";
new MainActivityData().execute(Senturl);
swipeLayout.setOnRefreshListener(this);
return home_view;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);setRetainInstance(true);
}
#Override
public void onRefresh() {
mProgressBar.setVisibility(View.GONE);
internet.setVisibility(View.GONE);
new MainActivityData().execute(Senturl);
}
public class MainActivityData extends AsyncTask<String,Void,Integer>
{
#Override
protected void onPreExecute() {
getActivity().setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode ==200 ) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e){
if(e.getLocalizedMessage()!=null){
Log.d(TAG, e.getLocalizedMessage());
}
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
mProgressBar.setVisibility(View.GONE);
swipeLayout.setRefreshing(false);
mDescription.setVisibility(View.GONE);
if (result == 1) {
new Thread(new Runnable() {
#Override
public void run() {
mAdapter = new MembersAdapter(getActivity(),membersList);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (mAdapter != null)
{
mRecyclerView.setAdapter(mAdapter);
}}
});
}
}).start();
} else {
internet.setVisibility(View.VISIBLE);
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
membersList = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
Members item = new Members();
item.setTitle(post.optString("title"));
item.setThumbnail(post.optString("thumbnail"));
item.setDescription(post.optString("content"));
item.setDate(post.optString("date"));
//item.setSub_title(post.optString("sub_title"));
membersList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Things are working fine but when I am changing the multiple fragments in very small interval of time then Application is getting crashed. What I think is this all is due to a lot of AysncTasks given to the system. May be this want to pause AsyncTask.
I would suggest putting every AsyncTask in one separate non-ui retained fragment (a fragment that doesn't hold any views and is initialized with setRetainInstance(true) method in onCreate(). The AsyncTasks will load the data into this fragment, and during reconfiguration it won't be destroyed thanks to setRetainInstance(true). Then, after reconfiguration you can retrieve the data from this fragment and do with it as you will - populate the adapters and so on.
Related
I tried to build an app that have 5 fragment that displayed using bottom navigation view. I use volley to get the data from database. i have a problem with calling the data. at fragment A. i call the web service and got some data and then display it using recyclerview. But if i move to another fragment ( lets say fragment B) and went back to the fragment A. the data is lost and it just show the standard ui like search widget,spinner widget. All i want to ask is :
where should i put the code to call web service for all my fragment. On the activity that handle the fragment or just on the fragment?
why volley doesn't call data again when i back to the fragment?
this is the code of my mainactivity that contain bottom navigation view with 5 fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkStatusAvialable (getApplicationContext())) {
bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
frameLayout=(FrameLayout) findViewById(R.id.main_frame);
herbal= new herbal();
crude = new crude();
database=new database();
analysis=new analysis();
compound=new compound();
setFragment(herbal);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
default:
return false;
}
}
});
} else {
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
this is the example in my fragment which calling web service and then display it using recycler view:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
kampoModels = new ArrayList<>();
searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
searchHerbal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchHerb();
}
});
loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
sortData(rootView);
get20DataJamu();
get20DataKampo();
StartRecyclerViewJamu(rootView);
return rootView;
}
private void searchHerb() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
searchHerbs searchHerbs = new searchHerbs();
ft.replace(R.id.main_frame, searchHerbs);
ft.commit();
}
private void StartRecyclerViewKampo(View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
mRecyclerView.setAdapter(kampoAdapter);
kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
kampoModels.add(null);
kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
kampoModels.remove(kampoModels.size() - 1);
kampoAdapter.notifyItemRemoved(kampoModels.size());
//add items one by one
int start = kampoModels.size();
int end = start + 20;
loadMoreKampo(start, end);
}
}, 5000);
}
});
}
private void loadMoreKampo(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
kampoAdapter.notifyItemInserted(kampoModels.size());
} catch (JSONException e) {
}
}
kampoAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void get20DataKampo() {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
Log.d(TAG, "lengthresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerrorkampo" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void StartRecyclerViewJamu(final View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
mRecyclerView.setAdapter(mAdapter);
loadData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAdapter.notifyDataSetChanged();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
herbalModels.add(null);
mAdapter.notifyItemInserted(herbalModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
herbalModels.remove(herbalModels.size() - 1);
mAdapter.notifyItemRemoved(herbalModels.size());
//add items one by one
int start = herbalModels.size();
int end = start + 20;
loadMoreJamu(start, end);
}
}, 5000);
}
});
}
private void get20DataJamu() {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
Log.d(TAG, "lengthonresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void loadMoreJamu(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
mAdapter.notifyItemInserted(herbalModels.size());
} catch (JSONException e) {
}
}
mAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void sortData(final View rootView) {
final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
itemList.add(
new categoriesHerbal(
"1",
"Jamu"
)
);
itemList.add(
new categoriesHerbal(
"2",
"Kampo"
)
);
ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewJamu(rootView);
} else {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewKampo(rootView);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
move your data code in separate class and call it wherever needed.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
/*default:
return false;*/ //no need for this one
}
return true; /*you forget'it*/
}
i'm trying to save object(saveMOvie) in onSaveinstanceState to restore it on screen rotated when debugging the code using tablet with main and detail fragments are next to each other the value of object (saveMOvie) is null but when using mobile phone with only one fragment on screen the value of object (saveMOvie) doesn't equal null could anyone tell me why ??
MainActivityFragment
public class MainActivityFragment extends Fragment {
Movie moviesStore[];
GridView gridView;
String[] moviesImages;
View rootView;
ImageAdapter imgadpt;
boolean flag;
OnNewsItemSelectedListener onis;
Movie saveMOvie = new Movie();
public interface OnNewsItemSelectedListener {
public void onMovieSelected(Movie movie);
}
public MainActivityFragment() {
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//3shan myy7slash duplicate
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
onis = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.open_settings_activity) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
//refresh used when there is no connection
} else if (id == R.id.Refresh_activity) {
onStart();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mode = prefs.getString(getString(R.string.key),
getString(R.string.default_value));
if (mode.equals("popular") || mode.equals("top_rated")) {
new FetchMovies().execute(mode);
} else {
if (flag) {
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
FavouriteActivityFragment fav = new FavouriteActivityFragment();
fragmentTransaction.replace(R.id.frag_main, fav);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Intent intent = new Intent(getActivity(), FavouriteActivity.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
transaction.commit();
flag = isTablet(getActivity());
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf == null && nf.isConnected() != true) {
Snackbar snackbar = Snackbar
.make(rootView, "Network Not Available", Snackbar.LENGTH_LONG)
.setAction("RECONNECT", new View.OnClickListener() {
#Override
public void onClick(View view) {
onStart();
}
});
snackbar.show();
}
updateMovies();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("movie",saveMOvie);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
onis.onMovieSelected(saveMOvie);
}
setHasOptionsMenu(true);
rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
return rootView;
}
public class FetchMovies extends AsyncTask<String, Void, Movie[]> {
private final String Log_Tag = FetchMovies.class.getSimpleName();
private Movie[] getMovieDataFromJson(String moviesJasonStr)
throws JSONException
{
final String lists = "results";
final String decription = "overview";
final String originalTitle = "original_title";
final String moviePoster = "poster_path";
final String userRating = "vote_average";
final String releaseDate = "release_date";
final String id = "id";
JSONObject moviesJason = new JSONObject(moviesJasonStr);
JSONArray moviesArray = moviesJason.getJSONArray(lists);
// String[] resultStrs = new String[moviesArray.length()];
moviesStore = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject oneMovieInfo = moviesArray.getJSONObject(i);
moviesStore[i] = new Movie();
moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview"));
moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average"));
moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date"));
moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title"));
moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path"));
moviesStore[i].setId(oneMovieInfo.getString("id"));
}
return moviesStore;
}
#Override
protected Movie[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJasonStr = null;
StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/");
baseUrl.append(params[0]);
baseUrl.append("?api_key=");
baseUrl.append(BuildConfig.MOVIE_DP_API_KEY);
try {
// URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6");
URL url = new URL(baseUrl.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
moviesJasonStr = buffer.toString();
Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr);
} catch (IOException e) {
Log.e(Log_Tag, "Error ", e);
// Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(Log_Tag, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(moviesJasonStr);
} catch (JSONException e) {
Log.e(Log_Tag, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Movie[] result) {
if (result != null) {
moviesImages = new String[result.length];
for (int i = 0; i < result.length; i++) {
StringBuilder baseUrl = new StringBuilder();
baseUrl.append("http://image.tmdb.org/t/p/w185/");
baseUrl.append(result[i].getMoviePoster());
moviesImages[i] = baseUrl.toString();
}
imgadpt = new ImageAdapter(getActivity(), moviesImages);
gridView.setAdapter(imgadpt);
// if(flag){
// onis.onMovieSelected(moviesStore[0]);}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String posterUrl = (String) imgadpt.getItem(position);
saveMOvie = moviesStore[position];
if (flag) {
onis.onMovieSelected(moviesStore[position]);
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie", moviesStore[position]);
startActivity(intent);
}
}
});
} else {
Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show();
}
}
}
}
When onCreate(savedInstanceState) is called, check whether savedInstanceState is null, and if not, then getExtras from it (as it's a Bundle).
if (savedInstanceState != null)
savedInstanceState.getParcelable(key)
Then do whatever you'd like with the object.
I m working on a project in which i have to add the tabs and the data dynamically from the json.
The following is the code in the activity in which i add the tabs
private void getShopDetails() {
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
SharedPreferences sharedPreferences = getSharedPreferences("ShopDetailsJson", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("sdresponse", response.toString());
editor.apply();
ProgressDialog.dismiss();
coordinatorLayout.setVisibility(View.VISIBLE);
try {
JSONArray shopDetailsArray = response.getJSONArray("shop_details");
JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
shopName = shopDetailsObj.getString("shop_name");
phone = shopDetailsObj.getString("tel");
shopNum = shopDetailsObj.getString("shop_no");
shopAddress = shopDetailsObj.getString("shop_address");
shopImage = shopDetailsObj.getString("featured_image");
Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
colLayout.setTitle(shopName);
address.setText("Address - " + shopAddress);
JSONArray tabsArray = response.getJSONArray("category");
if (tabsArray != null) {
categoryId = new int[tabsArray.length()];
for (int i = 0; i < tabsArray.length(); i++) {
JSONObject tabsObj = tabsArray.getJSONObject(i);
tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
categoryId[i] = tabsObj.getInt("category_id");
}
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
pager.setOffscreenPageLimit(tabLayout.getTabCount());
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
Log.d("CATIID", categoryId[tab.getPosition()] + "");
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
ProgressDialog.dismissWithError();
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
Following is the code of fragment
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = true;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
Boolean isdataloaded = false;
ProgressBar progressBar;
private boolean fragmentResume = false;
private boolean fragmentVisible = true;
private boolean fragmentOnCreated = false;
public ShopDetailsTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
progressBar = (ProgressBar) v.findViewById(R.id.progressBarTabs);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
if (!fragmentResume && fragmentVisible) { //only when first time fragment is created
makeJsonRequest();
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) { // only at fragment screen is resumed
fragmentResume = true;
fragmentVisible = false;
fragmentOnCreated = true;
makeJsonRequest();
} else if (isVisibleToUser) { // only at fragment onCreated
fragmentResume = false;
fragmentVisible = true;
fragmentOnCreated = true;
} else if (!isVisibleToUser && fragmentOnCreated) {// only when you go out of fragment screen
fragmentVisible = false;
fragmentResume = false;
}
// if (getView() != null) {
// isViewShown = true;
// makeJsonRequest();
//
//
// // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
// } else {
// isViewShown = false;
// }
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
isdataloaded = true;
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
if (arrayList != null) {
if (arrayList.size() > 0)
arrayList.clear();
}
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = "http://allmartapp.com/appapi/uploads/" + productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("price");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
void makeJsonRequest() {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("ShopDetailsJson", Context.MODE_PRIVATE);
String response = sharedPreferences.getString("sdresponse", null);
try {
JSONArray jsonArray = new JSONObject(response).getJSONArray("category");
Log.d("TBASARRAY", jsonArray + "");
progressBar.setVisibility(View.GONE);
if (arrayList != null) {
if (arrayList.size() > 0)
arrayList.clear();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject catObj = jsonArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = "http://allmartapp.com/appapi/uploads/" + productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("price");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.addOnItemTouchListener(new CategoryListActivity.RecyclerTouchListener(getActivity(), recyclerView, new CategoryListActivity.OnClickListener() {
#Override
public void onClick(View v, int position) {
int id = arrayList.get(position).getId();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CATITEMID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("catitemid", id);
editor.apply();
startActivity(new Intent(getActivity(), ItemDetailView.class));
}
#Override
public void onLongClick(View v, int position) {
}
}));
// shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
My problem is that the function makeJsonRequest() is only called when i swipe the tabs. Actually the onCreateview method is not called unless i swipe the tabs.
And also, when i press back and come back to that activity, the data of that tab that was left when pressing back appears at the first tab.
Any help/ guidance will be appreciated.
I would suggest you looking at theViewPager's setOffscreenPageLimit(int) method.
It controls how many tabs left/right must be preinitialised before showing them.
As for 'back' problem. Probably the first fragment is 'added' to the activity Backstack, and the other ones are 'replaced'. Therefore calling onBackPressed of Activity is just going back in the Backstack.
I'm fighting with this for a week, without luck.
From the begining:
There is an Activity with Navigation Drawer included. This activity has it's own fragments. Fragments have logic to send requests to a weather api and logic to update themselves with given data. At the first run everything seems to work fine! I'm able to send request and fill views with given data (using okHttp).
Everything is starting to collapse after fragments recreations, I'm getting constantly getActivity() to be null ;(
Code Sample below:
Fragments first initialisation:
public abstract class DoubleFragmentActivity extends AppCompatActivity {
protected static final String TOP_FRAGMENT = "TOP_FRAGMENT";
protected static final String BOTTOM_FRAGMENT = "BOTTOM_FRAGMENT";
protected abstract Fragment topFragment();
protected abstract Fragment bottomFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.topFragmentContainer, topFragment(), TOP_FRAGMENT)
.add(R.id.bottomFragmentContainer, bottomFragment(), BOTTOM_FRAGMENT)
.commit();
getSupportFragmentManager().executePendingTransactions();
}
}
}
Navigation Drawer:
private void selectDrawerItem(MenuItem menuItem) {
Fragment f;
Fragment f2;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (menuItem.getItemId()) {
case R.id.forecastFragment:
f = getSupportFragmentManager().findFragmentByTag("TOP_FRAGMENT");
f2 = getSupportFragmentManager().findFragmentByTag("BOTTOM_FRAGMENT");
if (f != mCurrentForecastFragment || f2 != mDailyForecastFragment) {
ft.replace(R.id.topFragmentContainer, new CurrentForecastFragment(), "TOP_FRAGMENT");
ft.replace(R.id.bottomFragmentContainer, new DailyForecastFragment(), "BOTTOM_FRAGMENT");
} else {
}
break;
case R.id.settingsFragment:
mToolbar.setVisibility(View.INVISIBLE);
f = new SettingsFragment();
ft.replace(R.id.topFragmentContainer, f);
break;
case R.id.paymentsFragment:
f = new PaymentsFragment();
ft.replace(R.id.topFragmentContainer, f);
break;
case R.id.aboutFragment:
break;
default:
}
getSupportFragmentManager().executePendingTransactions();
ft.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
Fragment`s logic for connecting and fullfilling data:
public void makeConnectionToApi(String lat, String lon) {
mWeatherParams.setLanguage(Locale.getDefault().getLanguage());
Activity a = getActivity();
Uri.Builder currentBuilder = new Uri.Builder();
currentBuilder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("weather")
.appendQueryParameter(WeatherConstants.KEY_LATITUDE, lat)
.appendQueryParameter(WeatherConstants.KEY_LONGITUDE, lon)
.appendQueryParameter(WeatherConstants.KEY_UNITS, mUnit)
.appendQueryParameter(WeatherConstants.KEY_LANGUAGE, mWeatherParams.getLanguage())
.appendQueryParameter("APPID", "###");
String currentUrl = currentBuilder.build().toString();
if (mUtility.isNetworkAvalaible()) {
Request requestCurrent = new Request.Builder().url(currentUrl).build();
//FIRST CALL
mCall = client.newCall(requestCurrent);
mCall.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Bundle args = new Bundle();
args.putString(TAG, e.toString());
Utility.invokeDialog(TAG, e.toString(), getFragmentManager());
}
#Override
public void onResponse(Response response) throws IOException {
String responseBody = String.valueOf(response.body().string());
try {
mForecast.setCurrent(fetchCurrent(responseBody));
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillViewWithValues();
}
});
}
});
} else {
Utility.invokeDialog(TAG, "Check your internet connection!", getFragmentManager());
}
}
private Current fetchCurrent(String responseBody) throws JSONException {
Current current = new Current();
JSONObject jo = new JSONObject(responseBody);
//FETCH WEATHER ARRAY
JSONArray weather = jo.getJSONArray(WeatherConstants.KEY_CURRENT_CONDITIONS_ARRAY);
for (int j = 0; j < weather.length(); j++) {
JSONObject weatherParser = weather.getJSONObject(j);
current.setIcon(weatherParser.getString(WeatherConstants.KEY_ICON_ID));
Log.i(TAG, "Icons ID: " + weatherParser.getString(WeatherConstants.KEY_ICON_ID));
current.setConditions(weatherParser.getString(WeatherConstants.KEY_DESCRIPTION));
}
//FETCH TEMP
JSONObject temp = jo.getJSONObject(WeatherConstants.KEY_MAIN_OBJECT);
current.setDay(temp.getDouble(WeatherConstants.KEY_TEMP));
current.setPressure(temp.getDouble(WeatherConstants.KEY_PRESSURE));
current.setHumidity(temp.getDouble(WeatherConstants.KEY_HUMIDITY));
current.setDayMax(temp.getDouble(WeatherConstants.KEY_TEMP_DAY_MAX));
// FETCH VISIBILITY
if (jo.has(WeatherConstants.KEY_VISIBILITY)) {
current.setVisibility(jo.getInt(WeatherConstants.KEY_VISIBILITY));
}
//FETCH WIND
JSONObject wind = jo.getJSONObject(WeatherConstants.KEY_WIND_OBJECT);
current.setWindSpeed(wind.getDouble(WeatherConstants.KEY_WIND_SPEED));
if (wind.has(WeatherConstants.KEY_WIND_DEGREES)) {
current.setWindDegrees(wind.getInt(WeatherConstants.KEY_WIND_DEGREES));
}
JSONObject clouds = jo.getJSONObject(WeatherConstants.KEY_CLOUDS);
current.setClouds(clouds.getInt("all"));
current.setTimeStamp(jo.getInt(WeatherConstants.KEY_TIMESTAMP));
current.setCurrentLocation(jo.getString(WeatherConstants.KEY_CITY_NAME));
return current;
}
private void fillViewWithValues() {
Current current = mForecast.getCurrent();
if (mDeegreSwitch == 0) {
mCurrentTemperature.setText(current.getDay() + "\u00B0");
// setBackgroundColor(current.getDay());
} else {
int c = current.getDay();
double f = (9.0 / 5.0) * c + 32;
int e = (int) Math.round(f);
mCurrentTemperature.setText(String.valueOf((int) Math.round(f)) + "\u00B0");
// setBackgroundColor(e);
}
mCurrentCondition.setText(current.getConditions());
mPressure.setText(String.valueOf(current.getPressure()) + "hPa");
mClouds.setText(String.valueOf(current.getClouds()) + "%");
mHumidity.setText(String.valueOf(current.getHumidity()) + "%");
mCurrentIcon.setImageResource(current.getIcon());
}
Problems occurs here: getActivity().runOnUiThread inside makeConnectionToApi method. I've tried to fetch an activity from onAttach method and pass it makeConnectionToApi as parameter, it worked...but partially. App didn't crash but fragment`s view was not updated, like there was a second fragment underneath or something.
I have filling it might be something with threads or I'm doing sth wrong with fragments transaction...
I need to start and stop the Http request based on AsychronousHttpClient library. i can able to get start the request and getting data from the server but i cannot able to stop the request? Can Anyone suggest any ideas. This is my sample code.
MainActivity:
public class MainActivity extends ActionBarActivity {
Context context;
public NSUCDownload downloadDishes;
public ByteArrayEntity entity;
public String jsonData;
Button send,cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
send=(Button)findViewById(R.id.send);
cancel=(Button)findViewById(R.id.cancel);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread t1 = new Thread(new Runnable() {
public void run()
{
PostMethod();
}
}); t1.start();
}
});
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// cancel code
Client.cancelAllRequests(context);
}
});
}
void PostMethod()
{
JSONObject objRootNode = new JSONObject();
JSONArray aryChildNodes = new JSONArray();
aryChildNodes.put("some data" );// here parameter for POST data
try {
objRootNode.put("lstDishKeys_in", aryChildNodes);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Json Request for = "+objRootNode.toString());
String postString = objRootNode.toString();
downloadDishes = new NSUCDownload("http:// link which contains value for the Post data",postString,this);
entity = downloadDishes.start();
try {
if(entity!=null)
{
jsonData = EntityUtils.toString(entity);
System.out.println(" Json Data="+jsonData);// here i get final data
}
else
jsonData=null;
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
This is Download Class which is interact with Client class
public class NSUCDownload {
Context context;
public String url;
public GetJsonData objGetJsonData;
int methodtype = 1;
String postData = null;
public final static int GET = 1;
public final static int POST = 2;
ByteArrayEntity responseEntity=null;
Client clientRequest=new Client();
public NSUCDownload(String url, String in_postData, MainActivity context) {
this.url = url;
this.postData = in_postData;
this.methodtype = 2;
this.context=context;
}
public ByteArrayEntity start()
{
objGetJsonData = new GetJsonData();
try {
objGetJsonData.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return objGetJsonData.getData();
}
public class GetJsonData extends AsyncTask<Void,Void,HttpEntity>
{
public ByteArrayEntity getData()
{
return responseEntity;
}
#Override
protected void onPostExecute(HttpEntity result) {
System.out.println("On_Post_Execute_Invoked");
super.onPostExecute(result);
}
#Override
protected HttpEntity doInBackground(Void...none) {
try {
if (methodtype == POST) {
if (postData != null) {
StringEntity entity = new StringEntity(postData);
Client.post(context,url,entity, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode,org.apache.http.Header[] headers,byte[] responseBody) {
responseEntity = new ByteArrayEntity(responseBody);
System.out.println(" Success ="+responseBody);
}
#Override
public void onFailure(int statusCode,org.apache.http.Header[] headers,byte[] responseBody, Throwable error) {
System.out.println( "Failure");
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
return responseEntity;
}
}
}
Finally this is my Client Class:
public class Client {
static AsyncHttpClient asyncClient = new AsyncHttpClient();
static AsyncHttpClient syncClient = new SyncHttpClient();
static AsyncHttpClient clientReq;
public static void post(Context context, String url, StringEntity entity,String string, AsyncHttpResponseHandler asyncHttpResponseHandler) {
clientReq=getClient();
clientReq.post(context, url, entity, "application/json", asyncHttpResponseHandler );
System.out.println("Context=="+context);
}
private static AsyncHttpClient getClient()
{
// Return the synchronous HTTP client when the thread is not prepared
if (Looper.myLooper() == null)
{
System.out.println(" Getting SyncHttpClient Object");
return syncClient;
}
System.out.println(" Getting AsyncHttpClient Object");
return asyncClient;
}
/*I used this method but still it does not cancel the request. */
public static void cancelAllRequests(Context context)
{
clientReq.cancelRequests(context, true);
//clientReq.cancelAllRequests(true);
System.out.println("CancledRequest ");
}
}