Arguments keep Returning Empty - android

Hello I've been having this problem for months , so please somebody help, I am a beginner in developing apps for android , that's why i wasn't able to fix this.
The Problem:
Developing A Music Player, my problem is with the playlists and its id,
when i pass the PlaylistId under the arguments its not returning anything so the screen stays white. Now I've tried a lot of stuff to fix this and i managed to get that the problem is with the arguments (The Adapter is fine,Layout is fine,Everything else is fine) So Please I Know Its Gonna Take Some Time And Work Put Please Help.
NavUtils :
public final class NavUtils {
public static void openSearch(final Activity activity, final String query) {
final Bundle bundle = new Bundle();
final Intent intent = new Intent(activity, Search.class);
intent.putExtra(SearchManager.QUERY, query);
intent.putExtras(bundle);
activity.startActivity(intent);
}
/**
* Opens the profile of an artist.
*
* #param context The {#link android.app.Activity} to use.
* #param artistName The name of the artist
*/
public static void openArtistProfile(final Activity context,
final String artistName) {
// Create a new bundle to transfer the artist info
final Bundle bundle = new Bundle();
bundle.putLong(Config.ID, Utils.getIdForArtist(context, artistName));
bundle.putString(Config.MIME_TYPE, MediaStore.Audio.Artists.CONTENT_TYPE);
bundle.putString(Config.ARTIST_NAME, artistName);
// Create the intent to launch the profile activity
final Intent intent = new Intent(context, Profile.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
/**
* Opens the profile of an album.
*
* #param context The {#link android.app.Activity} to use.
* #param albumName The name of the album
* #param artistName The name of the album artist
* #param albumId The id of the album
*/
public static void openAlbumProfile(final Activity context,
final String albumName, final String artistName, final long albumId) {
// Create a new bundle to transfer the album info
final Bundle bundle = new Bundle();
bundle.putString(Config.ALBUM_YEAR, Utils.getReleaseDateForAlbum(context, albumId));
bundle.putString(Config.ARTIST_NAME, artistName);
bundle.putString(Config.MIME_TYPE, MediaStore.Audio.Albums.CONTENT_TYPE);
bundle.putLong(Config.ID, albumId);
bundle.putString(Config.NAME, albumName);
// Create the intent to launch the profile activity
final Intent intent = new Intent(context, Profile.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
public static void openPlaylistProfile(final Activity context,
final String playlistName, final long playlistId) {
// Create a new bundle to transfer the album info
final Bundle bundle = new Bundle();
bundle.putString(Config.MIME_TYPE, MediaStore.Audio.Playlists.CONTENT_TYPE);
bundle.putLong(Config.ID, playlistId);
bundle.putString(Config.NAME, playlistName);
// Create the intent to launch the profile activity
final Intent intent = new Intent(context, Profile.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
PlaylistFragment:
public class PlaylistFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,OnItemClickListener {
private PlaylistsAdapter mAdapter;
GridView gridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_playlist, container, false);
mAdapter = new PlaylistsAdapter(getActivity(), null);
gridview = (GridView) myFragmentView.findViewById(R.id.playlistGrid);
getLoaderManager().initLoader(0, null, this);
return myFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gridview.setAdapter(mAdapter);
gridview.setOnItemClickListener(this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] {
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.PlaylistsColumns.NAME
}, null, null, MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Bundle bundle = new Bundle();
Cursor cursor = mAdapter.getCursor();
NavUtils.openPlaylistProfile(getActivity(),cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME)),cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID)));
}
}
PlaylistSong:
public class PlaylistSong extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener {
private SongAdapter mAdapter;
ListView listView;
long playlistID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_song, container, false);
mAdapter = new SongAdapter(getActivity(), null);
listView = (ListView) myFragmentView.findViewById(R.id.songlist);
final Bundle arguments = getArguments();
getLoaderManager().initLoader(0, null, this); /// if i set the second parameters as arguments instead of null it returns NullPointer
playlistID = arguments.getLong(Config.ID);
return myFragmentView;
}
/**
* {#inheritDoc}
*/
#Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(this);
listView.setFastScrollEnabled(true);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
final StringBuilder mSelection = new StringBuilder();
mSelection.append(MediaStore.Audio.AudioColumns.IS_MUSIC + "=1");
mSelection.append(" AND " + MediaStore.Audio.AudioColumns.TITLE + " != ''");
return new CursorLoader(getActivity(),MediaStore.Audio.Playlists.Members.getContentUri("external", playlistID),
new String[] {
/* 0 */
MediaStore.Audio.Playlists.Members._ID,
/* 1 */
MediaStore.Audio.Playlists.Members.AUDIO_ID,
/* 2 */
MediaStore.Audio.AudioColumns.TITLE,
/* 3 */
MediaStore.Audio.AudioColumns.ARTIST,
/* 4 */
MediaStore.Audio.AudioColumns.ALBUM,
/* 5 */
MediaStore.Audio.AudioColumns.DURATION
}, mSelection.toString(), null,
MediaStore.Audio.AudioColumns.TITLE);
}
/* if i replace the above code with the one below it displays all the songs fine
String select = null;
final StringBuilder mSelection = new StringBuilder();
mSelection.append(MediaStore.Audio.AudioColumns.IS_MUSIC + "=1");
mSelection.append(" AND " + MediaStore.Audio.AudioColumns.TITLE + " != ''");
return new CursorLoader(getActivity(),MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AudioColumns.TITLE,
/* 2 */
MediaStore.Audio.AudioColumns.ARTIST,
/* 3 */
MediaStore.Audio.AudioColumns.ALBUM,
/* 4 */
MediaStore.Audio.AudioColumns.DURATION,
/*5*/
MediaStore.Audio.AudioColumns.ALBUM_ID
}, mSelection.toString(), null,
MediaStore.Audio.AudioColumns.TITLE);
*/
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Profile:
public class Profile extends FragmentActivity {
/**
* The Bundle to pass into the Fragments
*/
private Bundle mArguments;
public static long playlistId;
/**
* MIME type of the profile
*/
private String mType;
public static long ID;
private long IDLong;
PagerAdapter mPagerAdapter;
/**
* Artist name passed into the class
*/
private String mArtistName;
private String mPlaylistName;
/**
* The main profile title
*/
private String mProfileName;
private Drawable ActionBarBackgroundDrawable;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Temporay until I can work out a nice landscape layout
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_profile);
///TODO FIX PLAYLIST ARGUMENTS
// Initialize the Bundle
mArguments = savedInstanceState != null ? savedInstanceState : getIntent().getExtras();
// Get the MIME type
mType = mArguments.getString(Config.MIME_TYPE);
ID = mArguments.getLong(Config.ID);
// Initialize the pager adapter
mPagerAdapter = new PagerAdapter(this);
// Get the profile title
mProfileName = mArguments.getString(Config.NAME);
// Get the artist name
if (isArtist() || isAlbum()) {
mArtistName = mArguments.getString(Config.ARTIST_NAME);
}
displayView();
}
#Override
public void onBackPressed() {
// super.onBackPressed();
Intent start = new Intent(this,Base.class);
startActivity(start);
finish();
}
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putAll(mArguments);
}
private void displayView() {
// update the main content by replacing fragments
Fragment fragment = null ;
if(isAlbum()){
Toast.makeText(getBaseContext(), "isAlbum", Toast.LENGTH_LONG).show();
Bundle bundle=new Bundle();
bundle.putLong(Config.ID, ID);
fragment=new AlbumSong();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.profileContainer, fragment).commit();
Toast.makeText(getBaseContext(), "Fragment Chnaged Succesfully", Toast.LENGTH_LONG).show();
// Action bar title = album name
setTitle(mProfileName);
}else{
if (isPlaylist()) {
// Add the carousel images
Toast.makeText(getBaseContext(), "isPlaylist", Toast.LENGTH_LONG).show();
Bundle bundle=new Bundle();
bundle.putLong(Config.ID, ID);
fragment=new PlaylistSong();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.profileContainer, fragment).commit();
Toast.makeText(getBaseContext(), "Fragment Changed Successfully", Toast.LENGTH_LONG).show();
// Action bar title = album name
setTitle(mProfileName);
}
}}
private final boolean isPlaylist() {
return mType.equals(MediaStore.Audio.Playlists.CONTENT_TYPE);
}
private final boolean isArtist() {
return mType.equals(MediaStore.Audio.Artists.CONTENT_TYPE);
}
/**
* #return True if the MIME type is vnd.android.cursor.dir/albums, false
* otherwise.
*/
private final boolean isAlbum() {
return mType.equals(MediaStore.Audio.Albums.CONTENT_TYPE);
}
}
And If There is An Other way to do this i am All Ears. New Update in code please read comments , now when i set the PlaylistSong to display all the songs it works fine.Now For The Weird Part when i set the PlayPlaylist Method on the item click , it requires the PlaylistId to work guess what, it plays the songs in the playlist so i think that the problem is in displaying the song for this specific playlist.So the playlist id is null when displaying the playlist put is not when playing the playlist.Please Help And If Someone Needs More Code Tell Me.
PlayPlaylist():
public static void playPlaylist(final Context context, final long playlistId) {
final long[] playlistList = getSongListForPlaylist(context, playlistId);
if (playlistList != null) {
playAll(context, playlistList, -1, false);
}
}
getSongListForPlaylist():
public static final long[] getSongListForPlaylist(final Context context, final long playlistId) {
final String[] projection = new String[] {
Playlists.Members.AUDIO_ID
};
Cursor cursor = context.getContentResolver().query(
Playlists.Members.getContentUri("external",
Long.valueOf(playlistId)), projection, null, null,
Playlists.Members.DEFAULT_SORT_ORDER);
if (cursor != null) {
final long[] list = getSongListForCursor(cursor);
cursor.close();
cursor = null;
return list;
}
return sEmptyList;
}

