Android scrollable list - android

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...

Related

my ViewPage does not work correctly in another Fragment

I have Strange problem
I Use frame layout and inside it I use Some Fragment Like Below And Handle Fragment With Bottom Bar
Now in One Of These Fragment I Use ViewPager And TabLayout Like Below
My Problem Is when Change Fragment From for exmple first to Third
First time change correctly but for
second time it does not work correctly and some thing happened like below
This is code for third Fragment Load (Just Load ViewPager)
public class Social extends Fragment {
// 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 TabLayout tabLayout;
private BestMonth b,b1;
private ViewPager viewPager;
private OnFragmentInteractionListener mListener;
public Social() {
// Required empty public constructor
b= new BestMonth();
b1= new BestMonth();
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Social.
*/
// TODO: Rename and change types and number of parameters
public static Social newInstance(String param1, String param2) {
Social fragment = new Social();
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 View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_social, container, false);
viewPager = (ViewPager)view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null);
tabOne.setText("برترین های ماه");
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null);
tabTwo.setText("محمبوب ترین ها");
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(b, "بهترین ها");
adapter.addFragment(b1, "برترین ها");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* 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
void onFragmentInteraction(Uri uri);
}
}
And This Fragment Load Content Of ViewPager Inside Third Fragment
public class BestMonth extends Fragment {
// 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 FloatingActionButton floatingActionButton;
private List<SocialInsClass> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private PostAdapter mAdapter;
private OnFragmentInteractionListener mListener;
public BestMonth() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BestMonth newInstance(String param1, String param2) {
BestMonth fragment = new BestMonth();
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 View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_best_month, container, false);
view = Init(view);
return view;
}
private void prepareMovieData() {
movieList.clear();
SocialInsClass movie = new SocialInsClass("آرش", "https://ig-s-b-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/s150x150/17267780_1886609681623949_4740572605386326016_a.jpg", "گل من", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima712.jpg");
movieList.add(movie);
movie = new SocialInsClass("راضیه", "https://ig-s-c-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/14134653_740842746053754_866503745_a.jpg", " قابل شما رو ندار", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima308.jpg");
movieList.add(movie);
movie = new SocialInsClass("یگانه", "https://ig-s-a-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/s150x150/17663339_736255433209640_3627796035541139456_a.jpg", "گل دون منزل من", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima953.jpg");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
private View Init(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_views);
floatingActionButton= (FloatingActionButton) view.findViewById(R.id.post);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), SendPost.class));
}
});
mAdapter = new PostAdapter(movieList, getActivity());
prepareMovieData();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Thank You So Much For Your Guide
:)
1) First Fragment 2) Third Fragment I am Using ViePager In It(Load Correctly) 3)When Choose in second time and does not work corectly

ListView not displaying information

