i have an error at setText in adapter class - android

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

Related

My application crashes when listview is loaded in fragment layout

I am trying to show a listview in a fragment layout; for that i have used custom adapter.Note that on a button click, fragment is changed. But on that button click application crashes, I don't know what is actual problem please help.
This is my Fragment Class:
public class Fragment1 extends Fragment {
public void Fragment1()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment1, container, false);
//return inflater.inflate(R.layout.fragment_fragment1, container, false);
ListView listView = (ListView)rootView.findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
return rootView;
}
class CustomAdapter extends BaseAdapter
{
int img_arr[] = {R.drawable.emmastone,
R.drawable.chloegracemoretz,
R.drawable.salmankhan,
R.drawable.emilia,
R.drawable.kitharington,
R.drawable.scarlettjohansson,
R.drawable.sophie,
R.drawable.deepika,
R.drawable.leonardodicaprio};
String name_arr[] = {"Emma", "Chloe", "Salman", "Emilia", "Kit", "Scarlet", "Sophie", "Deepika", "Leonardo" };
String msg_arr[] = {"Free at 8pm?", "I miss you <3", "Mota ho raha hun kia karon?", "Not in mood", "Danny or yagrit?", "Where are you?", "got engaged <3", "Give my money", "50 is enough" };
#Override
public int getCount() {
return img_arr.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.chats,null);
ImageView img = (ImageView)convertView.findViewById(R.id.imageView);
TextView name = (TextView)convertView.findViewById(R.id.textView_name);
TextView msg = (TextView)convertView.findViewById(R.id.textView_msg);
img.setImageResource(img_arr[position]);
name.setText(name_arr[position]);
msg.setText(msg_arr[position]);
return convertView;
}
}
}
This is in logcat:
0-21 23:52:21.581 3040-3040/com.example.farhan.a13_f_8310_lab_10_oct_fragments E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.farhan.a13_f_8310_lab_10_oct_fragments, PID: 3040
java.lang.NoSuchMethodError: No virtual method getLayoutInflater()Landroid/view/LayoutInflater; in class
Lcom/example/farhan/a13_f_8310_lab_10_oct_fragments/Fragment1; or its super classes (declaration of 'com.example.farhan.a13_f_8310_lab_10_oct_fragments.Fragment1' appears in /data/app/com.example.farhan.a13_f_8310_lab_10_oct_fragments-1/split_lib_slice_1_apk.apk)
at com.example.farhan.a13_f_8310_lab_10_oct_fragments.Fragment1$CustomAdapter.getView(Fragment1.java:91)

OnItemClickListener and OnClickListener not working for ListView using BaseAdapter

Here is my code which is not working
I'm getting data from server using `AsyncTask` and set data to the `listview` using `baseadapter` but using `convertview.setonclicklistner` working in adapter class and below code contains in `Fragmentclass(import android.support.v4.app.Fragment;)` so I think it is not problematic
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_restaurants, container, false);
restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);
no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);
// listening to single list item on click
restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("temp","temppppp");
}
});
//set layout slide listener
rowItems = new ArrayList<>();
history_list = new ArrayList<HashMap<String, String>>();
list_adapter = new ViewAdapter(getActivity(),rowItems);
restaurant_list.setAdapter(list_adapter);
}
What is the solution for this ?
add id to your parent layout for custom_list_item.xml
holder.parentLayout.setOnClickListener(new OnClickItem(position));
private class OnClickItem implements View.OnClickListener{
private int mPostion;
public OnClickItem(int position){
mPostion = position;
}
#Override
public void onClick(View v) {
YourActivity yourActivity = (YourActivity) mContext;
yourActivity.onItemClicked(mPostion);
}
}
android:descendantFocusability="blocksDescendants"
If any ListView contains focusable or clickable view then OnItemClickListener won't work. In that case we need to use this.
Try to set your setOnClickListener after setting the adapter:
Like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_restaurants, container, false);
restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);
no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);
//set layout slide listener
rowItems = new ArrayList<>();
history_list = new ArrayList<HashMap<String, String>>();
list_adapter = new ViewAdapter(getActivity(),rowItems);
restaurant_list.setAdapter(list_adapter);
// listening to single list item on click
restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("temp","temppppp");
}
});
}

Best way to fill a list with an adapter in a fragment

I developed an app which fills a list. It works fine in the way I did it but I'm not conviced that I solved the problem in a recommended way. I read that you should override onActivityCreated in a Fragment and fill the list there instead of doing this in onCreateView. onCreateView should only be used to inflate static views. Is this true? If yes, how should these two methods look like in the end?
This is my Fragment class:
public class FragmentMain extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
List<MyItem> items = createListItems();
ListView listView = (ListView) view.findViewById(R.id.list);
MyListAdapter adapter = new MyListAdapter(view.getContext(), items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
"Clicked " + position, Toast.LENGTH_LONG)
.show();
}
});
return view;
}
.
.
.
}
My MainActivity just adds the fragment:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentMain fm = new FragmentMain();
getFragmentManager().beginTransaction()
.add(R.id.fragment_main_container, fm).commit();
}
.
.
.
}
That is true to a certain extend only because onCreateView happens on the UI thread and you don't want anything slowing that down otherwise your UI will be slow and choppy. For example, in your fragment class you have a call to a method "createListItems()". I don't know how many items you're making but if it's a lot it could slow down your UI (especially if youre accessing a database and querying objects and so on). So you could do it in onActivityCreated but you could also use an AsyncTask. So your code would become something like this:
public class LoadListObjectsTask extend AsyncTask<Void, List<MyItem>, Void> {
private MyListAdapter myListAdapter;
private Context mContext;
public LoadListObjectsTask(Context context) {
this.mContext = context;
}
#Override
public void doInBackground(Void...params) {
//create your list objects here instead of on UI thread. This will run on a separate thread.
myListAdapter = new MyListAdapter(mContext, items);
return items; //return list of MyItems
}
//This is called when doInBackground is done. THIS WILL RUN ON THE UI THREAD So don't do
//anything slow here
#Override
public void onPostExecute(List<MyItem>...params //don't really need the list here//) {
listView.setAdapter(myListAdapter);
}
}
then in your fragment
public class FragmentMain extends Fragment {
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
List<MyItem> items = new ArrayList<MyItem>();
listView = (ListView) view.findViewById(R.id.list);
//new code
new LoadListObjectsTask(getActivity()).execute();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
"Clicked " + position, Toast.LENGTH_LONG)
.show();
}
});
return view;
}
public void onResume()... {
//also add the task here so your content is reloaded on resume..
new LoadListObjectsTask(getActivity()).execute();
}
.
.
.
}
If you don't want to do this just make your List of MyItems a private field and move
List<MyItem> items = createListItems();
to onActivityCreated().
Hope that helps!

Create listview in fragment android

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

Setting Data in ViewPagerIndicatorin different layouts

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

Categories

Resources