Navigation Drawer AsyncTask - android

I would like to expose my problem and I want to know how I could solve it.
In my application I'm using an activity, making a simple login, launching a asyncTask. At the end of this task, the user is redirected to another activity, which is the home activity of application. The latter has the task of managing a navigation drawer and its fragments. The contents of each fragment must be populated with data retrieved from a server and the navigation drawer set the default fragment F1, which is displayed after the user has logged on.
Now the problem is:
How can I recover the data necessary to populate the listView contained in fragment1?
I know how to implement an adapter for the listView, but I don't understand how to communicate the home activity with the fragment F1. My intention would be to retrieve a circular dialog (content in F1) and run it as long as the data required for the adapter have not been recovered.
Here some code:
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Login().execute();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Login");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (progessDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected Void doInBackground(String... params) {
// code to retrieve data.
}
}
}
public class HomeActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer fragmentDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
fragmentDrawer = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
fragmentDrawer.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fragmentDrawer.setDrawerListener(this);
// Here the problem!!!
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayView(int position) {
switch (position) {
case 0:
Fragment fragmentOne = new FragmentOne();
move(matchFragment);
break;
case 1:
Fragment fragmentTwo = new FragmentTwo();
move(teamFragment);
break;
case 2:
Fragment fragmentThree = new FragmentThree();
move(myTeamFragment);
break;
case 3:
//other fragment....
default:
break;
}
}
public void move (Fragment fragment) {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment, fragment.getClass().getSimpleName());
fragmentTransaction.commit();
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
}
public class FragmentOne extends Fragment {
private ListView listView;
private ArrayList<Info> infos;
private InfoAdapter infoAdapter;
public FragmentOne() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_match, container, false);
listView = (ListView) rootView.findViewById(R.id.match_list_view);
return rootView;
}
}
Now, where do I implement the AsyncTask to retrieve data for adapter? In fragment or the Activity?
If it were the Activity, how can I recover the elements of view of fragment?
Thanks in advance and sorry for bad english.

for your first quesiton:
I don't understand how to communicate the home activity with the
fragment F1
You can pass information from HomeActivity to the Fragment through parameters passed to the Fragment's constructors. So instead of Fragment fragmentOne = new FragmentOne();, you can call Fragment fragmentOne = new FragmentOne(A a); where a is data you want to pass to the fragment. Of course, you need to add in the constructor with parameters to the Fragment class.
For the 2nd point:
Now, where do I implement the AsyncTask to retrieve data for adapter?
In fragment or the Activity? If it were the Activity, how can I
recover the elements of view of fragment?
You can put AsynchTask call inside onCreate() to load data for the listView...etc. Another option which I prefer is to use Loaders. Please see this documentation on Loaders here http://developer.android.com/guide/components/loaders.html. It also has an example.
For explanation and sample, you can follow these 4-part tutorials:
http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html.

Related

When back button is pressed the APP exit. Why?

In my App when i press back button from the following activity doesn't return to main activity(fragment) but the App close.
public class ListaSmartphone extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_smartphone);
Button buttonSP = (Button)findViewById(R.id.buttonXIAOMI);
buttonSP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaSP = new Intent(ListaSmartphone.this, ElencoXiaomi.class);
startActivity(openListaSP);
}
});
Button buttonTB = (Button)findViewById(R.id.buttonMEIZU);
buttonTB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaTB = new Intent(ListaSmartphone.this, ElencoMeizu.class);
startActivity(openListaTB);
}
});
}
}
THIS IS THE MAIN ACTIVITY CODE
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
vpPager.setPageTransformer(true, new RotateUpTransformer());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static final String[] TAB_TITLES = new String[]{"WOW STORE", "PRODOTTI", "SERVIZI", "INFO"};
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentWithZeroImage.newInstance("", R.drawable.wowstorelogo);
case 1:
return FragmentWithOneImage.newInstance("", R.drawable.prodotti);
case 2:
return FragmentWithTwoImages.newInstance("", R.drawable.riparazioni);
case 3:
return FragmentWithThreeImages.newInstance("", R.drawable.info);
default:
return null;
}
}
#Override
public int getCount(){
return TAB_TITLES.length;
}
#Override
public CharSequence getPageTitle(int position){
return TAB_TITLES[position];
}
}
}
The Application works fine, no error but on a devices whe back button is pressed the App exits and doesn't back to MainActivity.
I use Main Activity with four fragments.
While Passing Intent you might have used finish(); after startActivity()
use this code :
#Override
public void onBackPressed() {
this.startActivity(new Intent(ListaSmartphone.this,MainActivity.class));
// super.onBackPressed();
}
and open the fragment in onCreate function of MainActivity
If you want to go back to the MainActivity on back button press then use this code
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}

