progress bar not showing after screen rotation in recyclerview fragment Reandroid - android

I have Recyclerview Fragment it work fine but when i change screen rotation , prograss bar not show any more , i know fragment distory all views , is there any way i can save prograss view obj in onsaveinstancestate or other any way to slove this problem ?
package com.example.ameerhamza6733.expressdaily.UI;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
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.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import com.example.ameerhamza6733.expressdaily.MainActivity;
import com.example.ameerhamza6733.expressdaily.R;
import com.example.ameerhamza6733.expressdaily.Utils.Constant;
import com.example.ameerhamza6733.expressdaily.Utils.RssFeed;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* Demonstrates the use of {#link RecyclerView} with a {#link LinearLayoutManager} and a
* {#link GridLayoutManager}.
*/
public class RecyclerViewFragment extends Fragment implements MainActivity.UpdateUI {
private static final String TAG = "RecyclerViewFragment";
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private static final int SPAN_COUNT = 2;
protected int indexofp = 0, indexOfPdash = 0;
protected LayoutManagerType mCurrentLayoutManagerType;
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected ArrayList<RssFeed> mDataset = new ArrayList<>();
protected RssFeed rssFeed;
protected Context context;
protected String url = Constant.HOME_URL;
protected ProgressBar progressBar;
protected ImageButton mImageButton;
protected boolean dataSetClrear=false;
protected View view;
#Override
public void onArticleNavigationSeleted(String url) {
this.url = url;
mDataset.clear();
dataSetClrear=true;
Log.i(TAG, "Current URL" + url);
}
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
rootView.setTag(TAG);
this.view = rootView;
// BEGIN_INCLUDE(initializeRecyclerView)
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.myRecylerView);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
mImageButton = (ImageButton) rootView.findViewById(R.id.mImageButton);
// LinearLayoutManager is used here, this will layout the elements in a similar fashion
// to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
// mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.RED).sizeResId(R.dimen.divider).marginResId(R.dimen.leftmargin, R.dimen.rightmargin).build());
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).build());
mLayoutManager = new LinearLayoutManager(getActivity());
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
} else {
mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
}
if (savedInstanceState != null ) {
// Restore saved layout manager type.
// mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
// .getSerializable(KEY_LAYOUT_MANAGER);
progressBar.setVisibility(View.VISIBLE);
mDataset = savedInstanceState.getParcelableArrayList(Constant.MY_DATA_SET_PARCE_ABLE_ARRAY_KEY);
mAdapter = new CustomAdapter(mDataset);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} else {
if (mDataset.isEmpty()) {
progressBar.setVisibility(View.VISIBLE);
initDataset();
}
}
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
return rootView;
}
/**
* Set RecyclerView's LayoutManager to the one given.
*
* #param layoutManagerType Type of layout manager to switch to.
*/
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been set, get current scroll position.
if (mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
switch (layoutManagerType) {
case GRID_LAYOUT_MANAGER:
mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT);
mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
break;
case LINEAR_LAYOUT_MANAGER:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
break;
default:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
}
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
// Save currently selected layout manager.
// savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
// savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, (Serializable) progressBar);
savedInstanceState.putParcelableArrayList(Constant.MY_DATA_SET_PARCE_ABLE_ARRAY_KEY, mDataset);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Generates Strings for RecyclerView's adapter. This data would usually come
* from a local content provider or remote server.
*/
private void initDataset() {
if (mDataset.isEmpty()) {
progressBar.setVisibility(View.VISIBLE);
new LoadRssFeedsItems().execute("");
Log.i(TAG, "" + mDataset.size());
Log.i(TAG, "initDataset");
}
}
public class LoadRssFeedsItems extends AsyncTask<String, Void, Void> {
private String mTitle, mDescription, mLink, mPubDate;
private String mCategory, mImageLn;
private String date, mContent;
private ProgressBar bar;
public void setProgressBar(ProgressBar bar) {
this.bar = bar;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
progressBar.setProgress(1);
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(String... params) {
Document rssDocument = null;
try {
rssDocument = Jsoup.connect(url).timeout(6000).ignoreContentType(true).parser(Parser.xmlParser()).get();
Elements mItems = rssDocument.select("item");
RssFeed rssItem;
for (Element element : mItems) {
mTitle = element.select("title").first().text();
mDescription = element.select("description").first().text();
mLink = element.select("link").first().text();
mPubDate = element.select("pubDate").first().text();
mCategory = element.select("category").first().text();
mImageLn = element.select("media|content").attr("url").toString();
date = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
mContent = element.select("content|encoded").first().text();
mContent = Jsoup.parse(mContent).text();
indexofp = mDescription.indexOf(Constant.P);
indexOfPdash = mDescription.indexOf(Constant.P_DASH);
mDescription = mDescription.substring(indexofp + 3, indexOfPdash);
Log.i(TAG, "Item title: " + (mContent == null ? "N/A" : mContent));
Log.i(TAG, "Item title: " + (mTitle == null ? "N/A" : mTitle));
Log.i(TAG, "Item Description: " + (mDescription == null ? "N/A" : mDescription));
Log.i(TAG, "Item link: " + (mLink == null ? "N/A" : mLink));
Log.i(TAG, "Item data: " + (mImageLn == null ? "N/A" : mImageLn));
Log.i(TAG, "Item data: " + (mPubDate == null ? "N/A" : mPubDate));
Log.i(TAG, "system date: " + (date == null ? "N/A" : date));
rssFeed = new RssFeed(mTitle, mLink, mPubDate, mCategory, mLink, mDescription, mImageLn, context, mContent);
mDataset.add(rssFeed);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (mDataset.isEmpty()) try {
// mImageButton.setVisibility(View.VISIBLE);
Snackbar mSnackbar = Snackbar.make(view, "انٹرنیٹ دستیاب نہیں ہے", Snackbar.LENGTH_INDEFINITE)
.setAction("دوبارہ کوشش کریں", new View.OnClickListener() {
#Override
public void onClick(View view) {
// Snackbar.make(getView(), "CheckIn Cancelled", Snackbar.LENGTH_LONG).show();
new LoadRssFeedsItems().execute("");
}
});
mSnackbar.show();
} catch (NullPointerException n) {
n.printStackTrace();
}
else {
progressBar.setVisibility(View.INVISIBLE);
mAdapter = new CustomAdapter(mDataset);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
}
}
here is my xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myRecylerView" />
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progressBar" />
<FrameLayout
android:id="#+id/mFramLaout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/ic_cloud_off_black_24dp"
android:id="#+id/mImageButton"
android:elevation="0dp"
android:visibility="gone"
android:background="#f1f1f1" />
</FrameLayout>
</LinearLayout>

You can use Bundle object to this purpose. In onDestroy() function add that line
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("PROGRESS", progress);
}
When Fragment will be recreated you can get back this value using this code in your public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) function by adding this line:
if(savedInstanceState!=null)
{
progress = savedInstanceState.getInt("PROGRESS");
}

Saving a variable at onSaveInstanceState didn't work for me, since you won't get updates while the Activity is destroyed.
I ended up using a ResultReceiver inside a Fragment that doesn't get destroyed by using setRetainInstance(true).
A good article concerning this problem can be found here: https://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
Also see my answer here: https://stackoverflow.com/a/54334864/6747171

Related

TextView OnClickListener not responding in fragment

I'm new to this fragment coding in Android stuff so I hope this is a simple one for most to answer.
I have a TextView object, 'next', that, when clicked, does not seem to be responding. I want to do a few things when the TextView text is clicked. First, check the String value in the eventName spinner, then Toast the eventID value and finally start a new fragment for the next part of user interaction.
I have not yet implemented the new fragment or a call to the fragment. I assume the way to call the new fragment is with the following code:
NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,"findThisFragment")
.addToBackStack(null)
.commit();
My questions are:
Why is the Toast not being displayed? It seems as though the OnCickListener or the OnClick method isn't triggering the Toast.
Is the code above all that I need to do to call a new fragment and make it active in the current Activity or is there something else that I need to add in the Activity code?
Fragment code:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FindEventFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FindEventFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FindEventFragment extends Fragment{
public static final String TAG = "FindEventFragment";
private VolleyHelper mInstance;
private ArrayList<String> eventList = new ArrayList<String>();
private JSONArray result;
private Spinner eventNameSpinner;
private TextView eventDate;
private String eventID;
private TextView next;
//TextView errorText;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FindEventFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FindEventFragment.
*/
// TODO: Rename and change types and number of parameters
public static FindEventFragment newInstance(String param1, String param2) {
FindEventFragment fragment = new FindEventFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public void onStart() {
super.onStart();
// Instantiate the RequestQueue from VolleyHelper
mInstance = VolleyHelper.getInstance(getActivity().getApplicationContext());
// API
connectApi();
}
#Override
public void onStop () {
super.onStop();
if (mInstance.getRequestQueue() != null) {
mInstance.getRequestQueue().cancelAll(TAG);
}
}
private void connectApi() {
String url = "http://gblakes.ddns.net/get_events.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
JSONObject j = null;
try {
result = new JSONArray(ServerResponse);
eventDetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity().getApplicationContext(), "Oops, something went wrong", Toast.LENGTH_LONG).show();
}
});
if (mInstance != null) {
// Add a request to your RequestQueue.
mInstance.addToRequestQueue(stringRequest);
// Start the queue
mInstance.getRequestQueue().start();
}
}
private void eventDetails(JSONArray j) {
eventList.add("Choose an event");
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
// eventList.add(json.getString("EventName") + json.getString("EventDate"));
eventList.add(json.getString("EventName"));
} catch (JSONException e) {
//e.printStackTrace();
Log.d(TAG, e.toString());
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, eventList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
eventNameSpinner.setAdapter(dataAdapter);
eventNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
//Setting the value to textview for a selected item
eventDate.setText(getEventDate(position));
eventID = (getEventID(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
eventDate.setText("test me");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make sure the user has made a valid selection
//errorText.setError("");
if (eventNameSpinner.equals("Choose an event")){
//errorText.setError("");
Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG);
//errorText.setText("Choose an event first");
} else {
//if an event is selected then open the next fragment
Toast.makeText(getActivity().getApplicationContext(),eventID.toString(),Toast.LENGTH_LONG);
}
}
});
}
private String getEventID(int position) {
String eventID = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
eventID = json.getString("EventID");
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return eventID;
}
private String getEventDate(int position){
String eventDate="";
try {
JSONObject json = result.getJSONObject(position);
eventDate = json.getString("EventDate");
} catch (JSONException e) {
e.printStackTrace();
}
return eventDate;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_find_event,container,false);
eventNameSpinner = (Spinner) v.findViewById(R.id.spinEventPicker);
//eventNameSpinner = new Spinner(getActivity().getApplicationContext());
eventDate = (TextView) v.findViewById(R.id.textEventDate);
next = (TextView) v.findViewById(R.id.link_judgeToEvent);
eventDate.setText("test me");
// errorText = (TextView)eventNameSpinner.getSelectedView();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(eventID);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String eventID);
}
}
and the fragment's XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/textEventName">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinEventPicker"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textEventDate"
android:layout_marginTop="49dp"
android:layout_below="#+id/spinEventPicker"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/link_judgeToEvent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_below="#+id/textEventDate"
android:gravity="center"
android:text="Next"
android:textAlignment="center"
android:textSize="16dip" />
</RelativeLayout>
Toast will display if you call show(), So you have to change the following line of code like this
Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG).show();
You can use the following code sample code to launch the fragment from another fragment
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();

