I'm a beginner with java and android development but managed to create a navigation drawer activity which switches between five fragment with ListViews using AsycTask. The AsycTask starts again when ever I switch between the fragments. I have gone through many of the post here but none seems to work. Any help.
Here is My Navigation Drawer Activity
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static String website = "https://www.website.com", fbPage = "https://www.facebook.com",
twitter = "https://twitter.com",
private android.support.v4.app.FragmentManager fragmentManager;
private android.support.v4.app.FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_holder, new HomeFragment(), "Home Fragment")
.commit();
fragmentManager = getSupportFragmentManager();
}
private void customNavgation() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, homeFragment, "HomeFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_message) {
MessageFragment messageFragment = new MessageFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, messageFragment, "MessageFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_word) {
WordFragment wordFragment = new WordFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, wordFragment, "WordFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_events) {
EventsFragment eventsFragment = new EventsFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, eventsFragment, "EventsFrangment");
fragmentTransaction.commit();
} else if (id == R.id.nav_service) {
ServiceFragment serviceFragment = new ServiceFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, serviceFragment, "Service Fragment");
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And here is one of my Fragment class
public class EventsFragment extends Fragment {
ArrayList<EventsFields> eventsFieldsList;
private ListView eventlist;
static final String EVENT_LINK = "http:www.website.com";
private ProgressBar pb;
private View view;
public EventsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_events, container, false);
eventlist = (ListView) view.findViewById(R.id.event_frag_listView);
pb = (ProgressBar) view.findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
if (isOnline()) {
requestData(EVENT_LINK);
} else {
Toast.makeText(EventsFragment.this.getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
return view;
}
protected void updateDisplay() {
EventsListAdapter adapter = new EventsListAdapter(EventsFragment.this.getActivity(), R.layout.event_list_layout, eventsFieldsList);
eventlist.setAdapter(adapter);
eventlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventsFragment.this.getActivity(), EventDetail.class);
EventsFields selectedEvent = eventsFieldsList.get(position);
intent.putExtra("selectedEvent", selectedEvent);
startActivity(intent);
}
});
}
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public class MyTask extends AsyncTask<String, String, ArrayList<EventsFields>> {
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<EventsFields> doInBackground(String... params) {
String data = HttpManager.getData(params[0]);
eventsFieldsList = EventsJsonParser.parseFeed(data);
return eventsFieldsList;
}
#Override
protected void onPostExecute(ArrayList<EventsFields> results) {
pb.setVisibility(View.INVISIBLE);
if (results == null) {
Toast.makeText(EventsFragment.this.getActivity(), "Web service not available", Toast.LENGTH_LONG).show();
return;
}
eventsFieldsList = results;
updateDisplay();
}
}
JsonPaser Class
public class EventsJsonParser {
public static ArrayList<EventsFields> parseFeed(String content) {
try {
JSONArray ar = new JSONArray(content);
ArrayList<EventsFields> eventList = new ArrayList<>();
for (int i = 0; i < ar.length(); i++) {
JSONObject obj = ar.getJSONObject(i);
EventsFields events = new EventsFields(null);
events.setId(obj.getInt("id"));
events.setEventName(obj.getString("EventName"));
events.setStartDate(obj.getString("StartDate"));
events.setEventDesc(obj.getString("EventDesc"));
events.setTime(obj.getString("Time"));
events.setVenue(obj.getString("Venue"));
eventList.add(events);
}
return eventList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Thanks
One approach is to persist the data and then don't call the AsyncTask if you've already received the data.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("eventsFieldsList", eventsFieldsList);
super.onSaveInstanceState(outState);
}
then in onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_events, container, false);
eventlist = (ListView) view.findViewById(R.id.event_frag_listView);
pb = (ProgressBar) view.findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
if (savedInstanceState != null) {
eventsFieldsList = savedInstanceState.getParcelableArrayList("eventsFieldsList");
}
if (eventsFieldList == null) {
if (isOnline()) {
requestData(EVENT_LINK);
} else {
Toast.makeText(EventsFragment.this.getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
return view;
}
You would need to make your EventsFields class implement Parcelable. There are lots of online tutorials and SO answers on this. If you have problems with implementing Parcelable, post a new question.
Related
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.page__navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
I read data from json file to an adapter and in the main.java under oncreate, when I try runing it,it doest show anything.
I tried the same code under menu onclick and it works, I want it to appear when the app is first runed.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String url = "myjsonurl.php";
JSONArray jArray;
ProgressDialog dialog;
ListView mycustomlist = null;
WebView mywebview =null;
CustomAdapter myadapter = null;
ArrayList<news> mydatalist = new ArrayList<news>();
ArrayList<news> maşetData = new ArrayList<news>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading....");
dialog.show();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
dialog.cancel();
}
});
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void parseJsonData(final String jsonString) {
try {
jArray = new JSONArray(jsonString);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
news news1 = new news();
news1.setTitle(jObject.getString("title"));
news1.setContent(Html.fromHtml(jObject.getString("content")));
news1.setDate(jObject.getString("date"));
news1.setImage("http://www.bolgegundem.com/d/news/" + jObject.getString("image").concat(".jpg"));
news1.setId(jObject.getString("id"));
news1.setCategory(jObject.getString("category"));
news1.set__comment_count(jObject.getString("__comment_count"));
news1.setHeadline(jObject.getString("headline"));
mydatalist.add(news1);
// http://www.bolgegundem.com/d/gallery/81_2.jpg
/* images.add("http://www.bolgegundem.com/d/gallery/" + id + "_" + imgUrl.replace(",", ".jpg") );*/
// al.add(title);
//imagelinks[i] = "http://www.bolgegundem.com/d/gallery/" + id + "_" + i + ".jpg";
}
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, al);
//listview.setAdapter(adapter);
// listview.setBackgroundColor(rgb(0, 255, 255));
/* listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i < links.length){
Uri uri = Uri.parse(links[i]);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
});*/
if (dialog.isShowing()){
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.manşet) {
// Handle the camera action
} else if (id == R.id.Anasayfa) {
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
} else if (id == R.id.ajansTv) {
} else if (id == R.id.foto) {
} else if (id == R.id.gundem) {
} else if (id == R.id.siyaset) {
}else if (id ==R.id.Ekonomi ){
}else if (id ==R.id.spor ){
}else if (id ==R.id.saglik ){
}else if (id ==R.id.nav_share ){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My adapter class is here
public class CustomAdapter extends BaseAdapter {
Context mycontext = null;
ArrayList<news> mydatalist;
public CustomAdapter(Context mycontext, ArrayList<news> mydatalist)
{
this.mycontext = mycontext;
this.mydatalist = mydatalist;
}
#Override
public int getCount() {
return this.mydatalist.size();
}
#Override
public Object getItem(int position) {
return this.mydatalist.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater = (LayoutInflater)mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder myholder = null;
if(convertView == null)
{
convertView = myinflater.inflate(R.layout.customlayout, null);
myholder = new ViewHolder();
myholder.mytextview1 = (TextView)convertView.findViewById(R.id.mytextview1);
myholder.mytextview2 = (TextView)convertView.findViewById(R.id.mytextview2);
myholder.mytextview3 = (TextView)convertView.findViewById(R.id.mytextview3);
myholder.myimageview1 = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(myholder);
}
else
{
myholder = (ViewHolder)convertView.getTag();
}
myholder.mytextview1.setText(mydatalist.get(position).getTitle());
myholder.mytextview2.setText(mydatalist.get(position).getContent());
myholder.mytextview3.setText(mydatalist.get(position).getDate());
myholder.myimageview1.setImageResource(R.drawable.bolgegundem);
new DownloadImageTask(myholder.myimageview1).execute(mydatalist.get(position).getImage());
return convertView;
}
static class ViewHolder
{
public TextView mytextview1;
public TextView mytextview2;
public TextView mytextview3;
public ImageView myimageview1;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
How can I solve this?
Put the three lines
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
in this method:
#Override
public void onResponse(String string) {
parseJsonData(string);
// put them here
}
This will work because it populates the list after the data is parsed add then adds it to the adapter. If you add the list to the adapter in OnCreate, the onResponse method will run later (when the data is returned) and the list will be empty.
you need to create fragments for every item which you declare in navigation and do parsing and all thing in it and that fragment is called from onNavigationItemSelected and if you want which is always show first than you have to call it in also from onCreate() method.
I am building an OpenGL live wallpaper. I decided to have a Navigation Drawer in my main activity since there are a lot of features the user will have access to.
The problem/issue
If I press the "hardware" back button to normally close an app the initial fragment that is shown just refreshes and the app never closes. If I hit the home button and go back to the app everything is a black screen. I've searched all throughout Google thinking that maybe I wasn't destroying the MainActivity properly or for a way to terminate a fragment. I've tried calling finish() in the main activity's onDestroy method. I've tried utilizing the remove method from fragment manager in each fragments onDetach method per posts that I've found online. Nothing has worked. I'm stumped. I've set debug points in the main activity on the onDestroy method and on the fragments onDetach method with no error being produced or any information being given. At this point I am clueless. Here's my MainActivity class.
public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
TextView usrTag, tagrEmail;
CircleImageView tagrPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
usrTag = (TextView)header.findViewById(R.id.usrName);
tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);
Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));
usrTag.setText(getUserName(getBaseContext()));
tagrEmail.setText(getUserEmail(getBaseContext()));
GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragmentClass = PreviewFragment.class;
} else if (id == R.id.nav_custom) {
startCustomLabelCreator();
} else if (id == R.id.nav_mylabels) {
} else if (id == R.id.nav_commLabels) {
fragmentClass = PostsFragment.class;
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCustomLabelCreator(){
Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
startActivity(cLC);
}
#Override
public void onPostComment(String postKey) {
}
#Override
public void onPostLike(String postKey) {
}
#Override
public void onPhotoSelected(String photoUrl) {
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
My Fragments
public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance() {
PostsFragment fragment = new PostsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
Query allPostsQuery = FirebaseUtil.getPostsRef();
mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
// TODO: Refresh feed view.
}
});
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
// FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
Log.d(TAG, post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
#Override
public void savePhotoUrl() {
//mListener.onPhotoSelected(post.getFull_url());
showLabelConfirm(post.getFull_url());
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
#Override
public void onSelectedPhoto(String selectPhoto) {
mListener.onPhotoSelected(selectPhoto);
}
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
void onPhotoSelected(String photoUrl);
}
private void showLabelConfirm(String uriBmp) {
FragmentManager fm = getFragmentManager();
PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
// SETS the target fragment for use later when sending results
editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
editNameDialogFragment.show(fm, "fragment_edit_name");
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Second Fragment:
public class PreviewFragment extends RajBaseFragment {
#Override
public ISurfaceRenderer createRenderer() {
return new PreviewRenderer(getContext());
}
}
Which extends:
public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {
protected FrameLayout mLayout;
protected ISurface mRajawaliSurface;
protected ISurfaceRenderer mRenderer;
public RajBaseFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the view
mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);
mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();
// Find the TextureView
mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);
// Create the loader
mRenderer = createRenderer();
onBeforeApplyRenderer();
applyRenderer();
return mLayout;
}
protected void onBeforeApplyRenderer() {
}
protected void applyRenderer() {
mRajawaliSurface.setSurfaceRenderer(mRenderer);
}
#Override
public void onClick(View v) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mLayout != null)
mLayout.removeView((View) mRajawaliSurface);
}
#Override
public int getLayoutID() {
return R.layout.rajawali_textureview_fragment;
}
}
I've tried all the recommendations below so far and the primary fragment that is set in the MainActivity's onCreate method still gets refreshed/reloaded when the back button is pressed rather than the app exiting/closing.
In your onNavigationItemSelected method, you are replacing the current fragment with fragment even in cases where fragment is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
with this one:
if (fragmentClass != null) {
fragment = fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish in the onDestroy method, which probably is not causing the problem but should be taken out because it does not make any sense there.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with addToBackStack, this allows back
navigation for added fragment.Because of fragment in backstack,
empty(black) activity layout will be displayed.
Change onBackPressed() as below which automatically close app after if no any Fragment found in FragmentManager:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
}
}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
Fragment pressing back button
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.
Try this code, hope this helps you, take necessary stuffs which are required for you. Also, try running this project in Android studio, it works.
https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java
When user press to back button it'll check fragment manager's backstack and if backstack entity count is bigger than 0 (this means there's a fragment in backstack) it'll popBackStack else it'll finish activity.
If you add your initial fragment to backstack, when user press back button they'll see a blank screen.
Also when you init your activity if you need to put a fragment it's a best practice to check if saved instance state is null. Here i modified some part of your code.
if(savedInstanceState == null){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}
I hope this'll help you. If you still have problem let me know.
Good luck.
create subclass for ISurface and override onKeyDown method like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Custom View", "onKeyDown");
//return super.onKeyDown(keyCode, event);
return false;
}
Could be related with the lifecycle...
Try using GLSurfaceView. I believe is easier for what you want, is special for OpenGL rendering and there is plenty information about it. Examples, lifecycle among others. Let me know if helped. If not, please, provide more info.
I'm getting null from the args in MyListFragment,
cant figure out why.
Basically what I'm trying to do is get a location from a Map
and replace the old fragment with a new one which has updated location,
MyListFragmnet is a "default" fragment in the NavigationDrawerActivity
//MyListFragment.java
public static MyListFragment newInstance() {
Bundle args = new Bundle();
return newInstance(args);
}
public static MyListFragment newInstance(Bundle args) {
MyListFragment fragment = new MyListFragment();
fragment.setArguments(args);
return fragment;
}
public MyListFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.setHasOptionsMenu(true);
Bundle args = getArguments();
searchQuery = args.getString(SEARCH_QUERY_ARG, ""); //NULL ERROR!!
final MyLocation checkLocation = (MyLocation) args.getSerializable(LOCATION_ARG);
if (!searchQuery.isEmpty()) {
activity.setTitle("\""+searchQuery+"\"");
}
setLocation(checkLocation);
............
private void setLocation(final MyLocation checkLocation) {
if (checkLocation != null) {
// If no location is set and there is a check
location = new Location("");
location.setLatitude(checkLocation.latitude);
location.setLongitude(checkLocation.longitude);
} else {
// If no location was provided, get the current one
location = LocationHelper.getInstance().getLocation(context);
}
}
//NavigationDrawerActivity.java
public class NavigationDrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navLayout;
//Location
private MyLocation checkLocation;
private boolean active;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setupReferences();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
try {
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setSubtitle(getString(R.string.subtitle));
actionBar.setDisplayShowTitleEnabled(true);
} catch (Exception ignored) {
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navLayout= (NavigationView)findViewById(R.id.navLayout);
navLayout.setNavigationItemSelectedListener(this);
active = false;
checkLocation = (MyLocation) getIntent().getSerializableExtra(MyListFragment.LOCATION_ARG);
handleIntent(getIntent());
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.frameLayout, new MyListFragment());
tx.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case R.id.navigation_item_1:
break;
case R.id.navigation_item_2:
break;
case R.id.navigation_item_3:
break;
}
return false;
}
#Override
protected void onNewIntent(Intent intent) {
if (active) {
// Only handles the Intent again if the Activity was already active
handleIntent(intent);
}
}
#Override
public void startActivity(Intent intent) {
super.startActivity(intent);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
intent.putExtra(MyListFragment.LOCATION_ARG, checkLocation);
}
active = true;
}
private void handleIntent(Intent intent) {
Bundle args = new Bundle();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String searchQuery = intent.getStringExtra(SearchManager.QUERY);
args.putString(MyListFragment.SEARCH_QUERY_ARG, searchQuery);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
} else if (MyListFragment.ACTION_CHECK.equals(intent.getAction())) {
checkLocation = (MyLocation) intent.getSerializableExtra(LocationActivity.EXTRA_LOCATION);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, MyListFragment.newInstance(args)).commit();
}
}
Please Help! Thanks.
You are not using MyListFragment.newInstance() but simply calling new MyListFragment()
this line
tx.replace(R.id.frameLayout, new MyListFragment());
should be
tx.replace(R.id.frameLayout, MyListFragment.newInstance());
Here:
...
tx.replace(R.id.frameLayout, new MyListFragment());
...
Not passing any bundle when creating object of MyListFragment Fragment.
Do it by calling newInstance(Bundle args) static method for getting Fragment object.
Bundle bundle = new Bundle();
bundle.putString(SEARCH_QUERY_ARG, "data_here");
...
tx.replace(R.id.frameLayout, new MyListFragment.newInstance(bundle));
...
I am doing an Android app using fragments but i haven't previously experience with fragments.
I have a main FragmentActivity where i load a main view and i call my fragment class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
FragmentTransaction FT = getFragmentManager().beginTransaction();
if (findViewById(R.id.fragmentAction) != null) {
FT.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), getApplicationContext()));
}
FT.addToBackStack(null);
FT.commit();
}
#Override
public void onBackPressed() {
}
And this is my fragmet classm where when i push button call to other fragment:
public class MainMenuFragment extends Fragment {
private static String my_description = "";
private static Context my_context = null;
public static MainMenuFragment newInstance(String description,
Context context) {
my_description = description;
my_context = context;
MainMenuFragment f = new MainMenuFragment();
return f;
}
public MainMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = null;
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
view = inflater.inflate(R.layout.main_menu, container, false);
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
Button new_user = (Button) getView().findViewById(
R.id.button_newUser);
new_user.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction FT = getFragmentManager()
.beginTransaction();
FT.replace(R.id.fragmentAction, LdapFragment.newInstance(
getString(R.string.new_user), my_context));
FT.commit();
}
});
}
}
}
My question is: how can i do to return to previously fragment when i push back key? I add onBackPressed function in my FragmentActivity and capture the event, but what have i to do?
Use this code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(
R.id.fragment_container);
setFragName("NONE");
if (currentFrag != null) {
setFragName(currentFrag.getClass().getSimpleName());
}
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commit();
}
following is the code that i use. You need not do anything. Android system handles backpress and shows the appropriate fragment in the navigation order
#Override
public void onBackPressed() {
super.onBackPressed();
if (getFragmentManager().getBackStackEntryCount() == 0)
finish();
}
you missed the super.onBackPressed(); call. Try adding that to your code.
Just create method for add and back to fragment .
for example,
public void setFragment(Fragment fragment, boolean backStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (backStack) {
fragmentTransaction.addToBackStack(tag);
}
fragmentTransaction.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), tag);
fragmentTransaction.commit();
}
call method from onCreate() or onResume()of your Activity.
setFragment(Your FragmentClass object, true, "tag");