nested fragment throwing null

The end goal is to click from a list view stored in one fragment,
open another fragment that has a nested fragments view AnswerFragment,
here the nested fragments should consist of two fragments, top portion being the question text from the list and the bottom half being the answer. Right now I've managed to pull off the communication bit of passing the question text from the list to the single question fragment (which should be stored in the top half of the answer fragment) However it's inflating the single question layout over the answer fragment like this SingleQuestionFragment
.
public class MainActivity extends AppCompatActivity implements AllQsFragment.Communicator {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView mNVDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
mDrawer.setDrawerListener(drawerToggle);
//Find our drawer view
mNVDrawer = (NavigationView) findViewById(R.id.nvView);
//Setup drawer view
setupDrawerContent(mNVDrawer);
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
//Creat a new fragment and specify the planet to show based on
//position
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = AllQsFragment.class;
break;
default:
fragmentClass = AllQsFragment.class;
}
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.flContent, fragment).addToBackStack("addedToBackStack").commit();
//Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//The action bar home/up action should open or close the drawer
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//Sync the toggle state after onRestoreInstanceState has occurred
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//Pass any configuration change to the drawer toggles
}
#Override
public void sendText(String data) {
SingleQuestionFragment questionFragment = (SingleQuestionFragment) getSupportFragmentManager().findFragmentByTag("fragmentQ");
if (questionFragment != null) {
questionFragment.changeText(data);
} else {
SingleQuestionFragment fragment = new SingleQuestionFragment();
Bundle args = new Bundle();
args.putString("text", data);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.flContent, fragment)
.addToBackStack(null).commit();
fragment.sentText();
}
}
}
fragment_answer
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.victor.nattest5.AnswerFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/q_fragment">
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/a_fragment">
</FrameLayout>
</LinearLayout>
AnswerFragment
public class AnswerFragment extends Fragment {
public AnswerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
insertNestedFragment();
return inflater.inflate(R.layout.fragment_answer, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void insertNestedFragment() {
Fragment childQFragment = new SingleQuestionFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.q_fragment, childQFragment,
"fragmentQ").commit();
Fragment childAFragment = new SingleAnswerFragment();
FragmentTransaction transaction1 = getChildFragmentManager().beginTransaction();
transaction1.add(R.id.a_fragment, childAFragment, "fragmentA").commit();
}
public static final AnswerFragment newInstance() {
AnswerFragment frag = new AnswerFragment();
return frag;
}
}
SingleQuestionFragment
public class SingleQuestionFragment extends Fragment {
TextView questionTxt;
String stringtext;
public SingleQuestionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_single_question, container, false);
questionTxt = (TextView) v.findViewById(R.id.textView_q);
return v;
}
public static final SingleQuestionFragment newInstance() {
SingleQuestionFragment frag = new SingleQuestionFragment();
return frag;
}
public void changeText(String data) {
questionTxt.setText(data);
}
public void sentText() {
new BackGroundTask().execute();
}
private class BackGroundTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle b = getArguments();
stringtext = b.getString("text");
return null;
}
protected void onPostExecute(String result){
changeText(stringtext);
}
}
}
When I run this with the debugger, the app runs without crashing. However, it shows this line is null ->
SingleQuestionFragment questionFragment = (SingleQuestionFragment) getSupportFragmentManager().findFragmentByTag("fragmentQ");
I know what null means, I just don't understand how to fix this problem. Somewhere in my code I think I'm inflating an extra layout or possibly inflating the wrong container.
It's hard to offer any suggestions because your app is complex and not all of the code is posted. It's also not clear whether any of the posted code includes changes you've made to try and work around the problem. For example, I don't understand the need for BackGroundTask. There is no reason to perform that processing in a background thread. Did you do this as a workaround to add some delay to the processing?
You didn't post the code that calls MainActivity.sendText(), or explain what causes it to be called.
If I understand your post correctly, in sendText(), the call to findFragmentByTag() is returning null and that is an error. Are you expecting to find the SingleQuestionFragment added in AnswerFragment? If so, you won't find it because you are searching the fragments held by the manager of MainActivity only. The search does not include fragments held by the managers of child fragments. In other words, the search does not recursively search the fragment tree.

A resource was acquired at attached stack trace but never released after start splash screen using jeremyfeinstein