I found this error in logcat hw_get_module_by_class: module name gralloc

I run my App on my phone. Everything works perfectly.. But after i check in my logcat for the debug.
It's show me this error.
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
It's show when user run the app for the first time. It's show just in time the app show splash screen. I'm not sure which code that make this thing happen.
So i'll show you my splash code and my fragment home code.
so this is my splasactivity code :
package com.apps.mathar;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;
import com.apps.utils.Constant;
import com.apps.utils.JsonUtils;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// hideStatusBar();
setStatusColor();
try {
Constant.isFromPush = getIntent().getExtras().getBoolean("ispushnoti", false);
Constant.pushID = getIntent().getExtras().getString("noti_nid");
} catch (Exception e) {
Constant.isFromPush = false;
}
try {
Constant.isFromNoti = getIntent().getExtras().getBoolean("isnoti", false);
} catch (Exception e) {
Constant.isFromNoti = false;
}
JsonUtils jsonUtils = new JsonUtils(SplashActivity.this);
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constant.GRID_PADDING, r.getDisplayMetrics());
Constant.columnWidth = (int) ((jsonUtils.getScreenWidth() - ((Constant.NUM_OF_COLUMNS + 1) * padding)) / Constant.NUM_OF_COLUMNS);
if(!Constant.isFromNoti) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openMainActivity();
}
}, 2000);
} else {
openMainActivity();
}
}
private void openMainActivity() {
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
public void setStatusColor()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.statusBar));
}
}
}
And this is my fragmenthome code
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
recyclerView.setAdapter(adapterRecent);
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
adapterRecent.notifyDataSetChanged();
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
recyclerView.setAdapter(adapterRecent);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
Once more, i'm sure what's going on here.
I'm looking this error since 3 days ago but i have checked my code, i dont know what is wrong with this code.
This kind of error occurs when you have a loop that doesn't terminate.I also faced the similar kind of situation and It took me literally two days to find out the root cause of problem.
My problem was:
When I run the above code, I used to get this kind of error
hw_get module_by class _gralloc... .
I was really frustrated because I was not able to find out the root cause and luckily I found out that the above section of the code was the main cause because the loop never goes to terminate in the above section and when I found about the problem main cause I replaced it by:
Then, the problem was solved..
So maybe your problem lies within the loop or similar kind of situations..