I am trying to save some information when I click a button from the "new project" page. Afterwards, I want to save this information in the "Projects" pages and display it in "My projects" page. For some reason, it doesn't display anything. Help, please?
new project page:
public class NewProjectFragment extends Fragment {
// 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;
LinearLayout container;
TextView new_project;
String tv_project_name;
private OnFragmentInteractionListener mListener;
public NewProjectFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment NewProjectFragment.
*/
// TODO: Rename and change types and number of parameters
public static NewProjectFragment newInstance(String param1, String param2) {
NewProjectFragment fragment = new NewProjectFragment();
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);
}
}
Button addButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_project, container, false);
new_project=(TextView) view.findViewById(R.id.textView_new_project);
tv_project_name= (String) new_project.getText();
addButton= (Button) view.findViewById(R.id.button_add_project);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
addItem(tv_project_name);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* 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
void onFragmentInteraction(Uri uri);
}
public void addItem(String name) {
Projects project=new Projects();
project.addItem(tv_project_name);
}
}
my project page:
public class MyProjectsFragment extends Fragment {
// 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 OnFragmentInteractionListener mListener;
public MyProjectsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MyProjectsFragment.
*/
// TODO: Rename and change types and number of parameters
public static MyProjectsFragment newInstance(String param1, String param2) {
MyProjectsFragment fragment = new MyProjectsFragment();
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);
}
}
ListView listView;
ArrayList<String> listItems= Projects.getArrayList();
ArrayAdapter<String> adapter;
#Override
public void onStart() {
super.onStart();
adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
Create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_projects, container, false);
listView=(ListView) view.findViewById(R.id.listview_projects);
listItems= new ArrayList<String>();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* 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
void onFragmentInteraction(Uri uri);
}
public void Create() {
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
}
});*/
}
}
projects class:
public class Projects {
static ArrayList<String> names= new ArrayList<String>();
public void addItem(String name)
{
names.add(name);
}
public static ArrayList getArrayList()
{
return names;
}
}
Each time you enter My Project ,you did listItems= new ArrayList<String>() in onCreateView. It has no data definately.
And when you addItem each time, you initialize a new Project,which is weird.
My advice is:
public class Projects {
static ArrayList<String> names= new ArrayList<String>();
public static void addItem(String name)
{
names.add(name);
}
public static ArrayList getArrayList()
{
return names;
}
}
Project.getArrayList() to getList
Project.addItem("") to add data
This way is not very properly yet,but it should work.

My ViewPager is blank when I click back, Its not showing the list

