I am working with fragments in android,am extending android.app.ListFragment to display listview, but it takes only one item in a list view. I want to display 2 items in a list view ,its possible with extending ListActivity class, but i want to extend both fragment and listactivty.
Refer this image
public class ListFragmentnewforel extends android.app.ListFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<HashMap<String, String>> list = buildData();
String[] from = { "purpose" , "name","desc", "num"};
int[] to = { R.id.detailsText1, R.id.detailsText2, R.id.detailsText3, };
SimpleAdapter adapter = new SimpleAdapter(this, list,R.layout.mylistview,from,to);
setListAdapter(adapter);
}
public void onListItemClick(ListView l, View v, int position, long id) {
ArrayList<String>arr=new ArrayList<String>();
String item = (String) getListAdapter().getItem(position);
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
fragment.setText(item);
}
else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
Xmlparsingactiforele d=new Xmlparsingactiforele();
arr=d.myelarraylist(item);
// arr.get(0);
intent.putExtra("value1", arr.get(0));
intent.putExtra("value2", arr.get(1));
intent.putExtra("value3", arr.get(2));
intent.putExtra("value4", arr.get(3));
startActivity(intent);
}
}
private ArrayList<HashMap<String, String>> buildData() {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
list.add(putData("Android", "Mobile","two", "1"));
list.add(putData("Windows7", "Windows7","one", "2"));
list.add(putData("iPhone", "iPhone","three", "3"));
return list;
}
private HashMap<String, String> putData(String name, String purpose,String a, String n) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("purpose", purpose);
item.put("desc", a);
item.put("num", n);
return item;
}
}
There is nothing stopping you from showing whatever you want in the ListView item. Please read the API documentation of ListFragment.
You can create a ListAdapter that returns the View of the type you want in its getView method. There is hardly any difference between ListActivity and ListFragment in this regard.
Extend both fragment and Activity classes to single Class not possible. So, extends Activity to main class and create inner class and extends Fragment class to in it.
Related
I am trying to send row item from list view to another activity but maybe I do something wrong.
I made one app for food.
And I want when the user click to "First Activity" the list item from this listview to be send to "Second Activity" and when the user click to "Add to cart" the listview item go to Cart.class
But when I click to "Add to cart" the Activity is send me tо Cart.class but there have nothing.
In cart.xml I have listvew.
Sorry for my bad english
Thanks in advance.
First Activity.
public class UnderCal extends Activity {
String classes[] = {"Grilled chicken","Asiago","Spicy"};
int[] meal = new int[]{
R.drawable.grilledchicken,
R.drawable.asiago,
R.drawable.spicy
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.under_menu);
final List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<3;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("food", Integer.toString(meal[i]));
hm.put("txt", "" + classes[i]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"food","arrow","txt"};
// Ids of views in listview_layout
int[] to = { R.id.food,R.id.arrow,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_layout, from, to);
// Getting a reference to listview of main.xml layout file
final ListView listView = ( ListView ) findViewById(R.id.mylist);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setDivider(new ColorDrawable(0xffffffff));
listView.setDividerHeight(1);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if (position == 0)
{
Intent intent = new Intent(UnderCal.this,GrilledChicken.class);
// intent.putExtra("get", aList.get(position));
String result = (String) listView.getItemAtPosition(position).toString();
intent.putExtra("get",result);
startActivity(intent);
overridePendingTransition(R.anim.animation3, R.anim.animation4);
}
}
});
}
Second Activity.
public class GrilledChicken extends Activity {
Button butadd;
//HashMap<String, String> hm;
String list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.grilled_chicken);
//hash
// hm =(HashMap<String, String>)getIntent().getSerializableExtra("get");
Bundle extras = getIntent().getExtras();
list = extras.getString("get");
butadd=(Button) findViewById(R.id.butadd);
butadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(GrilledChicken.this,Cart.class);
// intent.putExtra("hm",hm);
intent.putExtra("list",list);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
Cart.class
public class Cart extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cart);
Bundle extras = getIntent().getExtras();
String pos = extras.getInt("list");
}
}
For get item from your listview you have to write following code.
String item = food.get(position).toString();
Write this on your Itemclick method
Put the following code in your Cart.class
Bundle extras = getIntent().getExtras();
String list_data = extras.getString("list");
Now list_data contains the data.
There is another way through which you can do the task also.
Create a separate Global Class
Global.class
public class Globalclass {
public static String list_data;
}
And then in your FirstActivity replace the following
intent.putExtra("get",result);
with
Globalclass.list_data=result;
Now you can access the list_dataanywhere like the following
String data=Globalclass.list_data;
Try this once I hope this will help you.
First of all do this in YourFirstActivity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), YourSecondActivity.class);
YourModel yourModel = (YourModel) parent.getItemAtPosition(position);
intent.putExtra("yourModel", yourModel);
startActivity(intent);
}
});
At another Activity do this.
YourModel yourModel= (YourModel) getIntent().getSerializableExtra("yourModel");
From yourModel object you will get all the data of your ListView selected item of YourFirstActivity to YourSecondActivity.
Multiple Send ListView Item:-
ArrayList<String>checked11 = new ArrayList<String>();
SparseBooleanArray checked = listView1.getCheckedItemPositions();
final ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.get(i))
selectedItems.add(checked11.get(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
use Bunddle :
Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(),
OtherActivity.class);
bundle.putStringArray("selectedItems", outputStrArr);
intent.putExtra("screen2", "sub");
intent.putExtras(bundle);
intent.putExtra(EXTRA_RESPONSE, selected);
startActivity(intent);
I am using onItemClickListener() with a List. I want to pass name of the item clicked on, and an arbitrary number to next instance of the list. How can this be done?
Edit: here is the class:
public class ListViewA extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"col_1"};
int[] to = new int[] {R.id.item2};
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 10; i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_1", "col_1_item_" + i);
fillMaps.add(map);
lv.setOnItemClickListener(onListClick);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
lv.setAdapter(adapter);
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
Intent i=new Intent(ListViewA.this,ListViewA.class);
startActivity(i);
}
};
}
Following example shows you how to pass data onItemClick for particular position.
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
HERE YOU GOT POSITION FOR PERTICULAR ITEM
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("position", fillMaps.get(position));
startActivity(i);
}
});
And yes you need to declare fillMaps as globally.
public class ListViewA extends Activity{
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);......
Intent i=new Intent(ListViewA.this,ListViewA.class);
i.putExtra("Key", fillMaps.get(position));
startActivity(i);
You can use above code in your onItemClickListner.
In this method the third agrument is position. So you have to use this eg. The Arraylist you are passing to your listView contains the data shown on listView. so use this kind of code
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String data= mArrlist.get(position);
}
If you are using the arralist of String type otherwise If you are using arraylist of getter setter class then use
mArralist.get(potion).getName();
You should get item #paticular position
HashMap<String, String> item = adapterview.getAdapter().getItem(position);
check your condition according to requirement and by getting data from item and process further.
Intent i=new Intent(ListViewA.this,ListViewA.class);
i.putExtra("item", item);
startActivity(i);
For adding arbitrary number you can use the Random class of java as below
Random mRandom = new Random();
int random = mRandom.nextInt(mMoveToList.size());
random variable of int type return every time random value.
you can use getItem(int position) of SimpleAdapter
put your SimpleAdapter variable adapter as global
in your ClickListener call adapter.getItem(position)
I have serious problems with my ListActivity. When I open it and start scrolling, the app freezes for some seconds and after that it can be scrolled smoothly. I don't get an "application not responding" error. I made a *.hprof heap dump and put it into MAT. Here you can see my leaks:
Seems like something is fishy. Maybe I'm not using the cursor in the right way.
Here you can take a look at my code:
public class ListViewActivity extends ListActivity implements OnClickListener {
// Resources
static String like;
// Cursor
private SimpleCursorAdapter adapter;
private Cursor cursor;
String[] showColumns;
int[] showViews;
// Database
private DBAccess dbAccess;
#Override
public void onCreate(Bundle savedInstanceState) {
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
ListViewActivity.like = "";
Intent intent = getIntent(); // gets the previously created intent
ListViewActivity.like = intent.getStringExtra("like");
new DatabaseTask().execute(null, null, null);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor item = (Cursor) getListAdapter().getItem(position);
Intent intent = new Intent(ListViewActivity.this, ListClickActivity.class);
intent.putExtra("id", item.getString(0));
startActivity(intent);
}
private class DatabaseTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.v("doInBackground", "started!");
dbAccess = new DBAccess(ListViewActivity.this, 1, "FishingMatey.db");
dbAccess.initDownloadedDatabase();
cursor = dbAccess
.createBewirtschafterListViewCursor(ListViewActivity.like);
showColumns = new String[] { "gewName", "reviergrenzen" };
showViews = new int[] { R.id.datensatz_gewName,
R.id.datensatz_reviergrenzen };
Log.v("doInBackground", "finished!");
return null;
}
protected void onPostExecute(Void params) {
adapter = new SimpleCursorAdapter(ListViewActivity.this,
R.layout.datensatz, cursor, showColumns, showViews);
setListAdapter(adapter);
dbAccess.closeDatabase();
Log.v("onPostExecute", "finished!");
}
}
}
EDIT1:
The issue doesn't come from the database because I have the same leak with the following code:
public class ListViewActivity extends ListActivity {
// Activity
public static Activity forFinish;
// Resources
static String like;
// Cursor
private SimpleAdapter adapter;
String[] showColumns;
int[] showViews;
#Override
public void onCreate(Bundle savedInstanceState) {
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
forFinish = this;
ListViewActivity.like = "";
Intent intent = getIntent(); // gets the previously created intent
ListViewActivity.like = intent.getStringExtra("like");
// create the grid item mapping
showColumns = new String[] { "gewName", "reviergrenzen" };
showViews = new int[] { R.id.datensatz_gewName,
R.id.datensatz_reviergrenzen };
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 20; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("gewName", "See" + i);
map.put("reviergrenzen", "Revier" + i);
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.datensatz, showColumns, showViews);
setListAdapter(adapter);
}
}
Would be awesome if someone can find the memory leak.
Greetings Mike!
If you are using images in your list items then move the image loading to a background task. You could have a look at smoothie, an asynchronous loading list that can be used with Android-BitmapCache for better performance.
ListViews have always been my weak point and right now I am practicing putting a Listview, within a Listview. Anyway, I first call my ListView at the start of my program and it loads it with an array saved in my strings.xml:
String[] departments = getResources().getStringArray(
R.array.departments_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
departments));
setContentView(R.layout.main);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
What I want to do is update this ListView with a new array of values each time a list item is clicked. The reason why I am trying to do it this way is because I plan on having 27 different arrays with different values for each position, and I feel it would be lighter on my resources if instead of making a ListView for each array of items, I would update this one ListView. I know I am probably not doing this the most efficient way, but if there is another way of implementing my idea please tell me.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
switch (position) {
case 0:
try {
//It is here that i dont know what to do, I was going to call
//the Listview the same way i did previously using my setlistadapter,
//but i kept getting errors about the code being undefined
String[] listitems1 = getResources().getStringArray(
R.array.items_array);
} catch (ClassCastException e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
break;
case 1:
try {
//The listview will be changed again here
} catch (ClassCastException e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
break;
}
};
});
Have you thought of using a BaseAdapter and setting it as the list adapter
http://developer.android.com/reference/android/widget/BaseAdapter.html
Your approach is wrong( if I understand what are you doing). Instead of replacing the adapter of the ListView every time the user clicks(and simply setting a new adapter should work) a element in the initial list you should start a new activity passing the clicked position and in your new activity set the adapter on a ListView with the correct array based on that position.
A small example:
Main class:
/**
* The main class with the initial 27 items array.
*/
public class Class1 extends ListActivity {
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// start the second activity that will show our array depending on the
// position clicked
Intent i = new Intent(this, Class2.class);
// put the position in the Intent so we can know in the other activity
// what array to load.
i.putExtra("pos", position);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// I just used a simple array of 2 items, you'll load your 27 items
// array
String[] items = { "1", "2" };
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
}
}
Secondary activity that will show the array based on the previously selected position:
public class Class2 extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the Intent that started the activity
Intent i = getIntent();
// find out what position did that other activity send to us.
int position = i.getIntExtra("pos", -1);
// load the ListView with an adapter based on the array that you
// want(according to that position)
if (position == 0) {
// the first element in the main list
String[] items = getResources().getStringArray(R.array.a1);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
} else if (position == 1) {
// the second element in the main list
String[] items = getResources().getStringArray(R.array.a2);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
} else {
// etc
}
}
}
Luksprog's answer is indeed correct, and it is very useful for lists many levels deep (you do not put limits, just keep spawning new activity instances with the proper list loaded)
BUT
If your list isn't more than 2 levels deep you can use ExpandableListActivity instead of ListActivity which is basically an enhanced version of the single-level list you're using which natively handle group collapsing/expanding and therefore you do not need the spawn of a new activity for each sublevel.
again note that this approach works only for lists which do not go deeper than 2 levels
ExpandableListActivity documentation
ExpandableListView documentation
ExpandableListAdapter documentation - you should be fine with the BaseExpandableListAdapter implementation
And here you have some nice example from Google itself:
public class ExpandableList3 extends ExpandableListActivity {
private static final String NAME = "NAME";
private static final String IS_EVEN = "IS_EVEN";
private ExpandableListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < 20; i++) {
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(NAME, "Group " + i);
curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");
//filling with dummy data...
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (int j = 0; j < 15; j++) {
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(NAME, "Child " + j);
curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd");
}
childData.add(children);
}
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { NAME, IS_EVEN },
new int[] { android.R.id.text1, android.R.id.text2 },
childData,
android.R.layout.simple_expandable_list_item_2,
new String[] { NAME, IS_EVEN },
new int[] { android.R.id.text1, android.R.id.text2 }
);
setListAdapter(mAdapter);
}
}
Is it possible to call listactivity through tab activity? Basically, I am developing an app with 3 tabs, for which I am using tabactivity. Furthermore, in one of the tabs I want a listview, so I have derived from listactivity.
Now I want the click event to be determined in the listview. Am i missing something?
public class Tabissue extends TabActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TabHost host = getTabHost();
host.addTab(host.newTabSpec("Tab1").setIndicator("Tab1").setContent(new Intent(this,Tab1.class)));
host.addTab(host.newTabSpec("Tab2").setIndicator("Tab2").setContent(new Intent(this,Tab2.class)));
host.setCurrentTab(1);
}
}
Tab1 Class
public class Tab2 extends ListActivity
{
ListView list;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("Test1","####");
map.put("Test2", "India");
map.put("Time", "India time");
mylist.add(map);
map = new HashMap<String, String>();
map.put("Test1", "####");
map.put("Test2", "US");
map.put("Time","US time");
mylist.add(map);
map = new HashMap<String, String>();
map.put("Test1", "####");
map.put("Test2", "UK");
map.put("Time", "UK Time");
mylist.add(map);
ListAdapter mSchedule = new SimpleAdapter( this,
mylist,
R.layout.row,
new String[]
{
"India",
"US",
"UK"
},
new int[]
{
R.id.TRAIN_CELL,
R.id.FROM_CELL,
R.id.TO_CELL,
}
);
list.setAdapter(mSchedule);
}
}
In your ListActivity set onItemClickListener:
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int position,
long id) {
// Do your stuff here
}
});