Hello!
I have tried to add a listview in a fragment but it doesn´t accept getApplicationContext:
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
and this:
Toast.makeText(Todo.this, "" + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
How do I make it work for fragment instead of activity?
Code:
public class Todo extends Fragment {
EditText editText;
Button button;
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public Todo() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.todo, container, false);
editText = editText.findViewById(R.id.editText);
button = button.findViewById(R.id.button2);
listView = listView.findViewById(R.id.list);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String YeniVeri = editText.getText() .toString();
arrayList.add(YeniVeri);
adapter.notifyDataSetChanged();
editText.setText("");
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Todo.this, "" + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return view;
}
}
You can use requireActivity() or container.context in onCreatView. So you can also access "contex" via container.
Exp(Kotlin):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
var mContext:Context? = container.context
use requireActivity() instead of getApplicationContext and "ActivityName.this"
Related
I'm adding fragments to my menu.....now one of the menufragments is a listview and i need to use both appcompatactivity and fragment class which isn't possible to extends both
The error are in the Screenshots
public class friendjava extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.friends, container, false);
final ListView list = (ListView) findViewById(R.id.listview1);
final ArrayList<String> mylist = new ArrayList<>();
mylist.add("wisdom");
mylist.add("favour");
mylist.add("faith");
mylist.add("chisom");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mylist);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),mylist.get(position),Toast.LENGTH_SHORT).show();
}
});
}
}
the error are in screenshot this is error screenshot
That is a fragment. A fragment is separate from an activity. You have to bind it to an activity. The findViewById() method needs to be tied to a view of an activity.
Get the view reference to a view object first.
public class friendjava extends Fragment {
private View view;
private ListView list;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.friends, container, false);
list = view.findViewById(R.id.listview1);
final ArrayList<String> mylist = new ArrayList<>();
mylist.add("wisdom");
mylist.add("favour");
mylist.add("faith");
mylist.add("chisom");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mylist);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),mylist.get(position),Toast.LENGTH_SHORT).show();
}
});
}
return view;
}
Take care of how view is used and returned in the end.
Try changing
final ListView list = (ListView) findViewById(R.id.listview1);
into
final ListView list = findViewById(R.id.listview1);
and after that run the program and check logcat
I try do it with below code but it not working! Please help me... I am confused ...
In below code all things is good but onItemClickListener is useless and it is in onCreateView method is wrong?
My items layout is not problem..
public class favFrg extends Fragment {
View v;
ListView listView;
List<HashMap<String,Object>> listFav;
DatabaseManager dbManager;
public favFrg() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_fav_frg, container, false);
listView= v.findViewById(R.id.listViewFav);
dbManager=new DatabaseManager(getContext());
dbManager.openDB();
listFav=dbManager.getStoryFavorite();
dbManager.closeDB();
String[] keys={"id","txtName"};
int[] resources={R.id.favTxtViewNumberStory,R.id.favTxtViewTitleStory};
SimpleAdapter adapter=new SimpleAdapter(getContext(),listFav,R.layout.fav_item_layout,keys,resources);
listView.setAdapter(adapter);
Log.i("ListView","Adapter Set");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListView","click item");
Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
Log.i("ListView","Return View");
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Just Only clickable and focusable attr in my item layout should be false... and works for me
https://code.i-harness.com/en/q/1561bd1
instead of getContext() use container.getContext() in creating adapter for listview.
Try making the SimpleAdapter as a public variable and put it outside the class onCreateView
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}
I'm trying to add items at runtime to ListView placed on Tab.
But when I do so, I get an error. There are 3 tabs and I'm not using ListFragments, because I have different content in all tabs
my code below
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Gurusharan S is right, the problem is about the names of your variables. To avoid confusions I'd suggest to change your code to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.library, parent, false); //Change the name from v to view
ListView lvLibList = (ListView)view.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)view.findViewById(R.id.btAddItem);
EditText edit = (EditText)view.findViewById(R.id.eAddItem); //Initialize the EditText outside of the click method
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return view;
}
And in the future I'd advice to give your variables more meaningful names, sometimes it takes you a little more coding but it is worth it.
Posting my comment as answer, as I'm pretty sure that is the issue:
The variable edit seems to be null. That is because when you call v.findViewById, you are actually calling it on the view that was clicked and NOT the fragment's view.
So you got two options:
Change the name of the fragment's view. eg. View v1 = inflater.inflate(R.layout.library, parent, false); and then change the line to v1.findViewById
Change the name of the argument of onClick. eg. public void onClick(View v1) {.
Hope that helps.
Here's my code for trying to display a list in a Fragment, which as of now keeps reporting a NullPointerException whenever it tries to initialize the ListView:
public class PortfolioFragment extends ListFragment {
ListView l;
ArrayAdapter<String> adapter;
List<String> list;
public PortfolioFragment() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
list = MainActivity.globalArrayTest;
l = (ListView) getView().findViewById(android.R.id.list);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
l.setAdapter(adapter);
return inflater.inflate(R.layout.fragment_portfolio, container, false);
}
I am getting an error at this line:
l = (ListView) getView().findViewById(android.R.id.list);
Change to
View v = inflater.inflate(R.layout.fragment_portfolio, container, false);
l = (ListView) v.findViewById(android.R.id.list);
return v;
You should have the below in xml
<ListView android:id="#android:id/list"
Or override onActivityCreated and use getListView()
Also you can use the below as black belt commented this is better than the above.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
l = getListView(); // since you extend ListFragment
}
since you are extending ListFragment you should use getListView() instead of findViewById and setListAdapter should be called after onCreateView (inside onActivityCreated, for instance)
This is another way to go about this, although I extend only Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle SavedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
ListView itemList = (ListView)rootView.findViewById(R.id.itemListView);
String[] items = {"Alpha", "Orange", "Pineapple", "Venus", "Echo", "Pent", "Mouse",
"Phoenix", "Dent", "Sloppy"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(),
R.layout.text_row, items);
itemList.setAdapter(new ArrayAdapter<>(rootView.getContext(),
R.layout.fragment_item, items));
itemList.setAdapter(adapter);
return (rootView);
}