Let fragment wait for asynctask finished? - android-fragments

I use fragments with viewPager. One of fragment use asynctask to download data. Now the problem is the task hasn't finish but fragment's onCreateView return already.
Can I update fragment while task finished? I tried to call view.invalidate() is not working.
public class LineChartFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
new Background().execute();
return view;
}
}
class Background extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (haveInternet()) {
getter();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//UPDATE fragment
....
view = ChartFactory.getLineChartView(getActivity().getApplicationContext(), dataset, renderer);
....
view.invalidate();
}

I found this
Calling a class from a fragment
inflate a linearLayout and add chart view to the layout. Thanks!

Related

Getting a Fragment inside a ViewPager in Android using getRegisteredFragment returns null

I've been searching a lot and I can't make it work.
I have a problem trying to get fragments inside a viewpager with a tabstrip.
I've implemented a SparseArray as I read here and several methods that I found here but I can't make it work.
The thing is that everytime I call adapter.getRegisteredFragment(position).. I always receive null unless I made it inside the onPageSelected event of the tabsStrip, there it works.. but I don't want to get the fragments there.
Those are my classes:
My fragment:
public class WeekFragment extends Fragment implements View.OnClickListener
{
private static final String ARG_POSITION = "position";
private int position;
private LinearLayout[] btns;
public static WeekFragment newInstance(int position) {
WeekFragment f = new WeekFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
fillFragment();
}
private void fillFragment()
{
// Irrelevant stuff..
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.week_fragment, container, false);
}
#Override
public void onClick(View v)
{
// Irrelevant stuff
}
public LinearLayout[] getBtns()
{
return btns;
}
public void setBtns(LinearLayout[] btns)
{
this.btns = btns;
}
}
My adapter:
public class WeekAdapter extends FragmentPagerAdapter
{
Calendar cal;
Context context;
SparseArray<Fragment> registeredFragments;
private String[] TITLES = new String[6];
public WeekAdapter(FragmentManager fm, Context context)
{
super(fm);
registeredFragments = new SparseArray<>();
this.context = context;
fillTitles();
}
private void fillTitles()
{
// Fill titles
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
return WeekFragment.newInstance(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
and my activity:
public class MyActivity extends FragmentActivity
{
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WeekAdapter adapter;
private List<DayResumeItem> listDayResumesItems;
private User u;
private View mProgressView;
private View mRotaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rota2);
mProgressView = findViewById(R.id.view_progress);
mRotaView = findViewById(R.id.view_rota);
this.u = this.getIntent().getExtras().getParcelable(getString(R.string.parcel_user));
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
adapter = new WeekAdapter(getSupportFragmentManager(), getApplicationContext());
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is not null. Here I can work, but I don't want to.
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is null and I can't work.
}
#Override
protected void onResume()
{
super.onResume();
getList();
}
}
It is everytime I call adapter.getRegisteredFragment(position) on my activity where it crash because it always return null..
I swear that I've been searching a lot but I'm unable to make it work.
Thank you very much everybody!
I think my problem was that I was calling this adapter.getRegisteredFragment(position) in the onCreate of my activity, and in the onCreate, the viewpager is still not fully loaded and the registeredFragments aren't still instantiated, so the list is still empty..
If you move this callings to another place when the viewpager is fully loaded, it will work.
The items in registeredFragments are initialized in instantiateItem() method, which should be called during the process of drawing views. And this drawing process happens after onCreate()/onResume().
I am not sure what stuff you want to do by getting Fragment in onCreate(), but generally it is not a good idea since the Fragment is not initialized at that moment. You should access the fragment in onPageSelected() as you said.

Data passing between multiple fragment and activity: send different data to activity from multiple fragments

I have two activities, MainActivity, SecondActivity. Main Activity has a button. When I press the button Second Activity starts. Second Activity has 2 fragments, FragmentA and FragmentB. Fragment A has a button (B also), and I want to pass a string from Fragment A or B to Main Activity by clicking the button (Closing second activity).
I have used some references to do my job - When I click the button of Fragment A, second activity closes and a string passed to Main activity. It works But When I click the button of Fragment B (doing the same code as for Fragment A), I got an error,
java.lang.ClassCastException: (packagename).SecondActivity cannot be cast to (packagename).FragmentB$OnDataPass
dataflow:
Fragment A (button click) >> Main Activity (text view) (works)
Fragment B (button click) >> Main Activity (text view) (does not work)
Here is my Fragment A code:
String data ="String from fragment A";
public interface OnDataPass {
public void onDataPass(String data);
}
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_a, container, false);
btn = (Button) view.findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dataPasser.onDataPass(data);
getActivity().finish();
}
});
return view;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
Here is my Fragment B code:
String data ="String from fragment B";
public interface OnDataPass {
public void onDataPass(String data);
}
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a; // Exception occurs here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_b, container, false);
btn = (Button) view.findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dataPasser.onDataPass(data);
getActivity().finish();
}
});
return view;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
My second Activity code:
public class SecondActivity extends FragmentActivity implements OnDataPass {
Button btn1,btn2;
TabHost tabHost;
String dt="";
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_help);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
#Override
public void onDataPass(String data) {
// TODO Auto-generated method stub
Log.d("LOG::","hello " + data);
dt= data;
Intent intent = new Intent();
intent.putExtra("key", dt);
setResult(RESULT_OK, intent);
finish();
//startActivity(intent);
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
// TODO Auto-generated method stub
Fragment fragment=null;
if(i==0) {
fragment = new FragmentA();
}
if(i==1) {
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
if(position == 0) {
return "Tab 1";
}
if(position == 1) {
return "Tab 2";
}
return null;
}
}
What would I need to do to this code to get the string in FragmentB to MainActivity?
Please post code.
You have declared the OnDataPass interface in both Fragment A and Fragment B and I suspect you implemented SecondActivity with OnDataPass interface of Fragment A which You have tried to cast in Fragment B resulted in the exception.
Solution :
Move OnDataPass interface to SecondActivity
Remove OnDataPass interface from Fragment A and Fragment B.
Everything should be fine.

