Multiple Listviews in single Activity in Android? - android

I want to have multiple listviews in single activity. But only one
listview should be displayed at one time. The listviews will be loaded
dynamically. So, how can I fill all the four listviews at the same
time and display only one?

Instead of using all that code to flip between listviews why not put all your listviews inside a ViewFlipper? It the easiest way an required almost 1 line of code! :)
-Moto

You can do one thing for your problem. The reason you will only see the one list view, may be because one list will have the fill parent paramter value for its height. What you have to do is, use absolute layout or just fix the height for each layout. Also use the scrollview to place the controls. Moreover, if you post your XML layout here, then it will be easier to answer your query as to where you need to make changes.

You should use a FrameLayout; it allows z ordering of its child views which means that you can have your ListView stacked one above the other. You can then toggle visibility of each of these ListViews from your code using View#setVisibility() method.
You would create appropriate adapters for each of these ListViews and whenever a ListView is to be drawn the framwork will call getView() method of the required adapter.

I have used mostly the same way of showing multiple listviews as you
suggested i.e. using setvisibility.
But now what I want is to have the Bitmap image of all the four
listviews. Suppose, my activity starts and the data are loaded into
all four listviews by binding them to their respective adapters.
Now, when I am trying to fetch the Bitmap using getDrawingCache() it
always returns null to me.
So, can you let me know how can I fetch the Bitmap of all the four
listviews?
public class HomeScreenActivity extends Activity
{
private ImageView imgBabble = null;
private ListView listBabble = null;
private ListView listVille = null;
private ListView listPrivateMsgs = null;
private ListView listBookmarks = null;
private List<String> tempBabble = null;
private List<String> tempVille = null;
private List<String> tempPrivateMsgs = null;
private List<String> tempBookmarks = null;
//RelativeLayouts
private RelativeLayout babbleLayout = null;
private RelativeLayout villeLayout = null;
private RelativeLayout privateMsgsLayout = null;
private RelativeLayout bookmarksLayout = null;
//Bitmap
private Bitmap babbleShrunkView = null;
private Bitmap villeShrunkView = null;
private Bitmap privateMsgsShrunkView = null;
private Bitmap bookmarksShrunkView = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.homescreen);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
imgBabble = (ImageView) findViewById(R.id.imgBtnBabble);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.babble_top_logo);
BitmapDrawable bmpDrawable = new BitmapDrawable(bitmapOrg);
imgBabble.setBackgroundDrawable(bmpDrawable);
//Initialize the layouts for Babble, Ville, Private Messages and Bookmarks
babbleLayout = (RelativeLayout) findViewById(R.id.babbleLayout);
babbleLayout.setDrawingCacheEnabled(true);
villeLayout = (RelativeLayout) findViewById(R.id.villeLayout);
villeLayout.setDrawingCacheEnabled(true);
privateMsgsLayout = (RelativeLayout) findViewById(R.id.privatemsgsLayout);
privateMsgsLayout.setDrawingCacheEnabled(true);
bookmarksLayout = (RelativeLayout) findViewById(R.id.bookmarksLayout);
bookmarksLayout.setDrawingCacheEnabled(true);
//Babble
tempBabble = new ArrayList<String>();
tempBabble.add("First Babble");
tempBabble.add("Second Babble");
tempBabble.add("Third Babble");
listBabble = (ListView) findViewById(R.id.listBabble);
listBabble.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, tempBabble));
//babbleShrunkView = babbleLayout.getDrawingCache();
//babbleLayout = (RelativeLayout) findViewById(R.id.listLayout);
if(babbleShrunkView == null)
{
System.out.println("Babble View is null");
}
//Ville
tempVille = new ArrayList<String>();
tempVille.add("First Ville");
tempVille.add("Second Ville");
tempVille.add("Third Ville");
listVille = (ListView) findViewById(R.id.listVille);
//listVille.setDrawingCacheEnabled(true);
listVille.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, tempVille));
//villeShrunkView = villeLayout.getDrawingCache();
if(villeShrunkView == null)
{
System.out.println("Ville View is null");
}
//listVille.setVisibility(View.GONE);
//Private Messages
tempPrivateMsgs = new ArrayList<String>();
tempPrivateMsgs.add("First PM");
tempPrivateMsgs.add("Second PM");
tempPrivateMsgs.add("Third PM");
listPrivateMsgs = (ListView) findViewById(R.id.listPrivateMessages);
//listPrivateMsgs.setDrawingCacheEnabled(true);
listPrivateMsgs.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, tempPrivateMsgs));
//privateMsgsShrunkView = privateMsgsLayout.getDrawingCache();
if(privateMsgsShrunkView == null)
{
System.out.println("Private Messages View is null");
}
//listPrivateMsgs.setVisibility(View.GONE);
//Bookmarks
tempBookmarks = new ArrayList<String>();
tempBookmarks.add("First Bookmarks");
tempBookmarks.add("Second Bookmarks");
tempBookmarks.add("Third Bookmarks");
listBookmarks = (ListView) findViewById(R.id.listBookmarks);
//listBookmarks.setDrawingCacheEnabled(true);
listBookmarks.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, tempBookmarks));
//bookmarksShrunkView = bookmarksLayout.getDrawingCache();
if(bookmarksShrunkView == null)
{
System.out.println("Bookmarks Messages View is null");
}
//listBookmarks.setVisibility(View.GONE);
imgBabble.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
System.out.println("Babble Clicked");
babbleShrunkView = babbleLayout.getDrawingCache();
villeShrunkView = villeLayout.getDrawingCache();
privateMsgsShrunkView = privateMsgsLayout.getDrawingCache();
bookmarksShrunkView = bookmarksLayout.getDrawingCache();
BabbleVilleShrinkView.addBitmap(0, resizeBitmap(200, 200, babbleShrunkView));
BabbleVilleShrinkView.addBitmap(1, resizeBitmap(200, 200, villeShrunkView));
BabbleVilleShrinkView.addBitmap(2, resizeBitmap(200, 200, privateMsgsShrunkView));
BabbleVilleShrinkView.addBitmap(3, resizeBitmap(200, 200, bookmarksShrunkView));
Gallery gallery = new Gallery(getApplicationContext());
gallery.setAdapter(new ImageAdapter(getApplicationContext()));
}
});
} // End of class