Related

Why Android CursorAdapter call 3 times the same action

I have a problem with my CursorAdapter, I have to fill a listView with dynamic images.
I have a BBDD with some fields with value "1" or "0".
In bindView, when the fields returns 1 I add the image to a linearLayout.
The problem is that the image is added 3 times, and I don't know why.
girlsFragmentAdapter:
public class girlsListFragmentCursoAdapter extends CursorAdapter {
public girlsListFragmentCursoAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.girls_list_row,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView girlName;
ImageView imgExercice = new ImageView(context);
LinearLayout linearImgRow = (LinearLayout) view.findViewById(R.id.exercices_list_row);
girlName = view.findViewById(R.id.txtvwGirlName);
if (cursor.getString(cursor.getColumnIndexOrThrow("pull_ups")).equals("1") ) {
imgExercice.setImageResource(R.drawable.push_ups);
linearImgRow.addView(imgExercice);
Toast.makeText(context,"Pull ups: " +cursor.getString(cursor.getColumnIndexOrThrow("pull_ups")),Toast.LENGTH_SHORT ).show();
}
girlName.setText(cursor.getString(cursor.getColumnIndexOrThrow("nombre")));
}
}
I call this adapter from a Fragment ** when **OnActivityCreated is called
girls_fragment
public class girls_fragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private WodDbAdapter mWodAdapter;
ListView lvWods;
private View rootview;
public girls_fragment() {
// Required empty public constructor
}
public static girls_fragment newInstance(String param1, String param2) {
girls_fragment fragment = new girls_fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lvWods = (ListView) getView().findViewById(R.id.lvwGirlsList);
mWodAdapter = new WodDbAdapter(getContext());
mWodAdapter.open();
fillData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.fragment_girls_fragment,container,false);
return rootview;
}
private void fillData(){
Cursor mGirlsCursor = mWodAdapter.fetchAllWods("girl");
getActivity().startManagingCursor(mGirlsCursor);
String [] from = new String[]{WodDbAdapter.KEY_NOMBRE,};
int [] to = new int []{R.id.txtvwGirlName};
girlsListFragmentCursoAdapter mGirlsAdapter = new girlsListFragmentCursoAdapter(rootview.getContext(),mGirlsCursor);
lvWods.setAdapter(mGirlsAdapter);
}
}
The result is this:
As you can see the image appears three times instead of one
It's because the following code:
if (cursor.getString(cursor.getColumnIndexOrThrow("pull_ups")).equals("1") ) {
imgExercice.setImageResource(R.drawable.push_ups);
linearImgRow.addView(imgExercice);
Toast.makeText(context,"Pull ups: " +cursor.getString(cursor.getColumnIndexOrThrow("pull_ups")),Toast.LENGTH_SHORT ).show();
}
with the following line:
linearImgRow.addView(imgExercice);
where you're always adding the imgExercice to the linearImgRow each times the bindView is called.

