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

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.

Related

How to pass retrofit data in bundle to view pager fragments from activity?

In my activity i am receiving a game id from previous activity and using this id i am getting list of data from api. The method ("ApiCheats") in activity is used to get lis t of data.
I want to pass this list to my fragment in view pager, for this i used bundle but in fragment the bundle is null.
How should i pass bundle list to fragment , this data i am receiving through retrofit.
This is the Activity
public class GameListCheatsActivity extends AppCompatActivity {
private final String TAG = GameListCheatsActivity.class.getSimpleName();
public List<Cheats> Cheats;
ArrayList cheats = new ArrayList<Cheats>();
// public RecyclerView recyclerView;
String Gameid;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list_cheats);
// recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setHasFixedSize(true);
Gameid = getIntent().getStringExtra("GameID");
tabLayout = (TabLayout) findViewById(R.id.tab_layout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter( getSupportFragmentManager());
ApiCheats();
adapter.AddFragment(new Fragment_Cheats(),"GameCheats");
adapter.AddFragment(new Fragment_Favourites(),"Favourites");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == 0){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
if(state == 1){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
}
});
}
public void ApiCheats()
{
ApiUtil.getServiceClass().getAllCheats(Gameid).enqueue(new Callback<List<Cheats>>() {
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("cheatslist", (ArrayList<? extends Parcelable>) Cheats);
Fragment_Cheats fragment_cheats = new Fragment_Cheats();
fragment_cheats.setArguments(bundle);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
#Override
public void onFailure(Call<List<Cheats>> call, Throwable t) {
Log.d(TAG, "error loading from API");
}
});
}
}
this is one of the fragments class
public class Fragment_Cheats extends Fragment {
View v;
private RecyclerView mrecyclerview;
private List<Cheats> lstGameCheats;
public Fragment_Cheats()
{
}
// #Override
// public void onCreate(#Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// lstGameCheats = bundle.getParcelable("cheatslist");
// }
//
// }
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_fragment__cheats, container, false);
mrecyclerview = (RecyclerView)v.findViewById(R.id.recyclerview_cheats);
Bundle bundle = this.getArguments();
if (bundle != null) {
lstGameCheats = bundle.getParcelable("cheatslist");
}
CheatsAdapter recyclerAdapter = new CheatsAdapter(getContext(),lstGameCheats);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerview.setAdapter(recyclerAdapter);
return v;
}
}
this is view pager adapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
//return null;
}
#Override
public int getCount() {
return lstTitles.size();
//return 0;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment,String title){
lstFragment.add(fragment);
lstTitles.add(title);
}
}
You should set the Cheats to the Fragment which have added to your ViewPagerAdater, but according to your code you just set the data to a new fragment instance.
According to the Fragment_Cheats code, if you want to invoke getArgument() in onCreate() method, you should invoke fragment.setArgument() before the fragment add to the ViewPagerAdapter.
But in your situation it is not possible, because the data get from the network.
So, two step
Set data to the correct Fragment_Cheats instance
Notify Fragment_Cheats data changed, refresh the View state in the fragment
Replace your onResponse()
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Fragment_Cheats fragment_cheats = adapter.getCheatFragment()
fragment_cheats.setDatas(Cheats);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
Fragment_Cheats add setDatas() method
public void setDatas(List<Cheats> datas) {
this.lstGameCheats = datas;
// and set the datas to the RecylerView adapter
recyclerviewAdapter.notifyDataSetChanged();
}

Android Code for Refresh Button that destroys and recreates Text MediaPlayer (Hangs)!

viewPager4 Fragment Activities
If I click on the Texts that play short sounds, one after another then after sometimes the mediaplayer hangs and doesn't play any sound. But if I'm able to destroy activity and recreate the same activity with refresh button in Action Bar, I'd be able to click sounds again.
So what to write in the code for R.id.item2?
Or there is any other way that continuous clicking on short sounds by these texts is possible without any hang kind of problem?
Following is the reference code:
public class module1 extends FragmentActivity {
static Context con;
static int length = 0;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
static MediaPlayer mediaplayer, mediaplayert, m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mains, menu);
// Just .main into .mains [created new for different behavior of Action Bar]
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(in);
}
if (item.getItemId() == R.id.item2) {
//what should i write here? to destroy and recreate the same fragment activity again.
//Problem: After clicking fast on one after another text links, mediaplayert hangs and doesnt play
//Solution: exit app destroy and reopen, then mediaplayer works fine...
//SO, what to write here? kindly help!
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment ff = new DummySectionFragment1();
switch (arg0) {
case 0:
ff = new DummySectionFragment1();
break;
}
Bundle args = new Bundle();
args.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, arg0 + 1);
ff.setArguments(args);
return ff;
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int arg0) {
Locale l = Locale.getDefault();
switch (arg0) {
case 0:
return getString(R.string.title_section27).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment1 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.m01set01, container, false);
// Genius Shot by Stupid vIC//
TextView Text = (TextView) rootView.findViewById(R.id.textView2);
Text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound1);
mediaplayert.start();
}
});
TextView Text1 = (TextView) rootView.findViewById(R.id.textView4);
Text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound2);
mediaplayert.start();
}
});
TextView Text2 = (TextView) rootView.findViewById(R.id.textView6);
Text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound3);
mediaplayert.start();
}
});
return rootView;
}
}
#Override
protected void onDestroy() {
if (mediaplayert != null) {
mediaplayert.stop();
mediaplayert= null;
}
super.onDestroy();
}
}

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.

