i'm fairly new to Android and got a problem.
When i'm trying to append a item to my list, it' overwriting the list instead of appending.
Here is my fragment call
Activity:
FoodSearchFragmentContainer fragment = FoodSearchFragmentContainer.newInstance();
Bundle bundle = new Bundle();
bundle.putString("query", query);
fragment.setArguments(bundle);
android.app.FragmentTransaction ft = this.getFragmentManager().beginTransaction();
ft.add(R.id.frFoodSearch, new FoodSearchFragmentContainer());
ft.commit();
My Dialog (fragment)
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.measurements_array,
android.R.layout.simple_spinner_item);
The list appender (fragment) FoodSearchFragmentContainer
listView = (ListView) view.findViewById(R.id.lvIngredients);
Ingredients i = new Ingredients();
listView.setAdapter(adapter);
i.setName("test");
ingredients.add(i);
adapter.notifyDataSetChanged();
The order is: i call the dialog, from the dialog the method in the activity and from there append the item to the list.
Also i cant access the bundle in the appender from my activity.
Gratefully
Lukas
Okay i got the solution on my one now.
I Created everytime a new fragment, so they were overlapping.
Now i Create the Fragment in the OnCreate of the Activity and call a Method in the fragment to add a new item
Related
I am working on a Multipane app, where the left most pane is static and the right pane has dynamically added fragments.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="path.fragments.NavigationFragment"
android:id="#+id/navigation_fragment"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
tools:layout="#layout/navigation_layout" />
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent" />
</LinearLayout>
Whenever a list item is selected in the left pane, that contains the list of the users, I want to create a new fragment and add it to the container, and fill it with the messages from that user. The rest of my logic works great, but I am just having issues with the dynamically adding new fragments. updating the existing fragment before replacing it using the FragmentTransaction works. However, when I try the code below it doesn't work
DetailsFragment detailsFragment = new DetailsFragment();
Bundle args = new Bundle();
args.putInt(DetailsFragment.ARG_POSITION, position);
detailsFragment.setArguments(args);
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
trans.replace(R.id.fragment_container, detailsFragment);
trans.addToBackStack(null);
trans.commit();
Log.v(TAG, "updating details fragment with argument = " + position);
Cursor cursor = (Cursor) adapter.getItem(position);
Peer peer = new Peer(cursor);
String[] from = new String[] {MessageContract.TEXT};
int[] to = new int[] {android.R.id.text1};
adapter2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_expandable_list_item_1,
null,
from,
to, 2);
detailsFragment = (DetailsFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_container);
ListView LV = (ListView) detailsFragment.getView().findViewById(android.R.id.list);
LV.setAdapter(adapter2);
In summary, what I am trying to do is:
Create a new fragment
add it to the container
and update the view from the MainActivity
Additionally, inside the onCreate in the MainActivity I have this:
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
DetailsFragment firstFragment = new DetailsFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
Please accept my apologies if I am not clear enough, and thank you in advance for your help :)
From the Fragments Developer Guide:
"Calling commit() does not perform the transaction immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon as the thread is able to do so."
You have the following lines of code almost immediately after committing the FragmentTransaction.
ListView LV = (ListView) detailsFragment.getView().findViewById(android.R.id.list);
LV.setAdapter(adapter2);
It is most likely that the View for the detailsFragment has not been created yet.
Take a look at the Complete Activity/Fragment Lifecycle. View creation does not occur until after the Fragment is attached to the Activity.
If you need to pass adapter2 from the Activity to the Fragment, you could create a member variable and setter in your Fragment, but don't set the adapter on the ListView until the Fragment's View has been created.
For example, in your Fragment:
// member variable to hold the adapter
private SimpleCursorAdapter mAdapter2;
// setter for the member variable
private void setAdapter2(SimpleCursorAdapter adapter) {
mAdapter2 = adapter;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Now that the view is created, we can set the adapter.
ListView LV = (ListView) view.findViewById(android.R.id.list);
LV.setAdapter(mAdapter2);
}
And in your Activity:
// Create the new Fragment
DetailsFragment detailsFragment = new DetailsFragment();
// Add the Arguments to the Fragment
Bundle args = new Bundle();
args.putInt(DetailsFragment.ARG_POSITION, position);
detailsFragment.setArguments(args);
// Create the adapter
Cursor cursor = (Cursor) adapter.getItem(position);
Peer peer = new Peer(cursor);
String[] from = new String[] {MessageContract.TEXT};
int[] to = new int[] {android.R.id.text1};
adapter2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_expandable_list_item_1,
null,
from,
to, 2);
// Set the Adapter for the Fragment
detailsFragment.setAdapter2(adapter2);
// Do the FragmentTransaction
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.replace(R.id.fragment_container, detailsFragment);
trans.addToBackStack(null);
trans.commit();
I'am new to Android application developpement. I'am trying to create an application using navigation drawer. I created an apllication with the navigation drawer template with android studio. Then i changed it to redirect the user to a new fragment_layout each time he chooses a new item in the navigation menu. Now, my first fragment contains a listview, and onclick on one item of the list i am redirected to a detailfragment which contains a TextView.
When i tried to populate this TextView with details of the selected item i had a null pointer exception.After two days of research and trying to find out what is the problem i discovered that my visible fragment returns false when i call fragment.isInLayout().
Thanks for your help.
My code :
Creation of a new fragment :
VideoDetailFragment fragment = new VideoDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title)
fragment.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
getFragmentManager().executePendingTransactions();
if (fragment.isInLayout()) {
fragment.replaceText("Lalala");}
And the method replaceText code is :
public void replaceText(String text){
textView.setText(text);
}
The problem is that the methode replaceText is not reached And when i remove the if statement a null pointer exception is raised saying that i can not write in the textView
EDIT: I think the problem is with transaction.replace(R.id.container,fragment);, maybe there is another alternative to replace a fragment_layout content. Because, i have the VideoDetailFragment displayed in the simulator and i can't change it's content, Also when i tired VideoDetailFragment fragment1 = (VideoDetailFragment)getFragmentManager().findFragmentById(R.id.container);
it gave me a cast exception.
Thanks a lot for your help, really need it :)
Try to do something like this:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
Then in your second Fragment, retrieve the data (you could do it for example in onCreate()) with:
Bundle bundle = this.getArguments();
int myString = bundle.getString(key, ""); //the second parameter is a default value
Or show your code to see where do you get NullPointerException
YourFragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_fragment);
if (fragment != null) {
fragment.yourUpdateDataMethod(youData);
}
I am using Android Studio and I created an Activity that contains a NavigationDrawerFragment.
One of the Fragments is loading the content of an SQLite database inside a ListView, using a custom ArrayAdapter with complex items.
My problem is that if I select another fragment in the drawer, then come back to this one, the onCreate() of the Fragment is called again, so is the onCreateView(), and the database is loaded once again.
How can I preserve everything without having to load the database nor populate the list again?
I don't have this problem when orientation changes, so I am a bit confused. Maybe it is because I have a layout for both Portrait and Landscape ?
here is the code of the onCreateView()
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getActionBar().show();
View view = inflater.inflate(R.layout.fragment_papers, container, false);
allItems = new ArrayList<ItemData>();
getAllItemsFromDB("");
mAdapter = new ItemsList(getActivity(), allItems, this, mDBApi);
// Set the adapter
mListView = (AbsListView) view.findViewById(R.id.list);
mListView.setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
mListView.setOnScrollListener(this);
return view;
}
and the getAllItemsFromDB() contains something like
public void getAllItemsFromDB(String query){
Cursor c = sqldb.rawQuery("SELECT * FROM 'Table' " + query, null);
while (c.moveToNext()) {
allItems.add(parseSQL(sqldb, c));
}
c.close();
}
Set your array list static
private static List<ItemData> allItems;
Then check it for null and initialise it only once
if(allItems == null) {
allItems = new ArrayList<ItemData>();
getAllItemsFromDB("");
}
may be ur loading frament everytime as
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new UrFragment()).commit();
Don't do that, create instance of fragment and use it.
// update the main content by replacing fragments
Fragment fragment = new UrFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
Hello I'm trying to pass a String value from a fragment to another one. I have a single Activity.
The thing that I'm trying to do is when a listview item is pressed send the value to the another fragment, load the fragment (This I had made with this code):
Fragment cambiarFragment = new FragmentInterurbanos();
Bundle args = new Bundle();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction
.replace(R.id.container, cambiarFragment)
.addToBackStack(null)
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
// Commit the transaction
transaction.commit();
And then retrieve the String and update a WebView placed in the new fragment (This method cannot be launched when the user select in NavigationDrawer this section (Fragment).
Thanks for your help in advance!
There are many ways you can achieve this... you could pass the string to the new Fragment through a Bundle like this:
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
or maybe have a DataController class where you store the string and the new fragment retrieves it.
Apologies as I am an Android novice. I'm trying to programmatically add multiple list fragments to a single activity, but when I do, only one is displayed. How can I display multiple lists in a single action?
The end goal is to read a set of data from an API and categorize it into multiple lists in my application. I would like the data to be horizontally scrolling list fragments, but since that's an additional complication I've started with simple ListFragments. My code looks like this:
activity_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
ItemActivity:
public class ItemActivity extends FragmentActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager manager = getSupportFragmentManager();
ItemListFragment fragment1 = new ItemListFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragmentContainer, fragment1);
ItemListFragment fragment2 = new ItemListFragment();
transaction.add(R.id.fragmentContainer, fragment2);
transaction.commit();
}
}
ItemListFragment:
public class ItemListFragment extends ListFragment {
List<String> items = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
items.add("One");
items.add("Two");
items.add("Three");
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
}
If you want multiple lists in one Activity, here's what I usually do:
Because every ListView is using independent scrolling view, I usually split the screen for every ListView I have. Example: with 2 ListView i split the height of the screen 50/50 so every ListView have 50% portion of the screen.
If I have to dynamically add ListView to the screen, I use cwac merge adapter to merge the adapter and display it in a single ListView
Another alternative you can just use ViewPager to display ListFragment. This would achieve what you want, which is having multiple listviews in a single activity.
Why wouldnt you do it this way?
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
// work here to change Activity fragments (add, remove, etc.). Example here of adding.
fragmentTransaction.add (R.id.myFrame, myFrag);
fragmentTransaction.commit ()
i found this code, so as just one is displayed, commit each transaction in your code.
FragmentManager manager = getSupportFragmentManager();
ItemListFragment fragment1 = new ItemListFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragmentContainer, fragment1).commit();
transaction = manager.beginTransaction(); // might be unnescessary
ItemListFragment fragment2 = new ItemListFragment();
transaction.add(R.id.fragmentContainer, fragment2).commit();
if this throws some sort of error, you might need to start another transaction for adding the second fragment.