Android scrollable list

I have one list of elements and one AbsListView. How I can load my elements of list just when I scroll?
this is my list: private List<Database_elem> database_elemList = new ArrayList<Database_elem>();
public class PlacesFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private List<Database_elem> database_elemList = new ArrayList<Database_elem>();
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
ImageView imageView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static PlacesFragment newInstance(String param1, String param2) {
PlacesFragment fragment = new PlacesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PlacesFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
// mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}
String[] test;
String text = "Central Park";
Date data = new Date();
String data_database = String.valueOf(data);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_place, container, false);
Context ctx = view.getContext();
DataBase dataBase = new DataBase(getActivity().getApplicationContext());
// SQLiteDatabase db = dataBase.getReadableDatabase();
Cursor cr = dataBase.getInformation(dataBase);
cr.moveToFirst();
// dataBase.onCreate(db);
// ctx.deleteDatabase(DataBase.TABLE_NAME);
final DetectionLocation detectionLocation = new DetectionLocation(ctx);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
Integer val = Integer.valueOf(prefs.getString("sync_frequency", ""));
String sync_status = String.valueOf(val);
dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "Sincronizare", data, sync_status);
while (true) {
if (!cr.isLast()) {
database_elemList.add(new Database_elem(cr.getString(0), cr.getString(1), cr.getString(2), cr.getString(3), cr.getString(4), cr.getString(5)));
cr.moveToNext();
} else {
break;
}
}
test = new String[database_elemList.size()];
//System.out.println(cr.getString(1));
for (int i = 0; i < database_elemList.size(); i++) {
CustomListAdapter adapter = new CustomListAdapter(getActivity(), test, database_elemList.get(0).getLat() + " " + database_elemList.get(0).getLon(), database_elemList.get(0).getSync_date());
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(adapter);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// DataBase dataBase = new DataBase(getActivity().getApplicationContext());
// Cursor cr = dataBase.getInformation(dataBase);
// cr.moveToFirst();
for (int i = 0; i < database_elemList.size(); i++) {
CustomListAdapter adapter = new CustomListAdapter(getActivity(), test, database_elemList.get(0).getLat() + " " + database_elemList.get(0).getLon(), database_elemList.get(0).getSync_date());
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(adapter);
}
}
});
}
}
, val);
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
You could just use a CursorAdapter...

Android - Sending data from fragment to fragment using swipeview

Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.