Related

How can I use the component of any other layout(other than defined in setContentView()) in another activity in android

I'm working on an app in which i need to show some data in listview for that i've created an activity which is connected to the layout containing listview , for that listview i've created custom listitem. Now i need to access the components( Imageview) from custom list item in activity. Can anyone please tell me how to achieve this ?
This is the activity
package com.example.manishnegi.sharemyride;
public class RideMatched extends Activity {
int commentCount = 0;
private List<GetRidesSummaryDetails> oslist = new ArrayList<GetRidesSummaryDetails>();
ListView rides_matchedListview;
ImageView hrate1,hrate2,hrate3,hrate4,hrate5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ride_matched);
hrate1=(ImageView)findViewById(R.id.hrate1);
hrate2=(ImageView)findViewById(R.id.hrate2);
hrate3=(ImageView)findViewById(R.id.hrate3);
hrate4=(ImageView)findViewById(R.id.hrate4);
hrate5=(ImageView)findViewById(R.id.hrate5);
int l=0;
String arr;
JSONArray array=new JSONArray();
Bundle b=getIntent().getExtras();
if(b!=null)
{
l=b.getInt("array_length");
arr=b.getString("rides_array");
try {
array=new JSONArray(arr);
Log.e("String to array ",array.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.e("String to array",e.getMessage());
}
Log.e("Number of matched",l+"");
}
rides_matchedListview = (ListView)findViewById(R.id.rides_matchedListview);
Second scnd = new Second();
List<GetRidesSummaryDetails> detailsofrides = scnd.getallcomments(l,array);
for (GetRidesSummaryDetails values :detailsofrides){
String driver_imageget = values.getDriverimage();
String driver_nameget = values.getDrivername();
String pickup_get = values.getPickuptime();
String ride_idget= values.getRideId();
String rating_get = values.getRating();
String vehicle_imageget = values.getVehicleImage();
GetRidesSummaryDetails vehi = new GetRidesSummaryDetails();
vehi.setDriverimage(driver_imageget);
vehi.setDrivername(driver_nameget);
vehi.setPickuptime(pickup_get);
vehi.setRideId(ride_idget);
vehi.setRating(rating_get);
setRating(Integer.parseInt(rating_get));
vehi.setVehicleImage(vehicle_imageget);
oslist.add(vehi);
commentCount++;
rides_matchedListview.setAdapter(new RidesMatchedAdapter(RideMatched.this, 0, oslist));
new RidesMatchedAdapter(RideMatched.this ,0, oslist).notifyDataSetChanged();
}
}
public void setRating(int rate)
{
if (rate == 1) {
hrate1.setImageResource(R.drawable.star);
}
if (rate == 2) {
hrate1.setImageResource(R.drawable.star);
hrate2.setImageResource(R.drawable.star);
}
if (rate == 3) {
hrate1.setImageResource(R.drawable.star);
hrate2.setImageResource(R.drawable.star);
hrate3.setImageResource(R.drawable.star);
}
if (rate == 4) {
hrate1.setImageResource(R.drawable.star);
hrate2.setImageResource(R.drawable.star);
hrate3.setImageResource(R.drawable.star);
hrate4.setImageResource(R.drawable.star);
}
if (rate == 5) {
hrate1.setImageResource(R.drawable.star);
hrate2.setImageResource(R.drawable.star);
hrate3.setImageResource(R.drawable.star);
hrate4.setImageResource(R.drawable.star);
hrate5.setImageResource(R.drawable.star);
}
}
}
This is the listview layout(ride_matched.xml)
This is the custom list item
You must've created the adapter for the listview using that adapter declare the images inside viewHolder it should work.
Use any adapter (according to your need) to inflate data in the ListView. In the adapter itself, you can access the components of custom listitem.
You cannot access the components of custom listitem inside the activity. They can only be accessed inside the adapter inflating the data in the ListView.
We need to pass adapter to the listview. Adapters contain list of model object to be shown in list . You can create a custom adapter extending the base adapter. You can follow the below tutorial
http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92
p[ay attention to getView method in the adapter and change the layout name as per you custom layout in the following line of get view
vi = inflater.inflate(R.layout.tabitem, null);
Create a holder class where it has all the view item required to display in your list.
You need not to access Image view from activity as it can be accessed in the getView method for each row iteration.

Weird Behavior about notifyDatasetChanged refreshment

Background
Hi, I am new to Android and trying to get familiar with ListView. So I decide to write a simple program for user to enter quotes and display them in order. I implement a StringAdapter and call the notifyDataSetChanged every time when the user confirms.
Question
The weird thing is that the ListView would sometimes update the oldest quotes and sometimes the newer one. and I don't know the problem.
Please ignore the view data button. In this state, I have entered four quotes:
Quotes: hi - Signature:William Shakespeare
Quotes: hello - Signature:William Shakespeare
Quotes: Virtue is bold and goodness never fearful. - Signature:William Shakespeare
Quotes: Love all, trust a few, do wrong to none. - Signature:William Shakespeare
(in reverse order, meaning in time sequence, it goes 4,3,2,1)
Code
main activity
public class storage extends AppCompatActivity {
// the adapter
private StringAdapter sa;
// the edit text view
public EditText etString,etSignature;
// the list view
public ListView lv;
// the array list to capture the quotes and signature
private ArrayList<String[]> dataString = new ArrayList<String[]>();
// add the string and notify
public void addString(String[] s){
this.dataString.add(0,s);
((BaseAdapter)this.lv.getAdapter()).notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_storage);
// Link the view elements
this.etString = (EditText) findViewById(R.id.etInput);
this.etSignature = (EditText) findViewById(R.id.etSignature);
this.lv = (ListView) findViewById(R.id.stringList);
Button btn_confirm = (Button) findViewById(R.id.btnConfirm),
btn_viewData = (Button) findViewById(R.id.btnViewData);
// load the adapter
this.sa = new StringAdapter(this,this.dataString);
lv.setAdapter(sa);
btn_confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
storage s = (storage) v.getContext();
// get the String
String sString = s.etString.getText().toString(),
sSignature = s.etSignature.getText().toString();
System.out.println("Quotes: " + sString + "\nSignature:" + sSignature);
// verify it is not empty
if (!sString.isEmpty()&&!sSignature.isEmpty()) {
// add new string and notify
s.addString(new String[]{s.etString.getText().toString(),
s.etSignature.getText().toString()});
((StringAdapter) s.lv.getAdapter()).print_stringData();
// prompt the result
Toast.makeText(s.getBaseContext(),
"Enter Quotes from"+etSignature.getText().toString(),Toast.LENGTH_SHORT).show();
} else {
// prompt the result
Toast.makeText(s.getBaseContext(),
"Please Enter Quotes and Signatures!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
StringAdapter
public class StringAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String[]> dataStrings = new ArrayList<String[]>();
public StringAdapter(Context c,ArrayList<String[]> dataStrings){this.mContext=c;this.dataStrings=dataStrings;}
public int getCount(){return this.dataStrings.size();}
public Object getItem(int position){ return this.dataStrings.get(position);}
public long getItemId(int postion){ return (long) postion;}
public void print_stringData(){
System.out.println("String Adapter Output:");
for(String [] s: this.dataStrings){
System.out.println("Quotes: "+s[0]+"\nSignature:"+s[1]);
}
}
public View getView(int position, View convertView, ViewGroup parent){
LinearLayout ll;
if(convertView == null){
// set the linear layout
ll = new LinearLayout(this.mContext);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// get the data and set the text inside
String[] data = this.dataStrings.get(position);
TextView //tvNo = new TextView(this.mContext),
tvString = new TextView(this.mContext),
tvSignature = new TextView(this.mContext);
ll.addView(tvString);
ll.addView(tvSignature);
tvString.setText(data[0]);
tvString.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tvSignature.setText(data[1]);
tvSignature.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tvSignature.setGravity(Gravity.RIGHT);
}
else{
ll = (LinearLayout) convertView;
}
return ll;
}
}
Comments
Some might notice that I add the String[] always to the first element. Actually I have tried to add to the last. The weird behavior still exists.
Environment
Android SDK Version: API 23 lollipop
Emulator Version: Nexus S API 23
Yes, of course, you get that error. Why? Because ListView always re-use convertView in your getView function of Adapter.
Look at your if,else:
else{
ll = (LinearLayout) convertView;
}
return ll;
At this block, you tell the adapter reuse the convertView, but you dont re-set the data. As a result, it will show the data of the previous row.
How to resolve it? just set the data in else block as you do in if one.
P/s: you should learn how to use ViewHolder in ListView to avoid laggy in when scrolling.

notifyDataSetChange does not refresh ListView with custom adapter

I am trying to figure this out, but i just cant see what i am doing wrong. I want to dynamically fill ListView with products (add product to array then refresh list, basically for every click add one product to array then display content of array in ListView) which is in 2nd fragment with the data from the first Fragment. Passing Data is working (used Log to confirm), but my main problem is updating the ListView which has custom adapter. With this code nothing is happening (ViewList is not refreshing, I can see every log (and everything else works) and no errors).
Here is the code (All this is in 2nd Fragment):
This code is global
ReceiptListAdapter receiptListAdapter;
ArrayList<ReceiptItem> receiptItemArrayList;
int cat = 0;
int prodct = 0;
With this i get 2 numbers from 1st fragment (to this 2nd fragment)
public void use(int num1, int num2) {
Log.d("LOG","Category: " + num1 + "Product: " + num2); //This works
cat = num1;
prodct = num2;
ListView receiptItemListView = (ListView) getView().findViewById(
R.id.receiptItemsList);
receiptItemArrayList = (ArrayList<ReceiptItem>)generateReceiptItemsForTest();
receiptItemListView.setAdapter(receiptListAdapter); //i think here is the problem
receiptListAdapter.notifyDataSetChanged();
}
OnViewCreated
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView receiptItemListView = (ListView) getView().findViewById(
R.id.receiptItemsList);
receiptItemArrayList = (ArrayList<ReceiptItem>) generateReceiptItemsForTest();
receiptListAdapter = new ReceiptListAdapter(
getActivity().getBaseContext(), R.layout.receipt_item,
receiptItemArrayList);
receiptItemListView.setAdapter(receiptListAdapter);
TextView txtTotalAmmount = (TextView) getView().findViewById(
R.id.txtReceiptTotalAmmount);
double totalAmmount = getTotalAmmount(receiptItemArrayList);
totalAmmount = Math.round(totalAmmount * 100) / 100;
txtTotalAmmount.append(String.valueOf(totalAmmount));
}
private List<ReceiptItem> generateReceiptItemsForTest() {
List<ReceiptItem> receiptItemList = new ArrayList<ReceiptItem>();
DatabaseAdapter db = new DatabaseAdapter(getActivity());
if(cat != 0 && prodct != 0 )
{
name = db.readFromCategoriesAndGetOnePreduct(cat, prodct).getName();
price = db.readFromCategoriesAndGetOnePreduct(cat, prodct).getPrice();
Log.d("Name: " + name,"Price: " + String.valueOf(price)); //Also working (showing what i want) and i can see it in log but the ListView isnt refreshing this data
receiptItemList.add(new ReceiptItem(name,1,price,1);
}
}
return receiptItemList;
}
private double getTotalAmmount(ArrayList<ReceiptItem> receiptItems) {
double totalAmmount = 0;
for (ReceiptItem receiptItem : receiptItems) {
totalAmmount += receiptItem.getTotalPrice();
}
return totalAmmount;
}
ReceiptListAdapter
public class ReceiptListAdapter extends ArrayAdapter<ReceiptItem> {
private Context context;
public ReceiptListAdapter(Context context, int rowResourceId,
ArrayList<ReceiptItem> items) {
super(context, rowResourceId, items);
this.context = context;
}
#SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.receipt_item, null);
}
ReceiptItem item = getItem(position);
if (item != null) {
TextView itemDescription = (TextView) view
.findViewById(R.id.txtReceiptItemDescription);
TextView itemAmmount = (TextView) view
.findViewById(R.id.txtReceiptItemAmmount);
TextView itemPrice = (TextView) view
.findViewById(R.id.txtReceiptItemPrice);
TableRow listItem = (TableRow) view
.findViewById(R.id.trReceiptItem);
if (position % 2 == 0)
listItem.setBackgroundDrawable(view.getResources().getDrawable(
R.drawable.list_item_selector_a));
else
listItem.setBackgroundDrawable(view.getResources().getDrawable(
R.drawable.list_item_selector_b));
itemDescription.setText(item.getDescription());
itemAmmount.setText(String.valueOf(item.getAmmount()));
itemPrice.setText(String.format("%.2f", item.getPrice()));
}
return view;
}
}
Only time I got the list to update is when I used this code
receiptListAdapter = new ReceiptListAdapter(getActivity().getBaseContext(),R.layout.receipt_item,
instead of
receiptItemListView.setAdapter(receiptListAdapter);
But it only adds one time and refreshes the list again on click, but i know why.
Can you post the ReceiptListAdapter code? That is where you need to make the connection between the data source and the UI. You do this by registering ContentObservers on the database and then the ListView registers its ContentObserver with the Adapter. The Adapter notifies the ListView to update by calling the onChanged() method of the ListView DataSetObserver.
When working with a database, a common choice is to use a CursorLoader to fetch the data from the database on a background thread paired with a CursorAdapter. The CursorLoader automatically registers with the database to be notified of changes. You then implement the LoaderManager callbacks which tell you when the dataset changes and passes you an updated cursor. You then call swapCursor(cursor) on the CursorAdapter, passing it the new cursor and it notifies the ListView DataSetObserver that the dataset has changed. The ListView then queries the adapter to get the new values and refreshes the UI.
Check out this tutorial for some good example code: http://www.vogella.com/tutorials/AndroidSQLite/article.html
I figured it out i had to make this global List<ReceiptItem> receiptItemList = new ArrayList<ReceiptItem>(); Also I would like to thank middleseatman for explaining some things, it really helped me.

Android: Using a method to initialize associate spinners with views causing null pointer exception

I'm writing an app with quite a lot of spinners in it. In order to make things more concise, I made a method that associates a spinner with a view and array adapter. However, I'm getting a null pointer exception whenever I try to use that spinners (e.g set Visibility).
Here's my code:
private void setSpinners() {
ManureID = R.id.smanure;
ApplicationID = R.id.sapplication;
SlurryID = R.id.sslurry;
MaturityID = R.id.smaturity;
TimingID = R.id.stiming;
SoilTypeID = R.id.ssoil;
PreviousCropID = R.id.scropping;
GrassRotationID = R.id.sgrassrot;
RainID = R.id.srain;
StrawID = R.id.sstraw;
PID = R.id.sp;
KID = R.id.sk;
MgID = R.id.smg;
// TODO update slurry values depending
setSpinner(SlurryID, Slurry, slurrys);
setSpinner(ApplicationID, Application, application);
setSpinner(ManureID, Manure, manures);
setSpinner(MaturityID, Maturity, maturity);
setSpinner(TimingID, Timing, timing);
setSpinner(SoilTypeID, SoilType, soilTypes);
setSpinner(PreviousCropID, PreviousCrop, previousCrops);
setSpinner(GrassRotationID, GrassRotation, grassRotations);
setSpinner(RainID, Rain, rain);
setSpinner(StrawID, Straw, straw);
setSpinner(PID, P, p);
setSpinner(KID, K, k);
setSpinner(MgID, Mg, mg);
}
private void setSpinner(int ID, Spinner spinner, ArrayList<String> list) {
spinner = (Spinner) findViewById(ID);
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,
ID, list);
spinner.setAdapter(adapt);
}
I'm assuming that the method is at fault. Is it not actually associating views with spinners correctly? Is there a way to fix the method?
Thanks!
You always find just one spinner in setSpinner method right here
spinner = (Spinner) findViewById(ID);
. at last you will be able to use the spinner with R.id.smg id.
you need to do is this:
public void SetAllSpinners(int rootID) {
ViewGroup vg = (ViewGroup) findViewById(rootID);
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
/*
Here check all the layouts that you used to contain your spinners
*/
if(v instanceof LinearLayout || v instanceof RelativeLayout){
SetAllSpinners(v.getId());
}
if (v instanceof Spinner) {
Spinner sx = (Spinner) v;
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, ID,
list);
sx.setAdapter(adapt);
}
}
}
you have to call this method like:
SetAllSpinners(R.id.rootLayoutThatContainsYourSpinners);
after setting the array adapter you can set your events there.
let me know if this works please..