currently I need to create an application of wallpaper. I need to start a splash screen before enter into main screen. my main screen is developed using reference from slidingmenu. However, after start splash screen, I have got error below: Please advise and help. Thank you !!
Error after start a fragment activity after run splash screen
E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'end' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at java.util.zip.Inflater.<init>(Inflater.java:82)
at com.android.okio.GzipSource.<init>(GzipSource.java:57)
Splash Screen activity
public class SplashScreen extends SherlockActivity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, FragmentChangeActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
Fragment Activity
public class FragmentChangeActivity extends MainActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super(R.string.changing_fragments);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
if (mContent == null)
mContent = new ColorFragment(R.color.red);
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, mContent)
.commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment())
.commit();
// customize the SlidingMenu
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) {
mContent = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
new AlertDialog.Builder(this)
.setTitle(R.string.share)
.setMessage(Html.fromHtml(getString(R.string.apache_license)))
.show();
break;
case R.id.info:
new AlertDialog.Builder(this)
.setTitle(R.string.info)
.setMessage(Html.fromHtml(getString(R.string.about_msg)))
.show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.example_list, menu);
return true;
}
}
Remove the
public MainActivity(int titleRes) {
mTitleRes = titleRes;
}
Activity classes are instantiated with the no-arg constructor and your activity does not have it. Declaring an explicit constructor prevents the implicit no-arg constructor from being generated.
To pass parameters to activities, use the extras Bundle with the Intent. Start an Activity with a parameter
I am able to display the splash screen now. Here is the code:
public class SplashScreen extends SherlockFragmentActivity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
private PictureFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add the fragment on initial activity setup
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new PictureFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (PictureFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
Here is the code to display splash screen image
public class PictureFragment extends SherlockFragment {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_splash, container, false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(), FragmentChangeActivity.class);
startActivity(i);
getActivity().finish();
}
}, SPLASH_TIME_OUT);
return view;
}
}

How to send data from main activity to fragment

public class MyActivity extends Activity implements ButtonFragement.OnFragmentInteractionListener, TextFragment.OnFragmentInteractionListener,Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ButtonFragement btnfrg=new ButtonFragement();
TextFragment txtfrg= new TextFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.my_activity,btnfrg,"Fragment");
ft.add(R.id.my_activity,txtfrg,"Second Fragment");
ft.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void respond(String data) {
FragmentManager fm=getFragmentManager();
TextFragment f1= (TextFragment) fm.findFragmentById(R.id.textfrg);
f1.changeText(data);
}
}
This is my main_Activity code, here i am trying to send a data over the fragment but it gives me error at f1.changeText(data).Basic structure of my project is , on main Activity , i created two fragment. One with button and another with text. I want to show how many times the button was clicked on second fragment using a communicator interface. Here in "data" counter shows a how many times button was clicked but i am not able to transfer it over second fragment.
Complete Code for the Program---
public interface Communicator {
public void respond(String data);
}
In TextFragment class i added this method----
public void changeText(String data)
{
txt.setText(data);
}
In ButtonFragment class i added and modified following method
public class ButtonFragement extends Fragment implements View.OnClickListener{
int counter=0;
private OnFragmentInteractionListener mListener;
Button btn;
Communicator comm;
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
comm= (Communicator) getActivity();
btn= (Button) getActivity().findViewById(R.id.button);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
counter++;
// comm.respond("The button was clicked "+counter+" times");
comm.respond("hi");
}
Here, i just added which i added in my program. My program get crash at...MainActiviy f1.changeText(data);
But why i am not getting it.Can anyone Help me fixed this bug?
Bundle bundle = new Bundle();
bundle.putString("key", value);
// set Fragmentclass Arguments
YourFragment ff= new YourFragment ();
ff.setArguments(bundle);
transaction.add(R.id.my_activity, ff);
Using Bundle
From Activity:
Bundle bundle = new Bundle();
bundle.putString("message", "Hello!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String myValue = this.getArguments().getString("message");
...
...
}
You have no fragment with id R.id.textfrg.
You are for some reason adding two fragments with id R.id.my_activity. One with tag "Fragment" and another with tag "Second Fragment".
So you are getting error.
Your idea is rigth.
This may be helpfull
TextFragment f1= (TextFragment) fm.findFragmentByTag("Second Fragment");
DO this way:
On Activity Side.
Fragment fragment = new GridTemplate();
Bundle bundle = new Bundle();
bundle.putInt("index",your value);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
here R.id.frame_container is a frame Layout or Relative Layout In which you have to add the fragment.
On Fragment Side.
int index = getArguments().getInt("index");
hope this wil solve your problem. Thanks