passing cursor position from listview to viewpager

im working in one small project about handling feeds im looking to handle the feeds in listview and show details in viewpager and get the same feed when i click on the listview im lost about how i can pass the cursor position to the viewpaver
that it s the complet listfragment
public class EntryListFragmentt extends ListFragment
implements OnItemClickListener ,LoaderManager.LoaderCallbacks<Cursor>{
private static final String TAG = "EntryListFragmentt";
private OnItemSelectedListener mParentOnItemSelectedListener;
/**
* Cursor adapter for controlling ListView results.
*/
private SimpleCursorAdapter mAdapter;
public static ImageLoader imageLoader;
Uri detailUri;
static int pos;
private LoaderManager.LoaderCallbacks<Cursor> mCallbacks;
/**
* Handle to a SyncObserver. The ProgressBar element is visible until the SyncObserver reports
* that the sync is complete.
*
* <p>This allows us to delete our SyncObserver once the application is no longer in the
* foreground.
*/
ConnectionDetector cd;
private Object mSyncObserverHandle;
/**
* Options menu used to populate ActionBar.
*/
private Menu mOptionsMenu;
/**
* Projection for querying the content provider.
*/
private static final String[] PROJECTION = new String[]{
FeedContract.Entry._ID,
FeedContract.Entry.COLUMN_NAME_TITLE,
FeedContract.Entry.COLUMN_NAME_LINK,
FeedContract.Entry.COLUMN_IMAG_LINK,
FeedContract.Entry.COLUMN_TEXT_ENTRY,
FeedContract.Entry.COLUMN_NAME_PUBLISHED
};
// Column indexes. The index of a column in the Cursor is the same as its relative position in
// the projection.
/** Column index for _ID */
private static final int COLUMN_ID = 0;
/** Column index for title */
private static final int COLUMN_TITLE = 1;
/** Column index for link */
private static final int COLUMN_URL_STRING = 2;
/** Column index for published */
private static final int COLUMN_IMAG_LINK = 3;
private static final int COLUMN_TEXT_ENTRY = 4;
private static final int COLUMN_PUBLISHED = 5;
AlertDialogManager alert = new AlertDialogManager();
/**
* List of Cursor columns to read from when preparing an adapter to populate the ListView.
*/
private static final String[] FROM_COLUMNS = new String[]{
FeedContract.Entry.COLUMN_NAME_TITLE,
FeedContract.Entry.COLUMN_NAME_PUBLISHED,
FeedContract.Entry.COLUMN_NAME_LINK
// FeedContract.Entry.COLUMN_TEXT_ENTRY
};
/**
* List of Views which will be populated by Cursor data.
*/
private static final int[] TO_FIELDS = new int[]{
R.id.tx_title_actu,
R.id.tx_date_actu,
R.id.img_actu
// R.id.tx_text_actu
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public static EntryListFragmentt newInstance() {
return new EntryListFragmentt();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View view = inflater
// .inflate(R.layout.activity_entry_list, container, false);
return container;
}
**/
/**
* Create SyncAccount at launch, if needed.
*
* <p>This will create a new account with the system for our application, register our
* {#link SyncService} with it, and establish a sync schedule.
*/
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Create account, if needed
SyncUtils.CreateSyncAccount(activity);
}
// private void loaddata(){
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mAdapter = new SimpleCursorAdapter(
getActivity(), // Current context
R.layout.actu_listitem, // Layout for individual rows
null, // Cursor
FROM_COLUMNS, // Cursor columns to use
TO_FIELDS, // Layout fields to use
0 // No flags
);
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
private String slink;
#Override
public boolean setViewValue(View view, Cursor cursor, int i) {
if (i == COLUMN_PUBLISHED ) {
// Convert timestamp to human-readable date
Time t = new Time();
t.set(cursor.getLong(i));
((TextView) view).setText(t.format("%Y-%m-%d %H:%M"));
// Drawable fimag = ResourceUtils.getDrawableByName( imaglink, getActivity());
//String faceName = "ic_launcher";
return true;
} else if (i == COLUMN_URL_STRING ){
slink = CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor).trim();
// int vlink = Integer.parseInt(CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor));
ImageView vimage =(ImageView) view.findViewById(R.id.img_actu);
//vimage.setImageResource(getActivity().getResources().getIdentifier("app.oc.gov.ma:drawable/"+slink,null,null));
vimage.setImageDrawable(ResourceUtils.getDrawableByName(slink, getActivity()));
// imageLoader=new ImageLoader(getActivity().getApplicationContext());
//imageLoader.DisplayImage(imaglink, vimage);
// vimage.setImageResource(R.drawable.a);
// Let SimpleCursorAdapter handle other fields automatically
return true;
} else {
return false;
}
}
});
mCallbacks = this;
setListAdapter(mAdapter);
setEmptyText(getText(R.string.loading));
getLoaderManager().initLoader(0, null, mCallbacks);
}
#Override
public void onResume() {
super.onResume();
mSyncStatusObserver.onStatusChanged(0);
// Watch for sync state changes
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
}
#Override
public void onPause() {
super.onPause();
if (mSyncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
mSyncObserverHandle = null;
}
}
/**
* Query the content provider for data.
*
* <p>Loaders do queries in a background thread. They also provide a ContentObserver that is
* triggered when data in the content provider changes. When the sync adapter updates the
* content provider, the ContentObserver responds by resetting the loader and then reloading
* it.
*/
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// We only have one loader, so we can ignore the value of i.
// (It'll be '0', as set in onCreate().)
return new CursorLoader(getActivity(), // Context
FeedContract.Entry.CONTENT_URI, // URI
PROJECTION, // Projection
null, // Selection
null, // Selection args
// null); // Sort
FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort
}
/**
* Move the Cursor returned by the query into the ListView adapter. This refreshes the existing
* UI with the data in the Cursor.
*/
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mAdapter.changeCursor(cursor);
}
/**
* Called when the ContentObserver defined for the content provider detects that data has
* changed. The ContentObserver resets the loader, and then re-runs the loader. In the adapter,
* set the Cursor value to null. This removes the reference to the Cursor, allowing it to be
* garbage-collected.
*/
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mAdapter.changeCursor(null);
}
/**
* Create the ActionBar.
*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
mOptionsMenu = menu;
inflater.inflate(R.menu.main_actu, menu);
}
/**
* Respond to user gestures on the ActionBar.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// If the user clicks the "Refresh" button.
case R.id.menu_refresh:
cd = new ConnectionDetector(getActivity().getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
setEmptyText(getText(R.string.noconnect));
alert.showAlertDialog(getActivity(), "Internet Connection Error",
"Please connect to working Internet connection", false);
}else {
SyncUtils.TriggerRefresh();
return true;
}
return false;
}
return super.onOptionsItemSelected(item);
}
/**
* Load an article in the default browser when selected by the user.
*/
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Get a URI for the selected item, then start an Activity that displays the URI. Any
// Activity that filters for ACTION_VIEW and a URI can accept this. In most cases, this will
// be a browser.
// Get the item at the selected position, in the form of a Cursor.
Cursor c = (Cursor) mAdapter.getItem(position);
// Get the link to the article represented by the item.
Uri detailUri = Uri.parse(FeedContract.Entry.CONTENT_URI + "/" + id);
WhatsOnFragment.newInstance(position, detailUri);
WhatsOnFragment WWhatsOnFragment = new WhatsOnFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.frame_container, WWhatsOnFragment);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
public int getCount(int cmp) {
return cmp ;
}
public static WhatsOnFragment newInstance(int position,int cmp, Uri detailUri) {
WhatsOnFragment frag = new WhatsOnFragment();
Bundle args = new Bundle();
args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
args.putInt(WhatsOnFragment.POSITION_KEY, position);
frag.setArguments(args);
return frag;
}
/**
* Set the state of the Refresh button. If a sync is active, turn on the ProgressBar widget.
* Otherwise, turn it off.
*
* #param refreshing True if an active sync is occuring, false otherwise
*/
public void setRefreshActionButtonState(boolean refreshing) {
if (mOptionsMenu == null) {
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
if (refreshItem != null) {
if (refreshing) {
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
} else {
refreshItem.setActionView(null);
}
}
}
/**
* Crfate a new anonymous SyncStatusObserver. It's attached to the app's ContentResolver in
* onResume(), and removed in onPause(). If status changes, it sets the state of the Refresh
* button. If a sync is active or pending, the Refresh button is replaced by an indeterminate
* ProgressBar; otherwise, the button itself is displayed.
*/
private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
/** Callback invoked with the sync adapter status changes. */
#Override
public void onStatusChanged(int which) {
getActivity().runOnUiThread(new Runnable() {
/**
* The SyncAdapter runs on a background thread. To update the UI, onStatusChanged()
* runs on the UI thread.
*/
#Override
public void run() {
// Create a handle to the account that was created by
// SyncService.CreateSyncAccount(). This will be used to query the system to
// see how the sync status has changed.
Account account = GenericAccountService.GetAccount();
if (account == null) {
// GetAccount() returned an invalid value. This shouldn't happen, but
// we'll set the status to "not refreshing".
setRefreshActionButtonState(false);
return;
}
// Test the ContentResolver to see if the sync adapter is active or pending.
// Set the state of the refresh button accordingly.
boolean syncActive = ContentResolver.isSyncActive(
account, FeedContract.CONTENT_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, FeedContract.CONTENT_AUTHORITY);
setRefreshActionButtonState(syncActive || syncPending);
}
});
}
};
}
that it s the fragment detail viewpager
public class WhatsOnFragment extends Fragment implements
LoaderCallbacks<Cursor> {
private static final String TAG="WhatsOnFragment";
private OnItemSelectedListener mParentOnImageSelectedListener;
private Handler mHandler = new Handler();
private TextView mCountdownTextView;
private ViewGroup mRootView;
private Cursor mAnnouncementsCursor;
private LayoutInflater mInflater;
private int mTitleCol = -1;
private int mDateCol = -1;
private int mUrlCol = -1;
//**********************************************''
/** Column index for _ID */
private static final int COLUMN_ID = 0;
/** Column index for title */
private static final int COLUMN_TITLE = 1;
/** Column index for link */
private static final int COLUMN_URL_STRING = 2;
/** Column index for published */
private static final int COLUMN_IMAG_LINK = 3;
private static final int COLUMN_TEXT_ENTRY = 4;
private static final int COLUMN_PUBLISHED = 5;
private static final String[] PROJECTION = new String[]{
FeedContract.Entry._ID,
FeedContract.Entry.COLUMN_NAME_TITLE,
FeedContract.Entry.COLUMN_NAME_LINK,
FeedContract.Entry.COLUMN_IMAG_LINK,
FeedContract.Entry.COLUMN_TEXT_ENTRY,
FeedContract.Entry.COLUMN_NAME_PUBLISHED
};
public static String POSITION_KEY = "position";
private static final int ANNOUNCEMENTS_LOADER_ID = 0;
private Uri detailUri;
public static int vpos;
public static WhatsOnFragment newInstance(int position, Uri detailUri) {
WhatsOnFragment frag = new WhatsOnFragment();
Bundle args = new Bundle();
args.putInt(POSITION_KEY, position);
//args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
frag.setArguments(args);
return frag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v(TAG, "onAttach");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Bundle extras = getArguments();
//vpos = extras.getInt(POSITION_KEY,0);
//vpos = savedInstanceState.getInt(POSITION_KEY, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
//
mRootView = (ViewGroup) inflater.inflate(R.layout.content_f,
container,false);
refresh();
return mRootView;
}
#Override
public void onDetach() {
super.onDetach();
// mHandler.removeCallbacks(mCountdownRunnable);
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
private void refresh() {
mHandler.removeCallbacks(mCountdownRunnable);
//mRootView.removeAllViews();
setupDuring();
//getLoaderManager().initLoader(0, null, this);
}
private void setupDuring() {
// Start background query to load announcements
getLoaderManager().initLoader(0, null, this);
getActivity().getContentResolver().registerContentObserver(
FeedContract.Entry.CONTENT_URI, true, mObserver);
}
/**
* Event that updates countdown timer. Posts itself again to
* {#link #mHandler} to continue updating time.
*/
private final Runnable mCountdownRunnable = new Runnable() {
public void run() {
mHandler.postDelayed(new Runnable() {
public void run() {
refresh();
}
}, 100);
return;
}
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), // Context
FeedContract.Entry.CONTENT_URI, // URI
PROJECTION, // Projection
null, // Selection
null, // Selection args
// null);
FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (getActivity() == null) {
return;
}
if (data != null && data.getCount() > 0) {
mTitleCol = data.getColumnIndex(FeedContract.Entry.COLUMN_NAME_TITLE);
mDateCol = data.getColumnIndex(FeedContract.Entry.COLUMN_TEXT_ENTRY);
showAnnouncements(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAnnouncementsCursor = null;
}
/**
* Show the the announcements
*/
private void showAnnouncements(Cursor announcements) {
mAnnouncementsCursor = announcements;
ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate(
R.layout.detail, mRootView, false);
final ViewPager pager = (ViewPager) announcementsRootView.findViewById(
R.id.pager);
final PagerAdapter adapter = new AnnouncementsAdapter();
pager.setAdapter(adapter);
//pager.setCurrentItem(0);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
pager.setCurrentItem(pager.getCurrentItem());
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
//Toast.makeText(getActivity().getApplicationContext(),"myposition " + position,Toast.LENGTH_LONG).show();
}
});
//mRootView.removeAllViews();
mRootView.addView(announcementsRootView);
}
public class AnnouncementsAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup pager, int position) {
mAnnouncementsCursor.moveToPosition(position);
View rootView = (View) mInflater.inflate(
R.layout.detail_fragment, pager, false);
TextView titleView = (TextView) rootView.findViewById(R.id.title);
TextView subtitleView = (TextView) rootView.findViewById(R.id.description);
//WebView desc = (WebView) rootView.findViewById(R.id.desc);
// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) rootView.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set webview properties
//WebSettings ws = desc.getSettings();
//ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//ws.setLightTouchEnabled(false);
//ws.setPluginState(PluginState.ON);
//ws.setJavaScriptEnabled(true);
titleView.setText(mAnnouncementsCursor.getString(mTitleCol));
subtitleView.setText(mAnnouncementsCursor.getString(mDateCol));
//desc.loadDataWithBaseURL("http://.../",mAnnouncementsCursor.getString(mDateCol), "text/html", "UTF-8", null);
pager.addView(rootView, 0);
return rootView;
}
#Override
public void destroyItem(ViewGroup pager, int position, Object view) {
pager.removeView((View) view);
}
#Override
public int getCount() {
return mAnnouncementsCursor.getCount();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public Object getItem(int position) {
WhatsOnFragment frag = new WhatsOnFragment();
Bundle args = new Bundle();
args.putInt(POSITION_KEY, position);
//args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
frag.setArguments(args);
if (position > 0 && position < mAnnouncementsCursor.getCount() - 1) {
return position;
}
return position;
}
}
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
if (getActivity() == null) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID);
if (loader != null) {
loader.forceLoad();
}
}
};
}
Here's how I am passing my Uri from one activity to another:
After you get the uri from your onListItemClick, add this line of code after that:
String uriString = uri.toString();
Now, you can either do it through shared preference or by passing extras from intent,
Method 1: By shared preference:
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("uri", uriString);
editor.commit();
Then, in your other activity or where your listview is defined, use this to retrieve the uri,
SharedPreferences mPreferences = mPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String uri = mPreferences.getString("uri", uri);
//To parse the uri
Uri newUri = Uri.parse(uri);
Then you can use this uri to get the information you want to.
Method 2 : Getting uri from Intent:
First : In you activity where you are getting the Uri,
Intent myIntent = new Intent(SomeActivity1.this, SomeActivity2.class);
myIntent.putExtra("uri", uri);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
setResult(RESULT_OK, myIntent);
startActivity(myIntent);
In your other activity or where your listview is defined, use this to retrieve the uri,
Intent data = getIntent();
Uri uri = data.getParcelableExtra("uri");
Now you can use this uri to get whatever information you are trying to retrieve.
Hope this answer helps .. :)
The code below defines a simple ListView with a listener that calls a simple ViewPager by passing selected item in parameters.
First the list:
public class SampleListFragment extends android.support.v4.app.ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ArrayList<String> list = new ArrayList<String>();
list.add("object1");
list.add("object2");
list.add("object3");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, list);
getListView().setAdapter(adapter);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final String item = (String) adapterView.getItemAtPosition(i);
// Quick and dirty way to call the ViewPager with the selected item
final SampleViewPagerFragment sampleViewPagerFragment = SampleViewPagerFragment.newIntance(item);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, sampleViewPagerFragment).commit();
}
});
}
}
Next the ViewPager:
public class SampleViewPagerFragment extends Fragment {
public static SampleViewPagerFragment newIntance(String text){
final SampleViewPagerFragment sampleViewPagerFragment = new SampleViewPagerFragment();
final Bundle arguments = new Bundle();
arguments.putString("object", text);
sampleViewPagerFragment.setArguments(arguments);
return sampleViewPagerFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, null);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
final Bundle arguments = getArguments();
if(arguments != null){
// We create the adapter with arguments of the fragment
final SampleAdapter adapter = new SampleAdapter(getChildFragmentManager(), (String) arguments.get("object"));
viewPager.setAdapter(adapter);
}
return view;
}
private class SampleAdapter extends FragmentPagerAdapter {
private String object;
public SampleAdapter(FragmentManager fm, String object){
super(fm);
this.object = object;
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
// We pass the selected item in arguments
return SampleFragment.newInstance(object + " " + position);
}
}
}
Finally the fragment that displays the content:
public class SampleFragment extends Fragment {
public static SampleFragment newInstance(String text){
final SampleFragment sampleFragment = new SampleFragment();
final Bundle arguments = new Bundle();
arguments.putString("text", text);
sampleFragment.setArguments(arguments);
return sampleFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final TextView textView = new TextView(getActivity());
final Bundle arguments = getArguments();
if(arguments != null){
textView.setText((String) arguments.get("text"));
}
return textView;
}
}
I hope it is what you are looking for..

