public class CoursesActivity extends SherlockFragmentActivity {
ArrayList<CourseData> mCoursesList = new ArrayList<CourseData>();
public CoursesListAdapter coursesListAdapter;
public ListView mList;
public AlertDialog.Builder dlgAlert;
public Dialog loginDialog;
public Dialog loginDialogOverflow;
LinearLayout progressBar;
static SQLiteWebcourse dbHelper;
private GestureDetectorCompat mDetector;
public final static String EXTRA_MESSAGE = "com.technion.coolie.webcourse.MESSAGE";
public CoursesActivity() {
dbHelper = new SQLiteWebcourse(this, "WebcoureDB", null, 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create list of courses
mCoursesList = new ArrayList<CourseData>();
setContentView(R.layout.web_activity_courses);
mList = (ListView) findViewById(R.id.courses_list);
dlgAlert = new AlertDialog.Builder(getApplicationContext());
if (!CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
loginDialog = CoolieAccount.WEBCOURSE.openSigninDialog(this);
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// Check if connection success
if (CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
// Connection SUCCESS
progressBar = (LinearLayout) findViewById(R.id.progressBarLayout_courses);
progressBar.setVisibility(View.VISIBLE);
asyncParse<CourseData> a = new asyncParse<CourseData>() {
#Override
protected List<CourseData> doInBackground(
String... params) {
// TODO Auto-generated method stub
try {
courseList crL = new courseList(
getApplicationContext());
crL.getCourses(CoolieAccount.WEBCOURSE
.getUsername(),
CoolieAccount.WEBCOURSE
.getPassword());
mCoursesList = dbHelper
.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doInBackground(params);
}
#Override
protected void onPostExecute(List<CourseData> result) {
// TODO Auto-generated method stub
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
progressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
};
a.execute("");
} else {
// Connection FAILED
Log.v("dbAss", "Second Time");
}
}
};
loginDialog.setOnDismissListener(dismissListener);
} else {
mCoursesList = dbHelper.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
}
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
// OnItemClickListener itemClicked = new OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> list, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// loadCourseInformationActivity(((CourseData) mList
// .getItemAtPosition(position)).CourseDescription);
// }
// };
// mList.setOnItemClickListener(itemClicked);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.v(DEBUG_TAG,
"onFling: " + event1.toString() + event2.toString());
Toast.makeText(getApplicationContext(), "SWIPED", Toast.LENGTH_LONG)
.show();
if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
Toast.makeText(getApplicationContext(), "SWIPED",
Toast.LENGTH_LONG).show();
// if (showDeleteButton(e1))
// return true;
return super.onFling(event1, event2, velocityX, velocityY);
}
}
}
Hey fellas, i'm trying to implement swipe detection I went through android lesson and did exactly what is written there: http://developer.android.com/training/gestures/detector.html
For some reason when I touch the screen it doesnt go to onTouchEvent. What seems to be the problem?
You haven't set the touch listener to your ListView.
listView.setOnTouchListener(this);
Related
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();
}
I have some code, but the new HTTPRequest().execute(); won't work. What this code should do is use an HTTP GET request and then display the text on the screen (with the line of code card.setText(mResult);). My entire HTTPRequest class may be wrong? Is there a class that exists that I can call to say something like ExampleHTTPGetClass.getURLData("example.com"); I am fairly new to glass development, here is my code I tried to write:
public class MainActivity extends Activity {
private CardScrollView mCardScroller;
private View mView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
mView = buildView();
mCardScroller = new CardScrollView(this);
mCardScroller.setAdapter(new CardScrollAdapter() {
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return mView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return mView;
}
#Override
public int getPosition(Object item) {
if (mView.equals(item)) {
return 0;
}
return AdapterView.INVALID_POSITION;
}
});
// Handle the TAP event.
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Plays disallowed sound to indicate that TAP actions are not supported.
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.playSoundEffect(Sounds.DISALLOWED);
}
});
setContentView(mCardScroller);
new HTTPRequest().execute();
}
private View buildView() {
CardBuilder card = new CardBuilder(this, CardBuilder.Layout.TEXT);
card.setText(mResult);
return card.getView();
}
HttpURLConnection mURLConnection;
String mResult;
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0){
try{
URL url = new URL("http://exampleURL.com");
mURLConnection = (HttpURLConnection)
url.openConnection();
InputStream in = new BufferedInputStream(
mURLConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1){
b.append((char) ch);
}
mResult = new String(b);
Log.d("App", mResult);
} catch (Exception e){}
return null;
}
}
}
Thanks, Ryan.
You call buildView() and setText() before executing the Http request. Add onPostExecute in your AsyncTask and setText there. Try this:
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0){
try{
URL url = new URL("http://exampleURL.com");
mURLConnection = (HttpURLConnection)
url.openConnection();
InputStream in = new BufferedInputStream(
mURLConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1){
b.append((char) ch);
}
mResult = new String(b);
Log.d("App", mResult);
} catch (Exception e){}
return null;
}
#Override
protected void onPostExecute(Void v) {
mView = buildView();
}
}
Also, don't forget to add
<uses-permission android:name="android.permission.INTERNET"/>
in the manifest.
I encounter a problem with my ListFragment provided by Volley Library and hosted by a ViewPager ! So when i swipe follow Fragment and back to my previous ListFragment, datas are repeated again ! Why ? Please help me !
This my code :
Code for bind ListFragment:
public class AllConferencesFragment extends ListFragment {
// Variables
final String URL_ALL_CONFERENCES = "http://192.168.43.246/android_christEvent/all_events_conference.php";
//final String URL_ALL_CONFERENCES = "http://7avecdieu.org/android_christEvent/all_events_conference.php";
//private static String TAG = ConferenceActivity.class.getSimpleName();
ListView listView;
View view;
List<Event> eventLists = new ArrayList<Event>();
CustomListEventsAdapter customListEventsAdapter;
CircularProgressView circularProgressView;
// Contructeur
public AllConferencesFragment() {
}
// Creation du fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Creation de la vue
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.conferences_frag, container, false);
circularProgressView = (CircularProgressView) view.findViewById(R.id.circular_progress);
return view;
}
// Activité gestionnaire du fragment créé
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
circularProgressView.setVisibility(View.VISIBLE);
circularProgressView.startAnimation();
getListView();
//listView = (ListView) view.findViewById(R.id.list);
customListEventsAdapter = new CustomListEventsAdapter(getActivity(), eventLists);
//listView.setAdapter(customListEventsAdapter);
setListAdapter(customListEventsAdapter);
// On check si la cache est vide
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_ALL_CONFERENCES);
if (entry != null) {
circularProgressView.setVisibility(View.VISIBLE);
// Parcours des données de la cache de cette url passée en parametre
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
// Au Cliq sur un iem
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), DetailsEventsActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
/**
* Parsing json reponse and passing the data to event view list adapter
**/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray("events");
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
Event evt = new Event();
evt.setPriceEvent(eventObj.getString("event_price"));
// Image might be null sometimes
String image = eventObj.isNull("event_thumb") ? null : eventObj.getString("event_thumb");
evt.setThumbEvent(image);
evt.setNameEvent(eventObj.getString("event_name"));
evt.setPlaceEvent(eventObj.getString("event_place"));
evt.setHourEvent(eventObj.getString("event_hour"));
evt.setDateEvent(eventObj.getString("event_date"));
eventLists.add(evt);
}
circularProgressView.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//progressBar.setVisibility(View.GONE);
}
}
Code for Volley Application :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if(mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// Set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
My parseJsonEvent :
private void parseJsonEvent(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray(TAG_EVENTS);
// Loop Json node
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
// Create event object
Event evt = new Event();
evt.setIdEvent(eventObj.getInt(TAG_EVENT_ID));
evt.setDateEvent(eventObj.getString(TAG_EVENT_DATE));
evt.setPriceEvent(eventObj.getString(TAG_EVENT_PRICE));
evt.setNameEvent(eventObj.getString(TAG_EVENT_NAME));
evt.setCountryEvent(eventObj.getString(TAG_EVENT_COUNTRY));
evt.setPlaceEvent(eventObj.getString(TAG_EVENT_PLACE));
evt.setTypeEvent(eventObj.getString(TAG_EVENT_TYPE));
// event thumbnail
String eventUrl = eventObj.isNull(TAG_EVENT_THUMB) ? null : eventObj.getString(TAG_EVENT_THUMB);
evt.setThumbEvent(eventUrl);
// Adding in the list object
eventList.add(evt);
// notify list view to adding
}
adapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
My Main Activity :
public class ConferenceActivity extends AppCompatActivity {
private Toolbar toolbarConference;
private TabLayout tabLayoutConference;
private ViewPager viewPagerConference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbarConference = (Toolbar) findViewById(R.id.toolbar_conference);
setSupportActionBar(toolbarConference);
viewPagerConference = (ViewPager) findViewById(R.id.viewpager_conference);
setupViewPager(viewPagerConference);
tabLayoutConference = (TabLayout) findViewById(R.id.tabs_conference);
tabLayoutConference.setupWithViewPager(viewPagerConference);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AllEventsConferenceFragments(), "TOUS");
adapter.addFragment(new ThisWeekFragment(), "AUJOURD'HUI");
adapter.addFragment(new TodayEventFragment(), "CETTE SEMAINE");
adapter.addFragment(new AllEventsConferenceFragments(), "SEMAINE PROCHAINE");
adapter.addFragment(new ThisWeekFragment(), "CE MOIS CI");
adapter.addFragment(new TodayEventFragment(), "MOIS PROCHAIN");
adapter.addFragment(new AllEventsConferenceFragments(), "ANNEE EN COURS");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class AllConferencesFragment extends ListFragment {
private boolean loaded = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(loaded){
return;
}
loaded = true;
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
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.
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