Add new LinearLayout on each iteration of Activity

In one of my activities, I create a Linear Layout and some other Widgets when a bundle is received from an Intent. Currently, that Layout is overwrited each time I come back to that Activity. How can I create a new Layout each time without rewriting the code?
CODE:
public class FrontPageActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frontpage);
Bundle bundle = this.getIntent().getExtras();
try{
String size = bundle.getString("size");
int toppcount = bundle.getStringArrayList("toppings").toArray().length;
LinearLayout container = (LinearLayout)findViewById(R.id.container);
TextView t = new TextView(this);
TextView tprice = new TextView(this);
tprice.setGravity(Gravity.RIGHT);
LinearLayout inner = new LinearLayout(this);
LinearLayout.LayoutParams innerparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
inner.setLayoutParams(innerparams);
inner.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
inner.setPadding(10,10,10,10);
if(toppcount == 0){
t.setText(size+" Cheese Pizza");
}
else{
t.setText(size+" "+toppcount+" Topping Pizza");
}
tprice.setText(getPrice(size, toppcount)+"");
tprice.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
container.addView(inner);
inner.addView(t);
inner.addView(tprice);
}
catch(NullPointerException e){
}
final Intent sender = new Intent(this.getApplicationContext(), OrderPizzaActivity.class);
Button badd = (Button)findViewById(R.id.buttonaddpizza);
badd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivityForResult(sender, 0);
}
});
}
It sounds like you would need to create a data structure to hold the LinearLayouts, or provide a ViewGroup container for them to be added to each time.
Currently you are creating, modifying, and then overwriting the same LinearLayout in the try{} catch(){} block. Which I would guess to be the reason why it keeps overwriting.
As I understood you add new "options" to the "final order". Every time additional topping added you create a layout and fill it with specific data. And you want it to be aka OrderList. If what this app is about, you can have an application level variable myOrder:List. Add there toppings (topping = new Order()) and read list in FrontPageActivity.
Recommend you to have a separate layout for an order. Looping through orders fill layout with data and inflate in a container of Activity.
Idea in pseudo:
MyApplication extends Application {
private static List<Order> mOrderList = null;
public MyApplication(){
mOrderList = new ArrayList<Order>();
}
public static List<Order> getOrderList(){
return mOrderList();
}
public static void addOrder(Order order) {
mOrderList.add(order);
}
}
options activity:
MyApplication.add(order);
MyApplication.add(order);
FrontPageActivity
foreach(Order order : MyApplication.getOrderList()) {
// fill layout with order data
// inflate orderLayout into container
}

Categories

Resources