I have an issue where my view pager is showing blank fragment when I back press.
I have a grid fragment(consider Fragment A) where when I click on a button its navigates me to another grid fragment(Consider Fragment B),when I click on a button it navigates me to a ViewPager(Fragment C) which has three Slidingtabs. each Tab layout has a listview in which if I select an item it navigates me to another fragment(Fragment D).My problem is when I backpress from Fragment D the ViewPager sliding tabs(Fragment C) are showing blank empty screen.Can anyone tell me how to resolve this issue.
public class RetrievalListOperation extends Fragment {
// 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;
List<VehicleInfo> vehicleInfos=new VehicleInfoData().getVehicleData();
DataService dataService;
List<VinInfoDTO> retlist;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RetrievalListOperation.
*/
// TODO: Rename and change types and number of parameters
public static RetrievalListOperation newInstance(String param1, String param2) {
RetrievalListOperation fragment = new RetrievalListOperation();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public RetrievalListOperation() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrieval_list_operation, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
dataService=new DataService(getActivity());
retlist=dataService.getRetrievalJobsForStatus("Open");
super.onViewCreated(view, savedInstanceState);
RecyclerView rv = (RecyclerView) getActivity().findViewById(R.id.retrieval_operation_rview);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity().getApplicationContext());
rv.setLayoutManager(llm);
RetrievalOpenAdapter adapter=new RetrievalOpenAdapter(retlist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecycleItemClickListener(getActivity().getApplicationContext(), new RecycleItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
final TextView vin=(TextView)view.findViewById(R.id.ret_txt_VIN);
final TextView model=(TextView)view.findViewById(R.id.ret_txt_model);
final TextView variant=(TextView)view.findViewById(R.id.ret_txt_variant_no);
final TextView desc=(TextView)view.findViewById(R.id.ret_txt_description);
// final TextView color=(TextView)view.findViewById(R.id.ret_txt_color);
String VIN=vin.getText().toString();
Log.e("--Recycler onTouch VIN-", VIN);
JobsDTO det = dataService.getVehicleDetails(VIN);
String detail=det.JobID+" / SyncStatus: "+det.SyncStatus+" /Location Lat"+det.locationDTO.Latitude+" lng"+det.locationDTO.Longitude;
Log.e("---RetoPenList---", detail);
Bundle b=new Bundle();
b.putString("VIN", VIN);
b.putString("model", model.getText().toString());
b.putString("variant", variant.getText().toString());
b.putString("desc",desc.getText().toString());
// b.putString("color",color.getText().toString());
b.putString("job id",det.JobID);
Log.e("---Bundle Values--", " MODEL: " + model.getText().toString() + " VARIANT :" + variant.getText().toString() + " DESC:" + desc.getText().toString() + " COLOR :" );
Fragment fragment=new RetrievalMapOperation().newInstance("a" ," b");
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).addToBackStack("RetrievalList")
.commit();
fragment.setArguments(b);
}
})
);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* 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(Uri uri);
}
public class RetrievalOpenAdapter extends RecyclerView.Adapter<RetrievalOpenAdapter.ViewHolder>
{
List<VinInfoDTO> vinfo;
RetrievalOpenAdapter(List<VinInfoDTO> vinfo)
{
this.vinfo=vinfo;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.operationscardlayout, parent, false);
ViewHolder pvh = new ViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.vehicleNumber.setText(vinfo.get(position).VIN);
holder.variantNumber.setText(vinfo.get(position).Variant);
// holder.color.setText(vinfo.get(position).Color);
holder.desc.setText(vinfo.get(position).Desc);
holder.model.setText(vinfo.get(position).Model);
// Log.e("--RetCOLOR--",""+holder.color.getText().toString());
// holder.time.setText(vinfo.get(position).getTime());
}
#Override
public int getItemCount() {
return vinfo.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView vehicleNumber;
TextView variantNumber;
TextView model,color,desc ;
public ViewHolder(View itemView) {
super(itemView);
cv=(CardView)itemView.findViewById(R.id.operation_retrieval_cview);
vehicleNumber=(TextView)itemView.findViewById(R.id.ret_txt_VIN);
variantNumber=(TextView)itemView.findViewById(R.id.ret_txt_variant_no);
model=(TextView)itemView.findViewById(R.id.ret_txt_model);
// color= (TextView)itemView.findViewById(R.id.ret_txt_color);
desc=(TextView)itemView.findViewById(R.id.ret_txt_description);
//time=(TextView)itemView.findViewById(R.id.txt_srtime);
}
}
}
}
RetrievalTabs.java(slidinglayout)
public class RetrievalTabs extends Fragment {
NavigationDrawerActivity nav;
// 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;
CharSequence Titles[] = {"Open", "WIP", "Complete"};
int Numboftabs = 3;
ViewPager pager;
FrameLayout frameLayout;
LinearLayout linear;
private TextView actionBarTitle;
SlidingTabLayout tabs;
RetrievalPagerAdapter adapter;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RetrievalTabs.
*/
// TODO: Rename and change types and number of parameters
public static RetrievalTabs newInstance(String param1, String param2) {
RetrievalTabs fragment = new RetrievalTabs();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public RetrievalTabs() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
View actionBarCustomView = getActivity().getActionBar().getCustomView();
actionBarTitle = (TextView) actionBarCustomView.findViewById(R.id.head_text);
actionBarTitle.setText("Retrieval");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrieval_tabs, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tabs = (SlidingTabLayout) getActivity().findViewById(R.id.retrieval_tabs);
adapter = new RetrievalPagerAdapter(getFragmentManager(), Titles, Numboftabs);
pager = (ViewPager) getActivity().findViewById(R.id.retrieval_pager);
pager.setAdapter(adapter);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* 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(Uri uri);
}
}
RetrievalPagerAdapter.java
public class RetrievalPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
android.app.Fragment tab1, tab2, tab3;
FragmentManager fm;
MyApplication app;
public RetrievalPagerAdapter(FragmentManager fm, CharSequence mTitles[], int NumOfTabs) {
super(fm);
this.fm = fm;
this.Titles = mTitles;
this.NumbOfTabs = NumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
#Override
public android.app.Fragment getItem(int position) {
if (position == 0) {
tab1 = new RetrievalListOperation().newInstance("a", "b");
return tab1;
} else if (position == 1) {
tab2 = new RetrievalInProgressList().newInstance("a", " b");
return tab2;
} else {
tab3 = new RetrievalCompletedList().newInstance("a", "b");
return tab3;
}
}
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
}

Arguments keep Returning Empty

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;
}

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..

Categories

Resources