AsyncTaskLoader again initialized whenever app is minimized and resumed

When app is started it works fine i can swipe left and right without any problem. But as soon as app is been minimized and resumed it again calls the loader and data is been fetched again it results into more no of dots in bottom.
ps: The loader is been called again as dots are in onLoadfinshed.
At first launch
Intial launch
After minimizing and resuming the app
after resuming
package com.example.kaushal.slider;
/**
* Created by kaushal on 25-09-2017.
*/
import android.app.LoaderManager;
import android.content.Loader;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.List;
public class MainActivity1 extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<video1>> {
customadap adap;
ViewPager viewPager;
private List<video1> videolist;
int LoaderId = 1;
LinearLayout slidedotepanel;
int dotscount;
ImageView[] dots;
String jsonurl = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
viewPager =(ViewPager)findViewById(R.id.viewpager);
slidedotepanel = (LinearLayout)findViewById(R.id.SliderDots);
LoaderManager lm = getLoaderManager();
lm.initLoader(LoaderId,null,this);
}
#Override
public Loader<List<video1>> onCreateLoader(int i, Bundle bundle) {
return new videoLoader1(this,jsonurl);
}
#Override
public void onLoadFinished(Loader<List<video1>> loader, List<video1> videos) {
adap = new customadap(videos,this);
viewPager.setAdapter(adap);
dotscount = adap.getCount();
dots = new ImageView[dotscount];
for(int i = 0;i<dotscount;i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.nonactive_dot));
LinearLayout.LayoutParams layout_linear = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout_linear.setMargins(8, 0, 8, 0);
slidedotepanel.addView(dots[i], layout_linear);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(this,R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i =0; i<dotscount;i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onLoaderReset(Loader<List<video1>> loader) {
}
/*
public void getlib(){
StringRequest stringRequest = new StringRequest(jsonurl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONArray jarray = jsonObject.getJSONArray("videolist");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}*/
}
Updated: currently i am handling it via deleting the loader on LoadFinished in last line it works fine but won't able to handle orientation changes any better approach appreciated.
In the Activity's onCreate, we should check with the load manager if an existing thread already exists. If it does, we should not call initLoader. I've provided a simple example of how to use AsyncTaskLoader.
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Integer> {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int TASK_LOADER_ID = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate. Entered function.");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoaderManager loaderManager = getSupportLoaderManager();
Loader<Integer> myLoader = loaderManager.getLoader(TASK_LOADER_ID);
if (myLoader != null && MyAsyncTask.isRunning()) {
Log.d(TAG, "onCreate --> Existing loader exists and is running. Re-using it.");
// We use initLoader instead of restartLoader as callbacks
// must be replaced with those from this new activity
loaderManager.initLoader(TASK_LOADER_ID, null, this);
MyAsyncTask.setActivity(new WeakReference<>(this));
showProcess( true);
} else {
Log.d(TAG, "onCreate --> Loader is not active.");
showProcess( false);
}
}
private void showProcess(boolean pShowProcess) {
SeekBar seekBar = (SeekBar) findViewById(R.id.sb_progress);
Button btnStart = (Button) findViewById(R.id.btn_start);
Button btnCancel = (Button) findViewById(R.id.btn_cancel);
if (pShowProcess) {
seekBar.setVisibility(View.VISIBLE);
btnStart.setEnabled(false);
btnCancel.setEnabled(true);
}
else {
seekBar.setVisibility(View.INVISIBLE);
seekBar.setProgress(0);
btnStart.setEnabled(true);
btnCancel.setEnabled(false);
}
}
public void clickStart(View view) {
LoaderManager loaderManager = getSupportLoaderManager();
// Restart existing loader if it exists, otherwise a new one (initLoader) is auto created
loaderManager.restartLoader(TASK_LOADER_ID, null, this);
}
// A graceful attempt to stop the loader
public void clickCancel(View view) {
Loader<Integer> myLoader = getSupportLoaderManager().getLoader(TASK_LOADER_ID);
if (myLoader != null) {
MyAsyncTask.cancelled(true);
}
}
#Override
public Loader<Integer> onCreateLoader(int pID, Bundle pArgs) {
Log.d(TAG, "onCreateLoader. Entered function.");
showProcess(true);
return new MyAsyncTask(this);
}
#Override
public void onLoadFinished(Loader<Integer> pLoader, Integer pResult) {
Log.d(TAG, "onLoadFinished --> Number of items processed = " + pResult);
showProcess( false);
getLoaderManager().destroyLoader(TASK_LOADER_ID);
}
#Override
public void onLoaderReset(Loader<Integer> pLoader) { }
private static class MyAsyncTask extends AsyncTaskLoader<Integer> {
private final static int SLEEP_TIME = 10 * 10; // 100 milliseconds
static WeakReference<MainActivity> aActivity;
private static boolean isRunning = false, cancelled = true;
private Integer aResult; // Holds the results once the task is finished or cancelled
MyAsyncTask(MainActivity pActivity) {
super(pActivity);
aActivity = new WeakReference<>(pActivity);
}
synchronized static void setActivity(WeakReference<MainActivity> pActivity) {
aActivity = pActivity;
}
synchronized static void cancelled(boolean pCancelled) {
cancelled = pCancelled;
}
static boolean isRunning() {
return isRunning;
}
#Override
protected void onStartLoading() {
Log.d(TAG, "onStartLoading. Entered function. cancelled = " + cancelled);
super.onStartLoading();
if (aResult != null) {
deliverResult(aResult);
return;
}
if (!isRunning) { // Don't start a new process unless explicitly initiated by clickStart
Log.d(TAG, "onStartLoading --> No existing process running, so we can start a new one.");
forceLoad();
}
}
#Override
public Integer loadInBackground() {
Log.d(TAG, "loadInBackground. Entered function.");
isRunning = true;
cancelled = false;
int i;
for (i = 1; i < 100 && !cancelled; i++) {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
if (aActivity.get() != null) {
SeekBar seekBar = (SeekBar) aActivity.get().findViewById(R.id.sb_progress);
seekBar.setProgress(i);
}
if (i % 15 == 0) {
Log.d(TAG, "Process running with i = " + i);
}
}
isRunning = false;
aResult = i;
return aResult;
}
}
}
activity_main.xml is given below.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.snoopy.loadertest.MainActivity">
<SeekBar
android:id="#+id/sb_progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickStart"
android:text="Start Process"
app:layout_constraintBottom_toTopOf="#id/sb_progress"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
When the 'Start Button' is clicked, it makes the SeekBar visible and starts the AsyncTaskLoader in a separate thread. While the task is running, you can rotate the device and send it to the background. On restarting the app, onCreate checks if the task exists. If so, it updates the new Activity object to the task so that the new progress bar can be updated by the task. I've tested this and it works. This should give you a better idea on how to use AsyncTaskLoader and manage resume.