Adapt chrisbanes ActionBar-PullToRefresh to Fragments(NavigationDrawer)

Okay here is my problem:
I want to implement Chrisbanes ActionBar-PullToRefresh library with fragments to be able to use it with Navigationdrawer.
https://github.com/chrisbanes/ActionBar-PullToRefresh#fragments
.
Chrisbanes says this for the use with fragments:
One thing to note is that the PullToRefreshAttacher needs to be
created in the onCreate() phase of the Activity. If you plan on using
this library with Fragments then the best practice is for your
Activity to create the PullToRefreshAttacher, and then have your
fragments retrieve it from the Activity.
An example is provided in the Fragment & Tabs sample.
.
.
****Here comes the question:
I created the PullToRefreshAttacher in my activity but how the hell could I pass the PullToRefreshAttacher to my fragments :S****
I have read much about bundles and getArguments() with putSerializable and Parcelable :
Passing an Object from an Activity to a Fragment
and I also read this article in which sth. like this ((MyActivity ) getActivity()).getClassX() ; is used.
Call Activity Method From Fragment
But nothing I really understood/worked. :(
.
.
Here are the NavigationActivity and one example fragment.I have to say that I am new to android/Java :)
final String[] menuEntries = {"Start","Datum","Website","Kunden"};
final String[] fragments = {
"com.blabla.MainFragment",
"com.blabla.OneFragment",
"com.blabla.TwoFragment",
"com.blabla.KundenFragment",
};
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerAdapter;
private ListView navListAdapter;
private PullToRefreshAttacher mPullToRefreshAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_layout);
mPullToRefreshAttacher = PullToRefreshAttacher.get(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, menuEntries);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.refresh_navwiev);
final ListView navList = (ListView) findViewById(R.id.drawerMenu);
drawerAdapter=drawer;
navListAdapter=navList;
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this,
drawer,
R.drawable.navicon,
R.string.drawer_open,
R.string.drawer_close
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
}
};
drawer.setDrawerListener(drawerToggle);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
//Runs On completly Closed
}
});
//Runs Onclick if not same fragment
if(getActionBar().getTitle()!= menuEntries[pos])
{
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
//Fragment zusammenbauen
Fragment myFragment=new Fragment();
myFragment = Fragment.instantiate(NavigationActivity.this, fragments[pos]);
myFragment.setArguments(bundle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.setCustomAnimations(R.anim.fragmentfadein, R.anim.fragmentfadeout);
tx.replace(R.id.navigationScreen, myFragment);
tx.commit();
getActionBar().setTitle(menuEntries[pos]);
drawer.closeDrawer(navList);
}
}
});
Bundle bundle=new Bundle();
// bundle.putInt(PullToRefreshAttacher., position);
//Fragment zusammenbauen
Fragment myFragment=new Fragment();
myFragment = Fragment.instantiate(NavigationActivity.this, fragments[0]);
myFragment.setArguments(bundle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.setCustomAnimations(R.anim.fragmentfadein, R.anim.fragmentfadeout);
tx.replace(R.id.navigationScreen, myFragment);
tx.commit();
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
Log.i("FlosTemplate", "Menu Taste Gedrückt");
if(drawerAdapter.isDrawerOpen(navListAdapter))
{
drawerAdapter.closeDrawer(navListAdapter);
}
else
{
drawerAdapter.openDrawer(navListAdapter);
}
return true;
}
return super.onKeyUp(keyCode, event);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And a fragment
public class MainFragment extends Fragment {
public static Fragment newInstance(Context context) {
MainFragment f = new MainFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
It would be very kind if somebody could help me ,i am stuck at this point for days :)
P.S. sorry for the probably bad language , i am not a native speaker ;)
There is demo code on the GitHub page:
https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/samples/actionbarcompat/src/java/uk/co/senab/actionbarpulltorefresh/samples/actionbarcompat/FragmentTabsActivity.java
Add this to your Activity:
public PullToRefreshAttacher getPullToRefreshAttacher() {
return mPullToRefreshAttacher;
}
And this to the onCreateView in your Fragment:
PullToRefreshAttacher mPullToRefreshAttacher = ((NavigationActivity) getActivity()).getPullToRefreshAttacher();
A better approach would be to use an interface but I'd recommend starting with the GitHub example.

Categories

Resources