Saving GridView state in a Fragment (Android) on Back Button

In my android application, I am switching between the two set of images-(Set1, Set2) displayed in a GridView-A inside a Fragment-A.I am doing this on a button press using a boolean variable. Clicking on any GridView icon leads to another Fragment-B. The problem is when I press back button on Fragment-B , the Fragment-A is always loaded with the images of Set1 by default. I want the same set of images (Set1 or Set2 ) to be loaded on FramentA that were displayed before going to FragmentB.
EDITED:
Fragment Code
public class GridViewFragment extends Fragment {
Context context;
GridView GridMenu;
GridViewAdapter ga;
Button Btn_Settings;
Button Btn_lang_Ch;
Button favoriteDuas;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fragment = new GridViewFragment();
if (view == null) {
context = inflater.getContext();
view = inflater.inflate(R.layout.fragment_gridview, container, false);
ga = new GridViewAdapter(context);
Btn_lang_Ch = (Button) view.findViewById(R.id.lng_ch);
Btn_Settings = (Button) view.findViewById(R.id.button_settings);
favoriteDuas = (Button) view.findViewById(R.id.btn_favorite_duas);
GridMenu = (GridView) view.findViewById(R.id.gridView1);
GridMenu.setAdapter(ga);
} else {
// remove view from previously attached ViewGroup
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Btn_lang_Ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ga.changeImages(!ga.imageSetChange);
ga.Lang_Status();
}
});
GridMenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
((MainActivity) context).loadSingleDuaFragment();
}
});
super.onActivityCreated(savedInstanceState);
}
}
GridView Adapter
public class GridViewAdapter extends BaseAdapter {
public boolean imageSetChange = false;
public static boolean curr_lang = false;//english
public Integer[] mThumbIds = {
R.drawable.eng_pic1, R.drawable.eng_pic2,
R.drawable.eng_pic3, R.drawable.eng_pic4,
R.drawable.eng_pic5, R.drawable.eng_pic6,
R.drawable.eng_pic7, R.drawable.eng_pic8,
R.drawable.eng_pic9, R.drawable.eng_pic10,
R.drawable.eng_pic11, R.drawable.eng_pic12,
R.drawable.eng_pic13, R.drawable.eng_pic14,
R.drawable.eng_pic15, R.drawable.eng_pic16,
R.drawable.eng_pic17, R.drawable.eng_pic18,
R.drawable.eng_pic19, R.drawable.eng_pic20,
R.drawable.eng_pic21
};
public Integer[] mThumbIds1 = {
R.drawable.urdu_dua1, R.drawable.urdu_dua2,
R.drawable.urdu_dua3, R.drawable.urdu_dua4,
R.drawable.urdu_dua5, R.drawable.urdu_dua6,
R.drawable.urdu_dua7, R.drawable.urdu_dua8,
R.drawable.urdu_dua9, R.drawable.urdu_dua10,
R.drawable.urdu_dua11, R.drawable.urdu_dua12,
R.drawable.urdu_dua13, R.drawable.urdu_dua14,
R.drawable.urdu_dua15, R.drawable.urdu_dua16,
R.drawable.urdu_dua17, R.drawable.urdu_dua18,
R.drawable.urdu_dua19, R.drawable.urdu_dua20,
R.drawable.urdu_dua21
};
private Context mContext;
public GridViewAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View MyView;
if (convertView == null) {
LayoutInflater li = ((Activity) mContext).getLayoutInflater();
MyView = li.inflate(R.layout.menuitem, parent, false);
} else {
MyView = (View) convertView;
}
ImageView iv = (ImageView) MyView.findViewById(R.id.image);
if (imageSetChange) {
iv.setImageResource(mThumbIds1[position]);
} else {
iv.setImageResource(mThumbIds[position]);
}
return MyView;
}
public void changeImages(boolean change) {
this.imageSetChange = change;
notifyDataSetChanged();
// gf.Lang_Status();
}
public void Lang_Status() {
// if curr_eng
if (!curr_lang)
this.curr_lang = true; // change to urdu
// if curr_urdu
else
this.curr_lang = false; // change to english
}
}
EDIT:
MainActivity
public void loadGridViewFragment() {
if (activityActive) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(getSupportFragmentManager().findFragmentByTag(GridViewFragment.TAG)!=null){
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
else
{
frag = new GridViewFragment();
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
ft.commit();
}
}
So, can anybody help me out regarding what should be done to load the previous set of images on coming back to gridview fragment instead of having the default images of Set1.

Nullpoint Exception on image gallery

I'm creating an image gallery application in Android but I gives me a null point exception at run-time. Please help me to correct it. Here is my code
I use Gallery and ImageSwitcher for XML design
I here when user click the gallery images move in animation on ImageSwitcher
public class MainActivity extends Activity implements ViewFactory,OnItemSelectedListener{
private ImageSwitcher mswitcher;
private Integer[] mThimId={R.drawable.fba,R.drawable.fbb,R.drawable.fbc,R.drawable.fbd,R.drawable.fbe,R.drawable.fbf,R.drawable.fbg,R.drawable.fbh,R.drawable.fbi,R.drawable.fbj};
private Integer[] mImageId={R.drawable.fba,R.drawable.fbb,R.drawable.fbc,R.drawable.fbd,R.drawable.fbe,R.drawable.fbf,R.drawable.fbg,R.drawable.fbh,R.drawable.fbi,R.drawable.fbj};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mswitcher=(ImageSwitcher)findViewById(R.id.imageSwitcher1);
mswitcher.setFactory(this);
mswitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
mswitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
Gallery g=(Gallery) findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
#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 void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mswitcher.setImageResource(mImageId[arg2]);
}
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
public ImageAdapter(Context c) {
// TODO Auto-generated constructor stub
mcontext=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThimId.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView i = new ImageView(mcontext);
i.setImageResource(mThimId[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return null;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public View makeView() {
// TODO Auto-generated method stub
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
return null;
}
}
Here is my XML file code
<Gallery
android:id="#+id/gallery1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="36dp" />
<ImageSwitcher
android:id="#+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="159dp"
android:layout_marginLeft="63dp" >
</ImageSwitcher>
You should be returning 'i' instead of null from the getView and makeView methods.

onTouchEvent cannot #Override in fragment

The method onTouchEvent(MotionEvent) of type FindPeopleFragment must override or implement a supertype method.
Is there any way to fix it rather than removing the #Override as i suspect removing it is the cause that make the GestureDetector dont work.
public class FindPeopleFragment extends Fragment implements OnGestureListener{
private GestureDetector gDetector;
ImageView iv1;
public FindPeopleFragment(){}
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
gDetector = new GestureDetector(this);
iv1=(ImageView)rootView.findViewById(R.id.imageView1);
return rootView;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float xVelocity, float yVelocity) {
if (start.getRawY() < finish.getRawY()) {
Log.i("fling", "if");
//((ImageView)findViewById(R.id.image_place_holder)).setImageResource(R.drawable.down);
//startActivity(new Intent(getActivity(),MainActivity.class));
} else {
Log.i("fling", "else");
//((ImageView)findViewById(R.id.image_place_holder)).setImageResource(R.drawable.up);
//startActivity(new Intent(getActivity(),Secc.class));
}
return true;
}
#Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}

Resources