Loading data from sqlite and displaying on ViewPager

Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks

Android - Pull to refresh within a tabbed fragment

I'm trying to make a refresh while sliding down on the top of the listview possible. I followed this link to make it work and it does on an activty. But I need it on fragments that are tabbed within a main activity so I cannot as the example shows use this method on my fragments.
Here's the correct code while using an activity:
TestActivity.java
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class TestActivity extends BaseActivity {
#Override
protected Fragment getSampleFragment() {
return new SimpleListFragment();
}
public static class SimpleListFragment extends ListFragment implements
OnRefreshListener {
int i = 0;
private PullToRefreshLayout mPullToRefreshLayout;
ArrayAdapter<String> adapter;
List<String> list;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
list = new ArrayList<String>();
int no = 1;
for (int i = 0; i < 5; i++) {
list.add("Item No :" + no++);
}
super.onViewCreated(view, savedInstanceState);
ViewGroup viewGroup = (ViewGroup) view;
// As we're using a ListFragment we create a PullToRefreshLayout
// manually
mPullToRefreshLayout = new PullToRefreshLayout(
viewGroup.getContext());
// We can now setup the PullToRefreshLayout
ActionBarPullToRefresh
.from(getActivity())
// We need to insert the PullToRefreshLayout into the
// Fragment's ViewGroup
.insertLayoutInto(viewGroup)
// Here we mark just the ListView and it's Empty View as
// pullable
.theseChildrenArePullable(android.R.id.list,
android.R.id.empty).listener(this)
.setup(mPullToRefreshLayout);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
// Set the List Adapter to display the sample items
setListAdapter(adapter);
setListShownNoAnimation(true);
}
#Override
public void onRefreshStarted(View view) {
// TODO Auto-generated method stub
// setListShown(false); // This will hide the listview and visible a
// round progress bar
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000); // 5 seconds
int itemNo = list.size();
itemNo++;
list.add("New Item No :" + itemNo);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
// Notify PullToRefreshLayout that the refresh has finished
mPullToRefreshLayout.setRefreshComplete();
// if you set the "setListShown(false)" then you have to
// uncomment the below code segment
// if (getView() != null) {
// // Show the list again
// setListShown(true);
// }
}
}.execute();
}
}
}
I've already tried multiple times to make this method work in my fragment code but I cannot succeed. The code below is a working fragment example without any input of the TestActivity.
InfoFragment.java
import java.util.ArrayList;
import java.util.List;
import com.example.app.Config;
...
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class TicketInfoFragment extends Fragment {
List<Info> ticketInfo;
TicketFull ticket = new TicketFull();
private DatabaseHelper db;
int ticketId = TicketActivity.getCurrentTicketId();
String androidId;
String authCode;
String platform_url;
int uId;
View rootView;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = new DatabaseHelper(getActivity());
androidId = Secure.getString(getActivity().getContentResolver(),
Secure.ANDROID_ID);
Config config = new Config();
config = db.getConfig(androidId);
authCode = config.getAuthCode();
platform_url = config.getPlatformURL();
uId = config.getuId();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_ticket_information, container, false);
fillTicket();
return rootView;
}
private void fillTicket() {
HttpReader httpReader = new HttpReader();
httpReader
.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
#Override
public void resultReady(String result) {
JsonHelper jsonHelper = new JsonHelper();
ticket = jsonHelper.getTicket(result);
//showTicket();
fillSettings();
}
});
httpReader
.execute("http://aa.domainlink.com:1324/example/API/v1/json.php?auth=example&a=ticket&uauth="
+ authCode + "&uid=" + uId + "&id=" + ticketId);
}
private void readSettings() {
InfoAdapter infoAdapter = new InfoAdapter(
getActivity(), ticketInfo);
final ListView listViewInfo = (ListView) rootView.findViewById(R.id.listViewInfo);
listViewInfo.setAdapter(infoAdapter);
listViewInfo
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView,
View childView, int position, long id) {
}
});
listViewInfo.setEmptyView(rootView.findViewById(R.id.empty));
}
private void fillSettings() {
String dueDate = getString(R.string.noDueDate);
ticketInfo = new ArrayList<Info>();
ticketInfo.add(new Info(getString(R.string.ticket_subject), ticket.getSubject() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_relation), ticket.getRelation() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_status), ticket.getStatus() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_priority), ticket.getPriority() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_created), ticket.getTicketCreate() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_department), ticket.getDepartmentName() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_user), ticket.getUser() + ""));
if (!ticket.getDueDate().equals("00-00-0000 00:00:00")) {
dueDate = ticket.getDueDate();
}
ticketInfo.add(new Info(getString(R.string.ticket_dueDate), dueDate));
readSettings();
}
}
The BaseActivity that the activity normally requires:
BaseActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Add the Sample Fragment if there is one
Fragment sampleFragment = getSampleFragment();
if (sampleFragment != null) {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, sampleFragment).commit();
}
}
//This method will override by child class. Then base class can get the fragment
protected Fragment getSampleFragment() {
return null;
}
}
Posting my failed tries on implementing the activity method in my fragments would not work I guess so I do not post them.
If anyone of you could help thanks alot.
Android SDK has finally added SwipeRefreshLayout. Maybe you can add this to your layout?
http://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html

Categories

Resources