I have a Fragment activity that I am using to make a tab bar. Inside this activity I am planning to put a table or ListViews with some random values.
Here's my code:
import com.example.mvaguimaraes.beetrackprov.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
public class Orders extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.orders, container, false);
ListView listView1 = (ListView) findViewById(R.id.listView1);
Order[] items = {
new Order(1, "Milk", 21.50),
new Order(2, "Butter", 15.99),
new Order(3, "Yogurt", 14.90),
new Order(4, "Toothpaste", 7.99),
new Order(5, "Ice Cream", 10.00),
};
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(this,
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
}
The problem is that I cannot extend my Orders class to Fragment and Activity so I'm getting this errors in my code:
Cannot resolve method findViewByID(int)
ListView listView1 = (ListView) findViewById(R.id.listView1);
Cannot resolve constructor
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(this,
android.R.layout.simple_list_item_1, items);
Cannot resolve method getBaseContext()
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Probably because they inherit something from Activity. There's any way to make them work inside the Fragment? Sorry for my noob-ness I am new to Android Development.
To open another screen after clicking on one of the items of the listview I did this right after the onItemClick public void method:
String item = ((TextView) view).getText().toString();
Intent i = new Intent(getApplicationContext(), OrderDetails.class);
i.putExtra("new_variable_name",item);
Intent browserIntent =
new Intent(Orders.this, OrderDetails.class);
startActivity(browserIntent);
startActivity(i);
I tried to replace both "getApplicationContext()" and "Orders.this" with "getActivity()" but it didn't work.
Fragments do not have a findViewById() method like Activities. Instead you call findViewById() to lookup views on the View returned from inflating the layout in onCreateView(). Also, where you need a Context you typically use the Activity the fragment is attached to by calling getActivity().
public class Orders extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.orders, container, false);
ListView listView1 = (ListView) v.findViewById(R.id.listView1);
Order[] items = {
new Order(1, "Milk", 21.50),
new Order(2, "Butter", 15.99),
new Order(3, "Yogurt", 14.90),
new Order(4, "Toothpaste", 7.99),
new Order(5, "Ice Cream", 10.00),
};
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(getActivity(),
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();
}
});
return v;
}
}
Related
This shows one of the fragments that has the listview code in it which worked in it's own layout but does not work in the fragment. What should I do for this to work in the fragment? I am fairly new to android app development so I do not know what to do. if you do not understand what I am trying to do, I am having the user enter data into a form and then i want that data to be displayed in the fragment as a list so they can see all the data entered from beginning to end. I have been looking all over for a solution but i cannot find one that fits what i need to do. All the information i see is for pre-saved sq lite databases.
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.database.Cursor;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import static android.R.attr.button;
public class tab3expense extends Fragment {
private static final String TAG = "tab3expense";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3expense, container, false);
return rootView;
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(tab3expense.this, add_expense.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here is the layout file
<LinearLayout
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.dharquissandas.budget.MainActivity$PlaceholderFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
In Fragment class context will be accessed by in following method getActivity(). Here I make some change in your code. You have to inflate your layout view in onCreateView(), then cast your listview components in onActivityCreated(). Please get look on the following code. Thanks in advance.
public class Tab3expense extends Fragment {
private static final String TAG = "tab3expense";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab3expense, container, false);
return rootView;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) rootView.findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(getActivity(), add_expense.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(getActivity(),message, Toast.LENGTH_SHORT).show();
}
}
Rearrange your code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3expense, container, false);
mListView = (ListView)rootView. findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(getContext());
populateListView();
return rootView;
}
I have a database with Users and their data.
Then make ListView with their names.
How then set click listener to ListView assosiated with my List?
So when I click on List element strats new Activity with all User details, no only name?
package com.test.tabs;
import java.util.ArrayList;
import java.util.List;
import com.test.tabs.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SelectFragment extends Fragment {
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_select, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());
List<User> users = db.getAllUsers();
List<String> your_array_list2 = new ArrayList<String>();
for (int i = 0; i < users.size(); i++) {
your_array_list2.add(users.get(i).getFirstName());
}
listView = (ListView) getActivity().findViewById(R.id.listView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,your_array_list2);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
});
}
}
You need to implement parcelable in your User class:
public class User implements Parcelable
{
....
}
Now you can attach/send your user to the next activity like so:
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
User user = adapter.getItem(position);
Bundle b = new Bundle();
b.putParcelable("user", user);
Intent i = new Intent(context, OtherActivity.class);
i.putExtra("bundle", b);
startActivity(i);
}
});
In the new activity call:
Bundle b = getIntent().getBundleExtra("bundle");
User user = b.getParcelable("user");
Use ListView#setOnItemClickListener(AdapterView.OnItemClickListener listener).
In my opinion, you should use Cursor Adpater to populate listview from database. On item click event for each row, you can get corresponding cursor object, pass on some details to next activity, so it can fetch more user details and display to user.
You need to understand the basics first. Have a look at this tutorial to have some idea.
Good Luck!
how can I make WebView can open the fragment listview? this is my code, and i got error code in :
lv.setOnItemClickListener(new OnItemClickListener() : The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})
package info.androidhive.slidingmenu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.content.Intent;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
protected ListView lv;
protected ListAdapter adapter;
public static final String MOVIE_DETAIL_KEY = "movie";
SimpleAdapter Adapter;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> mylist;
String[] Pil;
String[] Ltn;
String[] Gbr;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_pulau, container,false);
ListView lv = (ListView) rootView.findViewById(R.id.lv);
Pil = new String[] {"Pulau Gusung", "Binatang Laut Khas"};
Ltn = new String[] {"Baca Selengkapnya...", "Baca Selengkapnya..."};
Gbr = new String[] {Integer.toString(R.drawable.ic_photos),
Integer.toString(R.drawable.ic_photos),
};
mylist = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < Pil.length; i++){
map = new HashMap<String, String>();
map.put("list", Pil[i]);
map.put("latin", Ltn[i]);
map.put("gbr", Gbr[i]);
mylist.add(map);
}
Adapter = new SimpleAdapter(getActivity(), mylist, R.layout.item_kepulauan,
new String[] {"list", "latin", "gbr"}, new int[] {R.id.tv_nama, R.id.tv_des, R.id.imV});
lv.setAdapter(Adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) lv
.getItemAtPosition(position);
if (position == 0) {
Intent myIntent = new Intent(getApplicationContext(),
Story.class);
startActivity(myIntent);
}else if (position == 1) {
Intent myIntent = new Intent(getApplicationContext(),
Story.class);
startActivity(myIntent);
}
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition + " ListItem : "
+ itemValue, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
The issue is because you're using a new instance of OnItemClickListener when it should be AdapterView.OnItemClickListener. You've imported AdapterView, but not the inner interface, and there is no standalone OnItemClickListener interface so the types do not line up.
The following code gives me this error: The constructor ArrayAdapter(TrainingDetails, int, String[]) is undefined. How to rectify it? Please help. Here I am trying to retrieve the value of the selected spinner and store it in another string.
package com.example.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.R;
public class TrainingDetails extends BaseFragment
{
View view;
private EditText nameEdt;
private Spinner trainingTypes;
private Spinner trainerProfile;
String data1[] = {"1", "2", "3"};
String data2[] = {"a", "b", "c"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.training_details, container,false);
nameEdt = (EditText) view.findViewById(R.id.name_edt);
trainingTypes = (Spinner) view.findViewById(R.id.trainingtypes_spn);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trainingTypes.setAdapter(adapter_state);
trainingTypes.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
String selectedItem = data1[index];
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
trainerProfile = (Spinner) view.findViewById(R.id.trainerprofile_spn);
return view;
}
}
change
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
to
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
in Fragment you'll get Context by using getActivity()
For ArrayAdapter you need to pass Context
change this
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
into
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
The first parameter of ArrayAdapter is a Context object not an instance of a Fragment. Change
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
with
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
I've a swive view along with 4 tabs which displays in my first UI. I've added ListView for each Tabs. But OnItemClickListener is not working for ListFragment. My class is extended from ListFragment and implements OnItemClickListener. What i wanted to do is that when i select a item from the list, i've to display the Toast which displays the name of item that i've selected. But its not working for me. No error occurs but not getting the things done. Can anyone help me for this. My complete code for this is below:
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TUFragment extends ListFragment implements OnItemClickListener {
ListView list;
View rootView;
final String[] courses = new String[] { "BIM", "BBA", "BBS", "BSc-CSIT",
"BSc-IT", "BHM", "BTTM", "MBA", "MBS", "MSc-IT", "MTTM" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tu, container, false);
list = (ListView) rootView.findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, courses);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(this.getActivity(), "You have Selected: " + courses[arg2],
Toast.LENGTH_LONG).show();
}
}
Thankx in advance
Try this..
And also change to setListAdapter(adapter);
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
String val = ((TextView) v).getText().toString().trim();
Toast.makeText(getActivity(), "You have Selected: " + val,
Toast.LENGTH_LONG).show();
}