Android annotations #afterviews called multiple times when fragment added

I have a fragment that whenever it is added to the layout #afterviews is called.
So for example in the parent activity I check if the fragment has been created, if not inflate it. Then I check if the fragment is added to the layout, if not add it and show the new fragment
#Click(R.id.tvActionFriends)
void friendsClicked() {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (friendsFragment == null) {
friendsFragment = new FriendsFragment_();
}
if (!friendsFragment.isAdded()) {
app.log("not added adding fragment");
fragmentTransaction.add(R.id.layoutMainContainer, friendsFragment);
}
fragmentTransaction.show(friendsFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
The first time its clickd it goes through the lifecycle normally.
So now the user has pressed the back button I can see the teardown onPause() onDestroy() and onDetach()
So now the friendsFragment is removed from the layout but the class still exists.
Now the user clicks on a button again to show the friendsFragment, in the host activity. This time the fragment already exists but is not in layout so it is re added and transaction commits
now the fragment goes through the lifecycle of creation but #afterviews method is triggered twice, if a user hits back again and clicks the button a third time #afterviews will be triggered 3 times etc...
Here is the friendsFragment
#EFragment(R.layout.fragment_friends)
public class FriendsFragment extends BaseFragment {
ArrayList<String> numbers, facebookIds, emails;
ArrayList<Friend> friends;
#Bean
FriendsAdapter friendsAdapter;
#ViewById(R.id.lvFriends)
CustomListView lvFriends;
boolean gettingFriends = false;
#AfterInject
void initInject() {
super.baseInject();
numbers = new ArrayList<String>();
facebookIds = new ArrayList<String>();
friends = new ArrayList<Friend>();
friendsAdapter.setItems(friends);
}
#AfterViews
void initViews() {
super.baseViews();
lvFriends.setAdapter(friendsAdapter);
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("+", "");
numbers.add(phoneNumber);
}
}
phones.close();
getFriends();
}
OnFriendsListener onFriendsListener = new OnFriendsListener() {
#Override
public void onComplete(List<Profile> friends) {
for (Profile p : friends) {
app.log(p.getName());
}
}
#Override
public void onException(Throwable throwable) {
app.log(throwable.getMessage());
};
#Override
public void onFail(String reason) {
app.log(reason);
}
};
#Background
void getFriends() {
if (gettingFriends == true)
return;
gettingFriends = true;
friends.clear();
MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
data.add("numbers", numbers.toString());
data.add("facebook_ids", facebookIds.toString());
ArrayList<Friend> resp = snapClient.recommendFriends(data);
friendsCallback(resp);
}
#UiThread
void friendsCallback(ArrayList<Friend> resp) {
if (resp != null)
friends.addAll(resp);
friendsAdapter.notifyDataSetChanged();
gettingFriends = false;
}
}
As you can see the fragment extends a basefragment and calls the parent super.baseInject() and super.baseViews() to handle common class fields across all fragments
the base fragment looks like this, it basically just injects a few classes and logs the activity lifecycle of the fragment
#EFragment
public class BaseFragment extends Fragment {
#App
MyApp app;
#SystemService
LayoutInflater layoutInflater;
#Bean
VideoCache videoCache;
#RestService
CloudClient cloudClient;
#Bean
MyResources myResources;
#ViewById(R.id.tvActionExtra)
TextView tvActionExtra;
SnapClient snapClient;
FragmentManager fragmentManager;
SimpleFacebook simpleFacebook;
void baseInject() {
app.log("init inject " + this.getClass().getCanonicalName());
app.currentContext = getActivity();
snapClient = app.snapClient;
}
void baseViews() {
app.log("init views " + this.getClass().getCanonicalName());
}
#Override
public void onAttach(Activity activity) {
Log.d(MyApp.TAG,"attach " + this.getClass().getCanonicalName());
super.onAttach(activity);
if (activity instanceof MainActivity) {
try {
MainActivity a = (MainActivity) activity;
simpleFacebook = a.simpleFacebook;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
void toast(String message) {
app.toast(message);
}
AlertDialog simpleAlert(String title, String message) {
return MyApp.simpleAlert(getActivity(), title, message);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(MyApp.TAG,"create " + this.getClass().getCanonicalName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(MyApp.TAG,"create view " + this.getClass().getCanonicalName());
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onPause() {
Log.d(MyApp.TAG,"pause" + this.getClass().getCanonicalName());;
super.onPause();
}
#Override
public void onResume() {
Log.d(MyApp.TAG,"resume " + this.getClass().getCanonicalName());
super.onResume();
}
#Override
public void onDetach() {
Log.d(MyApp.TAG,"detach " + this.getClass().getCanonicalName());
super.onDetach();
}
#Override
public void onDestroy() {
Log.d(MyApp.TAG,"destroy " + this.getClass().getCanonicalName());
super.onDestroy();
}
}
I dont' know if its an android annotation thing im messing up or something with the fragments, any help is appreciated.
It looks like this may be fixed in AndroidAnnotations 3.3?
There was a pull request at https://github.com/excilys/androidannotations/pull/1275, based on an issue at https://github.com/excilys/androidannotations/issues/1264.

Close Soft Keyboard in Fragment

I have a fragment that has a SearchView. When I click in the search box the keyboard appears. I enter a search term and press "Enter" the keyboard disappears and I get my results page. When I choose an item in my list of results I am taken back to the search fragment and the keyboard reappears. How to I not have the keyboard reappear? Here is part of my code:
public class LocationFragment extends ListFragment implements OnItemLongClickListener, OnClickListener{
// ===========================================================
// Constants
// ===========================================================
private static final int BTN_ID = 0x5f000001;
private static final String DEBUG_TAG = "Tablet/LocationFragment";
// ===========================================================
// Fields
// ===========================================================
private int pos;
private int mPositionToDelete = 0;
private FragmentListener listener;
private Activity mActivity;
// ===========================================================
// Lifecycle
// ===========================================================
#Override
public void onAttach(Activity activity) {
mActivity = activity;
super.onAttach(activity);
try {
listener = (FragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement Fragment");
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View v = inflater.inflate(R.layout.locations_tile, null);
SearchManager sm = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
final SearchView sv = (SearchView)v.findViewById(R.id.search_view);
sv.setSearchableInfo(sm.getSearchableInfo(getActivity().getComponentName()));
sv.setSubmitButtonEnabled(true);
consumeKeyUp(sv);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(pos, true);
lv.setSelector(R.xml.location_select_gradient);
lv.setCacheColorHint(0x00000000);
lv.setSelector(R.drawable.list_item_selector);
lv.setOnItemLongClickListener(this);
lv.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
// Log.i(DEBUG_TAG, "onkeyDown");
return !(lv.getSelectedItemPosition() < lv.getCount() - 1);
case KeyEvent.KEYCODE_DPAD_UP:
// Log.i(DEBUG_TAG, "onkey up");
if(lv.getSelectedItemPosition() == 0) {
// Log.i(DEBUG_TAG, " requesting for search focused");
return LocationFragment.this.getView().findViewById(R.id.search_view).requestFocus();
} else return false;
case KeyEvent.KEYCODE_DPAD_RIGHT:
Log.i(DEBUG_TAG, "KEYCODE_DPAD_RIGHT");
return true;
}
return false;
}
return false;
}
});
ImageView closeBtn = (ImageView) getView().findViewById(R.id.locationsCloseButton);
closeBtn.setOnClickListener(this);
closeBtn.setFocusable(true);
closeBtn.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
Log.i(DEBUG_TAG, "keypad Center");
return false;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
return !(KeyEvent.KEYCODE_DPAD_DOWN == keyCode);
}
return false;
}
});
} else {
v.setOnKeyListener(null);
}
}
});
}
You could trying clearing the search view focus in your list click callback, e.g. sv.clearFocus()
I grab the search view to do this in OnCreateOptionsMenu using getActionView() on the MenuItem.
Incidentally I also call the following on my search view in onCreateOptionsMenu
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemServiceContext.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
To be honest though I find the whole are of soft input keyboards a bit of a black art
private SearchView mSearchView;
...
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
// Associate search able configuration with the SearchView
android.app.SearchManager searchManager = (android.app.SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu(menu);
}
private result() {
mSearchView.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}
don't use startSearch or onSearchRequested

Resources