In the following code I have set up a fragment that shows 2 ListViews.
When the main activity call the Fragment methods:
prendiListaBest
and
prendiListaWorst
they call notifyDataSetChanged() on the adapters,
therefore the lists should update with the new contents of the ArrayLists.
But this does not happen.
Please any help and suggestion more than welcome
public class WorstBest extends Fragment {
public ListView lvBest;
public ListView lvWorst;
public MyAdapter myAdap;
public MyAdapter myAdap2;
public ArrayList<Stock> best;
public ArrayList<Stock> worst;
public View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.listaworstbest, container, false);
lvBest= (ListView)v.findViewById(R.id.listbest);
lvWorst=(ListView)v.findViewById(R.id.listworst);;
myAdap= new MyAdapter(best, getActivity());
myAdap2= new MyAdapter(worst, getActivity());
lvBest.setAdapter(myAdap);
lvWorst.setAdapter(myAdap2);
return v;
}
public void prendiListaBest(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment worstbest");
best=al;
Log.e("", "nel fragment best è" + Integer.toString(best.size()));
myAdap.notifyDataSetChanged();
}
public void prendiListaWorst(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment worstbest");
worst=al;
Log.e("", "nel fragment worst è" + Integer.toString(worst.size()));
myAdap2.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
}
This is the code of my custom adapter.
I posted as requested but I apologize because it is really messy:
public class MyAdapter extends BaseAdapter {
ArrayList<Stock> l;
Activity a;
public MyAdapter(ArrayList<Stock> li, Activity ac) {
// TODO Auto-generated constructor stub
l = li;
a=ac;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
if (row==null) {
LayoutInflater inflater=a.getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView tw=(TextView)row.findViewById(R.id.textView1);
String st=l.get(position).simbolo;
String st1=st;
String st2=st;
String st3=st;
String st4=st;
String st5=st;
String st6=st;
String st7=st;
String st8=st;
st8=st;
if(st.length()<=7){st1=st.concat(" ");st2=st1;st3=st1;st4=st1;st5=st1;st6=st1;st7=st1;st8=st1;}
if(st1.length()<=7){st2=st1.concat(" ");st3=st2;st4=st2;st5=st2;st6=st2;st7=st2;st8=st2;}
if(st2.length()<=7){st3=st2.concat(" ");st4=st3;st5=st3;st6=st3;st7=st3;st8=st3;}
if(st3.length()<=7){st4=st3.concat(" ");st5=st4;st6=st4;st7=st4;st8=st4;}
if(st4.length()<=7){st5=st4.concat(" ");st6=st5;st7=st5;st8=st5;}
if(st5.length()<=7){st6=st5.concat(" ");st7=st6;st8=st6;}
if(st6.length()<=7){st7=st6.concat(" ");st8=st7;}
if(st7.length()<=7){st8=st7.concat(" ");}
tw.setText(st8);
String allora=(String) tw.getText();
TextView tw2=(TextView)row.findViewById(R.id.nome);
///aggiungiamo numero minimo caratteri
tw2.setText((l.get(position).nome));
///
TextView tw3=(TextView)row.findViewById(R.id.prezzo);
tw3.setText((l.get(position).prezzo));
TextView tw4=(TextView)row.findViewById(R.id.cambiamento);
tw4.setText((l.get(position).cambiamento).concat(" %"));
try {
double value = Double.parseDouble(l.get(position).cambiamento);
if(value<0)tw4.setTextColor(Color.RED);
if(value>0)tw4.setTextColor(Color.GREEN);
TextView tw5=(TextView)row.findViewById(R.id.freccia);
if(value<0)tw5.setText("▼");
if(value>0)tw5.setText("▲");
if(value<0)tw5.setTextColor(Color.RED);
if(value>0)tw5.setTextColor(Color.GREEN);
} catch (Exception exc) {}
return row;
}
public int getCount() {
// TODO Auto-generated method stub
return l .size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return l .get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT *EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT *
Thank you very much, the answer makes perfectly sense.**
But I do not understand why the same Adapter works fine with the following fragment; I explain:
the following "listafragment" fragment has a similar logic, it uses the
prendiLista
method to retrieve the latest version of the
ListArray lt
exactly the same way it is done in the previous "WorstBest" fragment.
But in this case when
public void prendiLista(ArrayList<Stock> al){
lt=al;
myAdap.notifyDataSetChanged();
}
the view is updated !!!
Please what is the difference??? :-)
IN MY UNDERSTANDING THE CALL TO notifyDataSetChanged() WAS ENOUGH TO UPDATE THE VIEW !!
Thanks a lot anyway! (I will accept answer tomorrow morning).
public class listafragment extends Fragment {
public ListView lv;
public MyAdapter myAdap;
public ArrayList<Stock> lt;
public View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.lista, container, false);
lv= (ListView) v.findViewById(android.R.id.list);
if(lv==null){Log.e("","nel fragment la lista è nulla");}
if(lv!=null){Log.e("","nel fragment la lista NON è nulla");}
myAdap= new MyAdapter(lt, getActivity());
lv.setAdapter(myAdap);
return v;
}
public void prendiLista(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment");
lt=al;
if(myAdap==null){Log.e("","nel prendilista del fragment myadapt è nullo");};
myAdap.notifyDataSetChanged();
}
public void addToFavorites(int pos){
Quotes.addToFavorites(pos);
}
#Override
public void onCreate(Bundle savedInstanceState){
lt=Quotes.dammi();
super.onCreate(savedInstanceState);
}
}
therefore the lists should update with the new contents of the ArrayLists.
Unfortunately no. When your app first runs l and best both reference the same data. You have this set up.
Fragment:
best ---\
|
|--- <the initial data>
Adapter: |
l ------/
But after you call best=al, you have:
Fragment:
best ------- <the new data>
Adapter:
l ---------- <the initial data>
So you never update the reference in your Adapter. Either add a new method to your custom Adapter to change l or use l itself since you didn't declare it as private:
public void prendiListaBest(ArrayList<Stock> al){
myAdap.l=al;
myAdap.notifyDataSetChanged();
}
Related
public class AdapterListView extends BaseAdapter {
Context context;
ArrayList<String> brands;
public AdapterListView(ArrayList<String> brands, Context context) {
this.brands = brands;
this.context = context;
}
#Override
public int getCount() {
return brands.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view= LayoutInflater.from(context).inflate(R.layout.activity_listview,null);
ListView lv=(ListView)view.findViewById(R.id.mobile_list);
lv.setText(brands.get(i));
return view;
}
}
setText has error and displaying (cannot resolve method,settext(java.lag.string))
my message fragment class is given bellow am actually trying to set a listview
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_messages, container, false);
brands.add("microsoft");
brands.add("ios" );
brands.add("android");
AdapterListView adapter = new AdapterListView(brands,getActivity());
ListView listView = (ListView)rootView.findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return rootView;
}
i need to print the list brands.is thr any error in the way i set the listview
setText has error and displaying (cannot resolve
method,settext(java.lag.string))
Because setText method is not defined in ListView class.
Use TextView,EditText,Button like views for using setText method
instead of
ListView lv=(ListView)view.findViewById(R.id.mobile_list);
lv.setText(brands.get(i));
you have to take TextView in your R.layout.activity_listview
and than code should be
TextView tv=(TextView)view.findViewById(R.id.textViewId);
tv.setText(brands.get(i));
As the title I want to create a listview with custom row in Fragment. My code below.
Fragment class
public class PhotosFragment extends Fragment{
public PhotosFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
ArrayList<ListviewContactItem> listContact = GetlistContact();
ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);
lv.setAdapter(new ListviewContactAdapter(getActivity(), listContact));
return rootView;
}
private ArrayList<ListviewContactItem> GetlistContact(){
ArrayList<ListviewContactItem> contactlist = new ArrayList<ListviewContactItem>();
ListviewContactItem contact = new ListviewContactItem();
contact.SetName("Topher");
contact.SetPhone("01213113568");
contactlist.add(contact);
contact = new ListviewContactItem();
contact.SetName("Jean");
contact.SetPhone("01213869102");
contactlist.add(contact);
contact = new ListviewContactItem();
contact.SetName("Andrew");
contact.SetPhone("01213123985");
contactlist.add(contact);
return contactlist;
}
}
Adapter class
public class ListviewContactAdapter extends BaseAdapter{
private static ArrayList<ListviewContactItem> listContact;
private LayoutInflater mInflater;
public ListviewContactAdapter(Context photosFragment, ArrayList<ListviewContactItem> results){
listContact = results;
mInflater = LayoutInflater.from(photosFragment);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listContact.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return listContact.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(R.layout.contact_item, null);
holder = new ViewHolder();
holder.txtname = (TextView) convertView.findViewById(R.id.lv_contact_item_name);
holder.txtphone = (TextView) convertView.findViewById(R.id.lv_contact_item_phone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtname.setText(listContact.get(position).GetName());
holder.txtphone.setText(listContact.get(position).GetPhone());
return convertView;
}
static class ViewHolder{
TextView txtname, txtphone;
}
}
But when I run the app that display no thing. Could anyone tell me what wrong here and how can I fix it?
I guess your app crashes because of NullPointerException.
Change this
ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);
to
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
assuming listview belongs to the fragment layout.
The rest of the code looks alright
Edit:
Well since you said it is not working i tried it myself
Please use ListFragment. Otherwise, it won't work.
EDIT 1:
Then you'll only need setListAdapter() and getListView().
you need to give:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
inside fragment.
The inflate() method takes three parameters:
The id of a layout XML file (inside R.layout),
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from
the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the
parent ViewGroup elsewhere, by some of the Android code we call (in
other words, behind our backs). When you pass false as last parameter
to inflate(), the parent ViewGroup is still used for layout
calculations of the inflated View, so you cannot pass null as parent
ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
I have a list view with two text view and a image view and items I populate it with are 114 , I have created the list view with my custom adapter but the problem is that it takes a while like approx. 1 sec to 2 secs to load up and show the activity where I am displaying the list and whenever I open the activity it take time to show , so how can I minimize this delay time?
Here is my code:
public class ListViewFragment extends ListFragment {
int suraPicNum;
ArrayList<ListItem> imageArry = new ArrayList<ListItem>();
String[] names;
ImageTextListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.listviewtest, container, false);
suraPicNum = R.drawable.j415;
for (int x = 1; x <= 30; x++) {
imageArry.add(new ListItem(suraPicNum, R.drawable.j414, "Juz " + x,
String.valueOf(x)));
suraPicNum++;
}
adapter = new ImageTextListAdapter(getActivity(),
R.layout.list_item_image_text, imageArry);
setListAdapter(adapter);
return view;
}
}
And activity class:
public class ListFragActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.fragactivity);
}
use this...Endless Adapter
it will help you...:)
use AsyncTask to load all the images and then attach them to adapter.
I have 3 different layouts on my ViewPagerIndicator - https://github.com/JakeWharton/Android-ViewPagerIndicator
My project is to load data from the website and set the data accordingly into the 3 different layout of the ViewPager.
How do I go about achieving it?
In my TestFragment, I have
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("mContent", mContent);
View view = null;
if (mContent.equalsIgnoreCase("title1")) {
view = inflater.inflate(R.layout.one, container, false);
} else if (mContent.equalsIgnoreCase("title2")) {
view = inflater.inflate(R.layout.two, container, false);
} else if (mContent.equalsIgnoreCase("title3")) {
view = inflater.inflate(R.layout.three, container, false);
//Textview data = (TextView)view.findViewById(id)
}
return view;
}
I know this is for setting layout according to the fling'd titles.
I know how to findViewById to get the id of the widgets and set data. However, the data is set statically in the code itself.
For me, I have to grab data from the internet and put the data in accordingly. How do I achieved that?
Thanks in advance.
I almost know what you want.Here is my answers,and it works well.
You can according to the following steps.
1.Create three different Fragment class ,such as LoadImageFragment1,LoadImageFragment2,LoadImageFragment3, and all of them extends Fragment.
Follow is my example.
public class LoadImageFragment1 extends Fragment {
ListView listView;
LayoutInflater mInflater;
LoadImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
View view = inflater.inflate(R.layout.loadimage_layout, null);
listView = (ListView) view.findViewById(R.id.listview);
adapter = new LoadImageAdapter();
adapter.initList();
listView.setAdapter(adapter);
return view;
}
private class LoadImageAdapter extends BaseAdapter{
ArrayList<String> list = new ArrayList<String>();
public void initList(){
for(int i = 0 ; i < 30;i ++){
list.add("" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = mInflater.inflate(R.layout.loadimage_item, null);
}
return convertView;
}
}
2.Then modify your SampleTabsDefault class.
class GoogleMusicAdapter extends FragmentPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
switch(position){
case 0:
return new LoadImageFragment1();
case 1:
return new LoadImageFragment2();
case 2:
return new LoadImageFragment3();
}
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
And I just use the class of SampleTabsDefault as a sample.You can do this in other classes.
Here I just use a ListView as a sample , you can load your images and texts from internt, and you also can do other things in your LoadImageAdapter 's getView() method.
Hope this can help you.
I have 3 different layouts on my ViewPagerIndicator
ViewPagerIndicator is just an indicator
I thought your meaning is your viewadapter have three views to show.
Use FragmentPagerAdapter to handle different view.
you should read the ViewPagerIndicator samples
Before starting, copy the samples from ViewPagerIndicator
https://github.com/JakeWharton/Android-ViewPagerIndicator/tree/master/sample/src/com/viewpagerindicator/sample
The steps to be done are,
Create an custom FragmentPagerAdapter (ex: https://github.com/JakeWharton/Android-ViewPagerIndicator/blob/master/sample/src/com/viewpagerindicator/sample/TestFragmentAdapter.java)
Create custom Fragment for each each layout (in your case 3)
https://github.com/JakeWharton/Android-ViewPagerIndicator/blob/master/sample/src/com/viewpagerindicator/sample/TestFragment.java
Override onActivityCreated in the fragment class
In the onActivityCreated method, u can access the UI components as in onCreate method
So that u can make a web service call, bind it to ur UI components in this segment.
Cheers
Create and implement a Loader (AsyncTaskLoader) to load data from the internet.
Have your TestFragment implement LoaderCallbacks, so that it gets notified when the Loader (AsyncTaskLoader) has finished loading data from the internet.
In your implementation of your TestFragment's onActivityCreated, initialize or restart the loader:
getLoaderManager().initLoader(0, null, this);
In your TestFragment's implementation of onLoadFinished, assign the data to the widgets.
https://developer.android.com/reference/android/content/AsyncTaskLoader.html
https://developer.android.com/reference/android/app/LoaderManager.html
https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html
I have two almost identical ListFragment A & B, except that they draw data from their respective Asynctasker.
onListItemClick at A will result in Fragment A being replaced by B. However, my app always get stuck at the constructor of its CustomAdapter in B.
private class CustomAdapter_B extends ArrayAdapter<MatchType> {
// Stuck Here
CustomAdapter_B() {
super(getActivity(), R.layout.color_match_type_s2, matches_type_s2);
}
Fragment A
public class Fragment A extends ListFragment implements AsyncTaskCompleteListener<ArrayList<MatchType>>{
ArrayList<MatchType> matches_type = new ArrayList<MatchType>();
private ProgressDialog dialog;
private static FirstPageFragmentListener main_caller;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Interface, triggering Fragment Replace in my Fragment Adapter
main_caller.onMySignalWithNum(1, (matches_type.get(position).getLink()));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.dialog.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// AsyncTasker to draw data for ArrayAdapter
LoadMatchType lmt = new LoadMatchType(this);
lmt.execute();
}
#Override
public void onTaskComplete(ArrayList<MatchType> result) {
dialog.dismiss();
//result.remove(result.size()-1);
matches_type = result;
setListAdapter(new CustomAdapter());
}
}
//Custom Adapter
private class CustomAdapter extends ArrayAdapter<MatchType> {
CustomAdapter() {
super(getActivity(), R.layout.color_match_type, matches_type);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (row == null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
row = inflater.inflate(R.layout.color_match_type, parent, false);
}
TextView tv_type = (TextView) row.findViewById(R.id.textView_type);
tv_type.setText(matches_type.get(position).getType());
TextView tv_tweet = (TextView) row.findViewById(R.id.textView_tweet);
tv_tweet.setText(matches_type.get(position).getTweet());
TextView tv_tph = (TextView) row.findViewById(R.id.textView_tph);
tv_tph.setText(matches_type.get(position).getTph());
return row;
}
}
public static Fragment newInstance(
FirstPageFragmentListener pageFragmentListener) {
// TODO Auto-generated method stub
footOddsFragment frag = new footOddsFragment();
main_caller = pageFragmentListener;
return frag;
}
}
//INTERFACE
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(ArrayList<MatchType> result);
}
Fragment B is about the same.
The app will get stuck at Fragment B's CustomAdapter constructor and the screen will be blank.
Oh, and everything works fine if I abandon Fragment B and just call the Asynctasker_B in onListItemClick in Fragment A. Just that I can't press back to view the previous list.
Forget Fragment B. Override your back press, put an if in there to determine if List B is active, if it is, change it back, otherwise perform the normal back function.
public void onBackPressed() {
// Code here to change list or go back.
return;
}