I want to create an add to favorites action bar button on the news and if the button is clicked, add the news to a new list adapter in the favorites tab, can you help me please implementing the button and tell me how to create the new list?
here is my code: (displaying the clicked news)
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
}
here is the code for the listView:
public class Noutati1 extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.noutati);
context = this;
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
sitesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String Title = mAdapter.getItem(pos).getName();
String nDate = mAdapter.getItem(pos).getnDate();
String ImageUrl = mAdapter.getItem(pos).getImgUrl();
String Text = mAdapter.getItem(pos).getnText();
String VideoUrl = mAdapter.getItem(pos).getVideoUrl();
Intent i = new Intent(context, ListItemClicked.class);
//i.setData(Uri.parse(VideoUrl));
i.putExtra("pname", Title);
i.putExtra("pdate", nDate);
i.putExtra("pText", Text);
i.putExtra("pImage", ImageUrl);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Noutati1.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://www.link..../news.xml", openFileOutput("news.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(context, -1, SitesXmlPullParser.getStackSitesFromFile(Noutati1.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = " + mAdapter.getCount());
}
}
}
You can add button to layout of item in Recyclerview or ListView.
Then set action ClickItemListener. When click add button you can store this data of row item you clicked to Shared Preferences or Sqlite. When you open tab favorite reload view and get data from data you stored.
Related
Movie ListView Fragment
Movie Info Fragment
What I have is an app that has a database of movies, in my first tab fragment I have a listview which has all the movies in my database. I want it so when I click a movie in the listview it grabs the movie's database id and moves to the next tab which displays the movie info.
Main Activity (The activity that holds my tabs view pager)
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#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);
}
public static class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentMain();
case 1:
return new FragmentManuallyAddMovie();
case 2:
return new FragmentAddInternetMovie();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "MOVIES";
case 1:
return "ADD";
case 2:
return "SEARCH";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
FragmentMain (Where the movies database is displayed in a listview)
public class FragmentMain extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {
private MoviesDBHandler handler;
private SimpleCursorAdapter adapter;
private ListView lvMovies;
public FragmentMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
handler = new MoviesDBHandler(this.getActivity());
v.findViewById(R.id.btn_delete_all_movies).setOnClickListener(this);
lvMovies = (ListView) v.findViewById(R.id.lv_movies);
lvMovies.setEmptyView(v.findViewById(R.id.tv_instructionsa));
lvMovies.setOnItemClickListener(this);
lvMovies.setOnItemLongClickListener(this);
return v;
}
#Override
public void onResume() {
super.onResume();
String[] from = {MoviesDBHelper.MOVIES_TITLE, MoviesDBHelper.MOVIES_GENRE, MoviesDBHelper.MOVIES_YEAR, MoviesDBHelper.MOVIES_PLOT, MoviesDBHelper.MOVIES_RATING, MoviesDBHelper.MOVIES_RUNTIME, MoviesDBHelper.MOVIES_IMAGE_URL};
int[] to = {R.id.tv_title, R.id.tv_genre, R.id.tv_year, R.id.tv_plot, R.id.tv_rating, R.id.tv_runtime, R.id.img_movie_poster};
adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.movie_list_item, handler.getMovies(), from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == cursor.getColumnIndex(MoviesDBHelper.MOVIES_IMAGE_URL)) {
DatabaseDownloadImage task = new DatabaseDownloadImage((ImageView) view);
task.execute(cursor.getString(columnIndex));
return true;
}
return false;
}
});
lvMovies.setAdapter(adapter);
}
public class DatabaseDownloadImage extends AsyncTask<String, Integer, Bitmap> {
private ImageView imageView;
public DatabaseDownloadImage(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
String address = params[0];
HttpURLConnection connection = null;
Bitmap b = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
else {
b = BitmapFactory.decodeStream(connection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap == null) {
return;
}
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 180, false));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//Delete all movies from database
case R.id.btn_delete_all_movies:
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete All Movies?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteAllMovies();
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete Movie?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteMovie(id);
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
return true;
}
}
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
http://developer.android.com/intl/es/training/basics/fragments/communicating.html
You can communicate the two fragments with a static variable in the MainActivity that you change in the first fragment and get the content of this variable in the second fragment.
Update:
Create Movie.class, to save all the data of a one movie:
public class Movie() {
String title;
String genre;
int year;
String plot;
int rating;
int runtime;
String img;
public Movie(String title, String genre, int year, String plot, int rating, int runtime, String img) {
this.title=title;
this.genre=genre;
this.year=year;
this.plot=plot;
this.rating=rating;
this.runtime=runtime;
this.img=img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title=title;
}
//The same for the other variables
}
and in your MainActivity create a static variable of Movie:
public static Movie movie;
In onClick method save the data of the movie:
MainActivity.movie=new Movie(title, genre, year,plot,rating,runtime,img);
And to get the movie in the second fragment:
String title=MainActivity.movie.getTitle();
String genre=MainActivity.movie.getGenre();
...
I have 3 activities:
1. The list of categories;
2. The news in this category;
3. Details about News
see the images below!
I implemented back button from the third activity to the second by setting the second activity as the parent activity for the third activity in the android manifest file, but it can not see the category that is chosen in the first activity so it doesn't display the list and crash, can anybody help me implementing back button?
here is the code of activity where i want to implement the back button
public class Categorii_LIst_Item_Clicked extends ActionBarActivity {
static Context context;
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorii__list__item__clicked);
context = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_categorii__list__item__clicked, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return PlaceholderFragment.newInstance(position);
} else if (position == 1) {
return VideoFragment.newInstance1(position);
}
return PlaceholderFragment.newInstance(position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText(extras.getString("pdate"));
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText(extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener() {
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage(extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
public static class VideoFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static VideoFragment newInstance1(int sectionNumber) {
VideoFragment fragment = new VideoFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public VideoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.video_fragment, container, false);
VideoView myVideoView = (VideoView) rootView.findViewById(R.id.videoView);
Uri video = Uri.parse(extras.getString("pVideo"));
myVideoView.setMediaController(new MediaController(context));
myVideoView.setVideoURI(video);
myVideoView.requestFocus();
//myVideoView.start();
return rootView;
}
}
}
When you specify parent activity in manifest for Up Navigation like this:
android:parentActivityName
and when you click on Up button in action bar, the parent activity gets restarted (in your case it is category activity), instead to avoid activity get restarted. just finish the top activity by putting this code in your 3rd activity (i.e Details about News).
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
and remove the parentActivityName from manifest.
i am working on a xml parsing app- news app.
I've parsed the xml file and transformed it to the listView, and when i click the news i see more detailed info about it. I'd like to implement the "add to favorites" button so that it appears in a list in favorites tab (i've implemented the favorites tab in the tabhost in main activity), can anybody help me to do this? (I don't know how to implement action bar button (add to favorites) and how by clicking it to add it to a listview). Thanks!!!!
here is the code for listItemClicked
package com.example.andrian.jurnaltv;
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
}
I have an activity that holds 2 fragments, one for list and one for detail. What I would like to do is, whenever a list item is clicked the related parameters will be sent to detail fragment. But I couldn't achieve it.
Here is activity:
public class ActivityMain extends ActionBarActivity{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
List<String> naviList = new ArrayList<String>();
ViewPager mViewPager;
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawer;
ListView navList;
DrawerAdapter naviAdapter;
private static final int GRAVITY = Gravity.LEFT;
private static final String jsonURL = "";
List<String> categories = new ArrayList<String>();
int check = -1, listCheck = 0;
Dialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//some methods (e.g. navi-drawer etc.)
}
#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);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.medicalendar_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ListFragment.newInstance("FirstFragment, Default");
case 1:
return DetailFragment.newInstance("DetailFragment, Detail");
default:
return ListFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
private boolean version() {
if (Build.VERSION.SDK_INT > 11) {
return true;
} else {
return false;
}
}
My List Fragment:
public class ListFragment extends Fragment {
ListView list;
LazyAdapter adapter;
List<String> naviList = new ArrayList<String>();
RelativeLayout loading;
EventsParser parser;
List<Event> events = new ArrayList<Event>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_list, container, false);
parser = new EventsParser("");
events = parser.getITEMS();
list = (ListView) v.findViewById(R.id.list);
adapter = new LazyAdapter(getActivity(), events);
list.setAdapter(adapter);
return v;
}
public static ListFragment newInstance(String text) {
ListFragment f = new ListFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
My Detail Fragment:
public class DetailFragment extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_detail, container, false);
ImageButton imageButton = (ImageButton) v.findViewById(R.id.d_map);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "Navigating...", Toast.LENGTH_LONG).show();
}
});
return v;
}
public static DetailFragment newInstance(String text) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
If you could help me I would be greatly appriciated.
Best,
Basically you don't need ViewPager for navigating from one fragment to another. This should be achieved with replacing fragments using FragmentTransaction class, that will allow you to pass parameters in transaction. http://developer.android.com/reference/android/app/FragmentTransaction.html
If you still need ViewPager, you should set tag for each fragment with
fragment.setTag("detail_fragment");
and than your onListItemClick method should look like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get detail fragment instance by it's tag
DetailFragment detail = (DetailFragment) getActivity().getFragmentManager().findFragmentByTag("detail_fragment");
detail.setParam("data"); //you should define this method in your detail fragment
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}
I'm getting error stating "mImages & stringArray cannot be resolved to a variable" however I'm unsure why. I have used the following example and I'm pretty sure I've followed it very closely.
Different text for each image in image viewpager
ERROR LOCATIONS:
mImages cannot be resolved to a variable:
ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages, stringArray);
stringArray cannot be resolved to a variable:
uploader.setText(stringArray[position]);
SOURCE: Home.java
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "idconex";
Activity activity;
int imageArray[];
String[] stringArray;
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages, stringArray);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
// Here we are adding this activity as a listener for when any row in
// the List is 'clicked'
// The activity will be sent back the video that has been pressed to do
// whatever it wants with
// in this case we will retrieve the URL of the video and fire off an
// intent to view it
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
// This is the interface method that is called when a video in the listview
// is clicked!
// The interface is a contract between this activity and the listview
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages, String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
// setOnPageChangeListener(mPageChangeListener);
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
private String[] stringArray = new String[] {"vevo", "TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO", "EminemVEVO"};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
// Calc if swipe was left to right, or right to left
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
PLAYLIST.replace("TimMcGrawVEVO", PLAYLIST);
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
PLAYLIST.replace("TimMcGrawVEVO", PLAYLIST);
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
SOURCE: VideosAdapter
public class VideosAdapter extends BaseAdapter {
// The list of videos to display
List<Video> videos;
// An inflator to use when creating rows
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
/**
* #param context this is the context that the list will be shown in - used to create new list rows
* #param videos this is a list of videos to display
*/
public VideosAdapter(Context context, List<Video> videos) {
this.videos = videos;
this.mInflater = LayoutInflater.from(context);
my_context = context;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our list_item_user_video so no need to do it again
if(convertView == null){
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video, parent, false);
}
// We are using a custom imageview so that we can load images using urls
// For further explanation see: http://blog.blundell-apps.com/imageview-with-loading-spinner/
UrlImageView thumb = (UrlImageView) convertView.findViewById(R.id.userVideoThumbImageView);
TextView title = (TextView) convertView.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView.findViewById(R.id.userVideouploaderTextView);
// TextView uploader = (TextView) layout.findViewById(R.id.userVideouploaderTextView);
uploader.setText(stringArray[position]);
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Video video = videos.get(position);
// Set the image for the list item
thumb.setImageDrawable(video.getThumbUrl());
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
}
You don't have a stringarray, you have videos in VideoAdapter.java. So you should do something like uploader.setText(videos.get(position).getTitle())