I have some issues with a listview in a Fragment.
I want to show a List with Fruits in the Fragment, tried a few things but.
In a later version the String[] should contain data from a json object.
This is the current status:
public class fragmentA extends Fragment
implements View.OnClickListener {
TextView textView;
ViewStub viewStub;
ListFragment listView;
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// das Layout fuer dieses Fragment laden
View view= inflater.inflate(R.layout.fragmenta, container, false);
// inflate layout
Button notfallbtn = (Button) view.findViewById(R.id.notfallbtn);
textView = (TextView) view.findViewById(R.id.textView);
// listView = (ListFragment) view.findViewById(R.id.einkaufsliste);
viewStub = (ViewStub) view.findViewById(R.id.viewStub);
viewStub.setVisibility(View.GONE);
// initialize button using the inflated view object
notfallbtn.setOnClickListener(this);
// listener for button
setListAdapter(new ArrayAdapter<String>(this, R.layout.einkaufsliste,FRUITS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
return view; // return inflated view
}
The error messages I get:
Cannot resolve 'setListAdapter'
Cannot resolve 'einkaufsliste'
Any help will be greatly appreciated.
public class fragmentA extends Fragment
does not extend ListFragment. setListAdapter is a method of ListFragment.
http://developer.android.com/reference/android/app/ListFragment.html
Also you probably need
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,FRUITS)
Instead of this use getActivity() which returns the activity this fragment is associated with.
Also read
http://developer.android.com/reference/android/app/ListActivity.html
Also override onActivityCreated and use ListView lv = getListView().
Related
I am trying to have a checkable list view fragment pop up with a button at the top of the list view. After user clicks an item in the navigation menu, the main activity will be populated with my button and list view fragment. I'm getting 'invoke virtual method' error, even though the element in declared. Here's some code.
My list fragment class:
public class ThingsManager extends Fragment {
ArrayList<String> selectedItems;
ListView checkable_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(layout.things_manager_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
public ThingsManager() {
// Required empty public constructor
}
}
List fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ThingsManager">
<TextView
android:id="#+id/things_manager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Things Manager"
android:textSize="25dp"/>
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/checkable_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Should I be controlling the listview in MainActivity or in the FragmentClass ?
Move your all your view initialization and listview setup code from onActivityCreated to onCreateView method.
And your this statement
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
is wrong. You have to find ListView from the view you have inflated in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout.things_manager_fragment, container, false);
init(rootView);
return rootView;
}
public void init(View rootView){
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list = rootView.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
In here I am trying to make OnItemLongClick, I tried doing it in ListActivity before and that's working.
Now I am trying to make one inside a Fragment, but I get an error here and there, I need some advice/suggestion/answer to solve the error, or the correct way to implement the method.
In the ListActivity (working):
public class ViewData extends ListActivity implements OnItemLongClickListener {
//init controller
private DBDataSource dataSource;
//init arraylist
private ArrayList<Barang> values;
private Button delButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewdata);
dataSource = new DBDataSource(this);
// open controller
dataSource.open();
// get values
values = dataSource.getAllBarang();
// insert data to array adapter
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(this,
android.R.layout.simple_list_item_1, values);
// set adapter in list
setListAdapter(adapter);
// listview for set onItemLongClickListener
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
}
//if user longclick
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
//tampilkan alert dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilih Aksi");
dialog.show();
final Barang b = (Barang) getListAdapter().getItem(pos);
delButton = (Button) dialog.findViewById(R.id.button_delete_data);
//apabila tombol delete di klik
delButton.setOnClickListener(
new OnClickListener()
{
#Override
public void onClick(View v) {
// Delete barang
dataSource.deleteBarang(b.getId());
dialog.dismiss();
finish();
startActivity(getIntent());
}
}
);
return true;
}
}
The Fragment version (still giving an error) :
public class Menu_Riwayat extends Fragment {
//init controller
private DBDataSource dataSource;
//init arraylist
private ArrayList<Investasi_DB> values;
static ListView lv;
private Button button_hapus;
static LinearLayout mLinear;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
mLinear = (LinearLayout) inflater.inflate(R.layout.viewdata, container, false);
lv = (ListView) mLinear.findViewById(R.id.list);
dataSource = new DBDataSource(getActivity());
// open controller
dataSource.open();
// get values
values = dataSource.getAllInvestasi_DB();
// insert data to array adapter
ArrayAdapter<Investasi_DB> adapter = new ArrayAdapter<Investasi_DB>(getActivity(),
android.R.layout.simple_list_item_1, values);
// set adapter in list
lv.setAdapter(adapter);
return mLinear;
// ERROR IN THIS PART BELOW, not sure what to change "this" with
lv.setOnItemClickListener(this);
}
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
//tampilkan alert dialog
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilihan");
dialog.show();
// ERROR IN THIS PART BELOW, not sure how to implement "getListAdapter()" inside fragment
final Investasi_DB b = (Investasi_DB) getListAdapter().getItem(pos);
button_hapus = (Button) dialog.findViewById(R.id.button_hapus);
button_hapus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource.deleteInvestasi_DB(b.getId());
dialog.dismiss();
getActivity().finish();
// ERROR IN THIS PART BELOW, the "getIntent()" part
startActivity(getIntent());
}
});
return true;
}
}
I need help to solve the error (correct way to implement it):
getListAdapter(), getIntent(), and this in lv.setOnItemClickListener(this);
EDITED PART AFTER SOME SUGGESTION :
so now i make it like this
public class Menu_Riwayat extends Fragment {
//inisialisasi kontroller
private DBDataSource dataSource;
//inisialisasi arraylist
private ArrayList<Investasi_DB> values;
static ListView lv;
private Button button_hapus;
static LinearLayout mLinear;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
mLinear = (LinearLayout) inflater.inflate(R.layout.viewdata, container, false);
lv = (ListView) mLinear.findViewById(R.id.list);
dataSource = new DBDataSource(getActivity());
// buka kontroller
dataSource.open();
// ambil semua data barang
values = dataSource.getAllInvestasi_DB();
// masukkan data barang ke array adapter
ArrayAdapter<Investasi_DB> adapter = new ArrayAdapter<Investasi_DB>(getActivity(),
android.R.layout.simple_list_item_1, values);
// set adapter pada list
lv.setAdapter(adapter);
//lv.setOnItemLongClickListener(this);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilihan");
dialog.show();
final Investasi_DB b = (Investasi_DB) lv.getItemAtPosition(position);
button_hapus = (Button) dialog.findViewById(R.id.button_hapus);
button_hapus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource.deleteInvestasi_DB(b.getId());
dialog.dismiss();
getActivity().finish();
}
});
}
});
return mLinear;
}
its working, but the apps close itself after i click the button (i think because of getActivity().finish();), any idea about that ?
I need help to solve the error (correct way to implement it):
getListAdapter(), getIntent(), and this in
lv.setOnItemClickListener(this);
if with this you want to access a Context, you can use getActivity(). Fragment is not a Context
In setOnItemClickListener(this);, this refers to the current instance. With that line you are implying that this is also implementing the OnItemClickListener interface. Which is not true. You need yo add implement OnItemClickListener to your Fragment class.
getListAdapter():
instead of getListAdapter() you can use the ListView to retrieve the item at position, since you are already keeping a reference as member. Change
final Investasi_DB b = (Investasi_DB) getListAdapter().getItem(pos);
with
final Investasi_DB b = (Investasi_DB) lv.getItemAtPosition(pos);
why do you need this line startActivity(getIntent());?
I have a ListView which is populated in my MainActivity, but when i want to find the selected item, all of the items appear to have the same position.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_teams);
ListView mainListView;
// Find the ListView in the UI.
mainListView = (ListView) findViewById( R.id.listView );
String values = "Team A vs Team B=Team C vs Team D";
//Matches are send in one long string, and are separated by the = sign.
//This splits the string up and puts it into an array.
String[] array = values.split("=", -1);
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.addAll( Arrays.asList(array) );
ArrayAdapter listAdapter;
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(listAdapter);
}
This makes a list like this:
Team A vs Team B [checkbox]
Team C vs Team D [checkbox]
I have a button and when it is clicked it runs this method:
public void matchStart(View view){
String selectedMatch = String.valueOf(((ListView) findViewById( R.id.listView )).getSelectedItemPosition());
Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();
}
However whenever i click the button, the toast displays the same value no matter which item in the listview is selected. Why is this?
You should use the adapters getView method, something like this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.some_layout, parent,
false);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//here get what you need by the position
}
});
}
}
I've been trying to make listView redirect user onClick to URL's when clicking on different elements.
Example:
clicking on "apple" would open "stackoverflow.com",
but clicking on tomato would open "google.com" etc.
Could anyone give me some advice how can I accomplish this, because after 2 days of trying and searching all I've got is a headache..
displayMainMenu.java
public class DisplayMainMenu extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_main_menu);
final String[] food = new String[] {"Apple", "Tomato", "Potato"};
ListAdapter adapter = new MyAdapter(this, food);
ListView listView = (ListView) findViewById(R.id.mainMenu);
listView.setAdapter(adapter);
}
class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, String[] values)
{
super(context, R.layout.entry, values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.entry, parent, false);
String text = getItem(position);
TextView textView = (TextView) view.findViewById(R.id.listTextView1);
textView.setText(text);
return view;
}
}
}
You should make a new class that holds the shown string value (Apple, Tomato, Potato, etc) and also holds the URL that you want to link to.
Then make the ArrayAdapter use that class. The getView function you have already should suffice (when its updated to use the new class).
Then in your activity, use 'setOnItemClickListener' to set a new listener.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyItem clickedItem = () parent.getItemAtPosition(position);
<< Insert code to open the link with the URL you can get from 'clickedItem' >>
}
});
That should do it.
I have one fragment contain list view, buttons and images.Buttons,images and other widget loaded correctly but instead of list view it shows only loading icon
public class ListDetails extends SherlockFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ListView listView = (ListView)container.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return inflater.inflate(
R.layout.listdetails_fragement, container, false);
}
I have check other Button,Images are Loaded but List view gives error on my ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values); line
here i provided my logcat error.
Here's what I did:
Instead of doing everything in onCreateView(), I used onActivityCreated().
In onActivityCreated(), I just added this code:Here's the implementation:
public class Database extends Fragment {
public ViewPager viewPager;
private AllPagesAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Tab1", "Tab2" };
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
ArrayAdapter<String> mArrayAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View databaseview = inflater.inflate(R.layout.database, container,
false);
return databaseview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ListView mListView = (ListView)getActivity().findViewById(R.id.databaselist);
mArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
mListView.setAdapter(mArrayAdapter);
}
}
And the layout I used was :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/databaselist"
android:layout_width="match_parent"
android:layout_height="254dp" >
</ListView>
<TextView
android:id="#+id/newmainlist"
android:layout_width="match_parent"
android:layout_height="250dp"
android:gravity="center"
android:text="database" />
</LinearLayout>
Also, here's the image for it:
Hope this helps .. :)
The error because of this line..
ListView listView = (ListView)container.findViewById(R.id.list_view2);
here listview is null
change your code like this..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.listdetails_fragement, container,
false);
ListView listView = (ListView) view.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation", "Simple List View In Android",
"Create List View Android", "Android Example",
"List View Source Code", "List View Array Adapter",
"Android Example List View" };
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
.getApplicationContext(), android.R.layout.simple_list_item_1,
android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return view;
}
Change onCreateView(....) with this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(
R.layout.listdetails_fragement, container, false);
ListView listView = (ListView)v.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return v;
}