ViewPager FragmentPagerAdapter only updates last fragment onNavigationItemSelected

I have a ViewPager hosted in a fragment that hosts two ListFragments that are populated by a Cursor returned from an SQLite query. I recently added a spinner to my Action Bar that will allow the user to sort the lists in the ViewPager. However, every time the spinner is selected, only the second list is sorted even when the first list is currently displayed. It seems like the ViewPager is not keeping track of the currently displayed ListFragment.
I have tried overriding getItemPosition in my adapter and using notifyDataSetChanged, but that doesn't help. I tried caching the position of the current active fragment in onAttach() also to no avail. I also tried using an OnSortChanged interface implemented by my adapter to try and recreate the ListFragments. I'm truly at a loss here. Here is my current code:
My main fragment:
public class BeerMenuFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.beer_menu_fragment, container,
false);
ViewPager pager = (ViewPager) view.findViewById(R.id.beer_pager);
pager.setAdapter(buildAdapter());
return view;
}
private PagerAdapter buildAdapter() {
return (new BeerMenuAdapter(getChildFragmentManager()));
}
}
My FragmentPagerAdapter:
public class BeerMenuAdapter extends FragmentPagerAdapter {
private final int NUM_ITEMS = 2;
public BeerMenuAdapter(FragmentManager fm) {
super(fm);
}
/*
* (non-Javadoc)
*
* #see android.support.v4.view.PagerAdapter#getPageTitle(int)
*/
#Override
public CharSequence getPageTitle(int position) {
return BeerListFragment.getTitle(position);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
return BeerListFragment.newInstance(position);
}
}
And finally, the ListFragment:
public class BeerListFragment extends SherlockListFragment implements
OnNavigationListener {
private static final String KEY_POSITION = "position";
private static final String KEY_SPINNER = "ab_spinner";
private IconicAdapter adapter;
private static final String[] LABELS = { "Newest First", "Oldest First",
"Alphabetical" };
private Context ctxt;
private int mShowItems;
private Cursor data;
private boolean synthetic = true;
static BeerListFragment newInstance(int position) {
BeerListFragment frag = new BeerListFragment();
Bundle args = new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return (frag);
}
static String getTitle(int position) {
String header = "Draft";
switch (position) {
case 0:
header = "Draft";
break;
case 1:
header = "Bottle";
break;
}
return (header);
}
/*
* (non-Javadoc)
*
* #see
* android.support.v4.app.ListFragment#onCreateView(android.view.LayoutInflater
* , android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.menu_list_fragment, container,
false);
ctxt = getActivity().getApplicationContext();
SQLiteDatabase db = DatabaseHelper.getInstance(ctxt)
.getReadableDatabase();
SherlockFragmentActivity activity = getSherlockActivity();
ArrayAdapter<String> show = null;
ActionBar bar = activity.getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
show = new ArrayAdapter<String>(bar.getThemedContext(),
android.R.layout.simple_spinner_item, LABELS);
} else {
show = new ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_item, LABELS);
}
show.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(show, this);
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState
.getInt(KEY_SPINNER));
}
data = getBeerMenuDbData(db, mShowItems);
// set up list adapter
adapter = new IconicAdapter(ctxt, data);
setListAdapter(adapter);
return (result);
}
private Cursor getBeerMenuDbData(SQLiteDatabase db, int showItems) {
String order;
String WHERE;
switch (showItems) {
case 1: // Oldest First
order = DbContract.BeerEntry.COLUMN_MODIFIED + " ASC";
break;
case 2: // Alphabetical
order = DbContract.BeerEntry.COLUMN_TITLE + " ASC";
break;
default: // Newest first
order = DbContract.BeerEntry.COLUMN_MODIFIED + " DESC";
break;
}
String[] COLUMNS = { DbContract.BeerEntry._ID,
DbContract.BeerEntry.COLUMN_TITLE,
DbContract.BeerEntry.COLUMN_MODIFIED };
WHERE = "serving='" + getTitle(getArguments().getInt(KEY_POSITION, -1))
+ "'";
return db.query(DbContract.BeerEntry.TABLE_NAME, COLUMNS, WHERE, null,
null, null, order);
}
class IconicAdapter extends CursorAdapter {
LayoutInflater inflater;
IconicAdapter(Context context, Cursor data) {
super(context, data, 0);
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String dateString = cursor.getString(2);
String[] dateArray = new String[3];
TextView beerName = (TextView) view.findViewById(R.id.beerName);
TextView date = (TextView) view.findViewById(R.id.drinkDate);
RatingBar rb = (RatingBar) view.findViewById(R.id.ratingBar1);
beerName.setText(cursor.getString(1));
if (!dateString.isEmpty()) {
dateArray = dateString.split("-");
date.setText(dateArray[1] + "/" + dateArray[2] + "/"
+ dateArray[0]);
} else {
date.setText(dateString);
}
rb.setRating((float) Math.random() * 5.0f);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater
.inflate(R.layout.beer_club_list_item, parent, false);
}
}
/*
* (non-Javadoc)
*
* #see android.support.v4.app.Fragment#onDestroy()
*/
#Override
public void onDestroy() {
super.onDestroy();
((CursorAdapter) getListAdapter()).getCursor().close();
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (synthetic) {
synthetic = false;
return true;
}
mShowItems = itemPosition;
SQLiteDatabase db = DatabaseHelper.getInstance(ctxt)
.getReadableDatabase();
Cursor newData = getBeerMenuDbData(db, mShowItems);
adapter.changeCursor(newData);
return true;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_SPINNER, getSherlockActivity()
.getSupportActionBar().getSelectedNavigationIndex());
}
}
Thanks in advance for any help!
So, your problem is that you are calling bar.setListNavigationCallbacks(show, this) inside of your BeerListFragments. When your 1st BeerListFragment is created in your ViewPager, it sets itself as the callback for the navigation selections. Then, when your 2nd BeerListFragment is created (ViewPagers resumes pages to the left and right of the currently visible page), it sets itself as the callback for the navigation selections, and overwrites the 1st BeerListFragment, which now will no longer get the onNavigationItemSelected callback.
This all results with the behavior you are seeing, the last BeerListFragment to call bar.setListNavigationCallbacks will be the only one to receive the onNavigationItemSelected callback. This is why only the 2nd BeerListFragment is being sorted.
To solve this, I would recommend you do a few things:
Manage setting the callback for the navigation selections in the BeerMenuFragment, and pass the results to the children Fragments that are in "alive" (in onResume). You will need to use one of the answers here in order to do so.
Store the the latest sort option applied, and check in onResume of each BeerListFragment to see if its sort matches, and if not, apply the sort.
This will guarantee that all of your sorts are applied to all of your pages in the ViewPager, whether they are displayed or not at the time of the sort being applied.

Categories

Resources