Displaying ArrayList Information When Opening an Activity - android

I've only been working with Android for 2 weeks and I'm trying to create a simple homework assignment list to learn the basics. The code I have written displays information through an EditText and an ArrayList. When I go to one of my activities through my MainActivity and add information it shows up great. But when I go back to my MainActivity and back again to my previous activity. My data is deleted (or not displayed, I'm not sure). I'm sure I'm messing up something basic. If anyone is willing to offer some help or pointers, I'd greatly appreciate it. Thank You!
Here is my MainActivity Code:
package com.example.homeworkassignments;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
public class MainActivity extends Activity {
// instantiation of buttons
private Button btnDatabase;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems = new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseButton();
} // end onCreate()
public void databaseButton() {
//create database button
btnDatabase = (Button)findViewById(R.id.databaseBtn);
btnDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start Database class when identify button is clicked
Intent i = new Intent(MainActivity.this, Database.class);
startActivity(i);
}
});
} // end databaseButton()
Here is my Database Activity Class Code:
package com.example.homeworkassignments;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class Database extends ListActivity {
private Button addData;
private Button removeData;
private Button back;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems = new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
setListAdapter(adapter);
addButton();
removeButton();
backButton();
} // end OnCreate()
public void addButton() {
// create add button
addData = (Button)findViewById(R.id.databaseAddBtn);
addData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView myEdit = (TextView)findViewById(R.id.editText1);
String myEditValue = myEdit.getText().toString();
listItems.add(myEditValue);
adapter.notifyDataSetChanged();
myEdit.setText("");
}
});
} // end addButton()
public void removeButton() {
// create remove Button
removeData = (Button)findViewById(R.id.databaseRemoveBtn);
removeData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listItems.isEmpty()) {
listItems.clear();
}
else {
listItems.remove(0);
}
adapter.notifyDataSetChanged();
}
});
}
public void backButton() {
// create back Button
back = (Button)findViewById(R.id.databaseBackBtn);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Database.this, MainActivity.class);
startActivity(i);
}
});
} // end backButton()
} // end Database class
And finally, here is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal" >
<Button
android:id="#+id/databaseAddBtn"
style="?#android:style/ButtonBar"
android:layout_width="35dp"
android:layout_height="35dp"
android:text="#string/add_button" />
<Button
android:id="#+id/databaseRemoveBtn"
style="?#android:style/ButtonBar"
android:layout_width="35dp"
android:layout_height="35dp"
android:text="#string/remove_button" />
<Button
android:id="#+id/databaseBackBtn"
style="?#android:style/ButtonBar"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:text="#string/back" />
</LinearLayout>
<EditText android:id="#+id/editText1"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="35dp"
android:ems="10" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />
</LinearLayout>
I understand it's a lot and probably very poorly written, but any help or advice would be extremely appreciated (I'm just trying to learn Android!)

ok i think u want to keep the arraylist constant in Database.java...
there are 2 cases of storage i can guess :-
if u only want to store until you are executing the app and you allow the data be lost if the app is exited then in that case simply do this
a. Declare an ArrayList like this public ArrayList<String> listItems = new ArrayList<String>(); in MainActivity.java and remove the same from Database.java.
b. to add to this list you will access using MainActivity.listItems.add(object);
You can try using public static ArrayList<String> listItems = new ArrayList<String>();
instead in MainActivity note the "static" it can hold data even if u exited the app.For
more on static variables you can refer any tutorial.
it should store the data permanently so dat even if you reboot you will have the data.
if your case is this then u need to use database.
Hope it helps ....
thanks

Related

what is the difference between notifyDataSetChanged and add(T object) or addAll(T... items) methods in array adapter?

I'm trying to learn List view and adapters, made a very basic app to learn in which I have a button that inserts a String object to the data source of an array adapter and the other view is list view which shows this data set. add() and addAll() method apends the data to the data set but when I do that list view shows it but I didn't call notifyDataSetChanged method, so why list view refreshed itself and if it did so then why do I need the method? Could anyone help me by giving some clarity? add(), addAll() and insert() methods already making the list view show the new added data but how? so what's the difference?
the app's only layout:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="8dp">
<Button
android:id="#+id/insert_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="insert data"/>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
the main activity code:
package famiddle.smart.apps.learningandroid;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button insertButton;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> data = new ArrayList<>();
data.add("hello world");
ListView listView = findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
insertButton = findViewById(R.id.insert_button);
insertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.add("hi there");
}
});
}
}

OnClick Button action in Custom ListView

Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.
Here is the Product Adapter
package com.example.raswap.octomatic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aurora on 22/03/16.
*/
public class Pro_Adapter extends ArrayAdapter {
List list = new ArrayList();
public Pro_Adapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler{
ImageView img;
TextView p_name;
TextView b_name;
TextView price;
Button b_atc;
}
#Override
public void add(Object object) {
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.e_layout, parent, false);
handler = new DataHandler();
handler.img = (ImageView)row.findViewById(R.id.pro_image);
handler.p_name = (TextView)row.findViewById(R.id.pro_name);
handler.b_name = (TextView)row.findViewById(R.id.brand);
handler.price = (TextView)row.findViewById(R.id.pricing);
handler.b_atc = (Button)row.findViewById(R.id.atc);
row.setTag(handler);
}else{
handler = (DataHandler)row.getTag();
}
Product_data_provider dataProvider;
dataProvider = (Product_data_provider)this.getItem(position);
handler.img.setImageResource(dataProvider.getPro_img_resource());
handler.p_name.setText(dataProvider.getPro_name());
handler.b_name.setText(dataProvider.getBr_name());
handler.price.setText(dataProvider.getPricing());
return row;
}
}
Here is the Main Activity class:
package com.example.raswap.octomatic;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class E_shop extends Activity {
ListView listView;
int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
String[] pro_name;
String[] br_name;
String[] price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_e_shop);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
View z = findViewById(R.id.oct_logo);
z.setClickable(true);
z.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, MainActivity.class));
}
});
View x = findViewById(R.id.for_user_info);
x.setClickable(true);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, UserInformation.class));
}
});
Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
ListView listView = (ListView)findViewById(R.id.e_list);
listView.setAdapter(adapter);
pro_name = getResources().getStringArray(R.array.nameOfProduct);
br_name = getResources().getStringArray(R.array.branding);
price = getResources().getStringArray(R.array.pricing);
int i = 0;
for(String pro: pro_name){
Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
adapter.add(dataProvider);
i++;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
newActivity.putExtra("pro_emage",R.drawable.gb32);
newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
startActivity(newActivity);
break;
case 1:
Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
Activity1.putExtra("pro_emage",R.drawable.tb1);
Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
startActivity(Activity1);
break;
case 2:
Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
Activity2.putExtra("pro_emage", R.drawable.dvd);
Activity2.putExtra("title", "A pack of 50 DVD's");
Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
startActivity(Activity2);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
}
}
Here is the Product Data Provider Class:
package com.example.raswap.octomatic;
/**
* Created by aurora on 22/03/16.
*/
public class Product_data_provider {
private int pro_img_resource;
private String pro_name;
private String br_name;
private String pricing;
public int getPro_img_resource() {
return pro_img_resource;
}
public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
this.setPro_img_resource(pro_img_resource);
this.setPro_name(pro_name);
this.setBr_name(br_name);
this.setPricing(pricing);
}
public void setPro_img_resource(int pro_img_resource) {
this.pro_img_resource = pro_img_resource;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getBr_name() {
return br_name;
}
public void setBr_name(String br_name) {
this.br_name = br_name;
}
public String getPricing() {
return pricing;
}
public void setPricing(String pricing) {
this.pricing = pricing;
}
}
Now, Custom ListView XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/pro_image"
android:src="#drawable/gb32"
android:layout_width="160dp"
android:layout_height="match_parent" />
<LinearLayout
android:background="#afeeee"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Product Name"
android:id="#+id/pro_name"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Branding"
android:id="#+id/brand"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:textColor="#000"
android:id="#+id/pricing"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:id="#+id/atc" />
</LinearLayout>
</LinearLayout>
<View
android:layout_below="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>
</RelativeLayout>
</RelativeLayout>
and finally the main layout XML file:
<?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"
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.example.raswap.octomatic.E_shop">
<ListView
android:id="#+id/e_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.
Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here
Add the onClickListener to your Button in getView() of your ListAdapter.
If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview
you can try this.
Change in custom Listview xml file.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:onClick="AddCart"
android:id="#+id/atc" />
In MainActivity
public void AddCart(View v)
{
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
child.setText("I've been clicked!");
vwParentRow.refreshDrawableState();
}

Android ListView wont scroll

I have tried so many things to get my android ListView to scroll. However I have been unsuccessful in my attempt. Here is my xml code below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:listSelector="#color/theme_colour"
android:scrollbarStyle="outsideInset">
</ListView>
</RelativeLayout>
I have also added my java code below. I am not sure how to fix this problem and your help would be greatly appreciated.
package com.outdeh;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
/**
* Created by horacedaley on 2/15/14.
*/
public class EventsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
populateListView();
}
public void populateListView(){
ParseQueryAdapter<ParseObject> adapter =
new ParseQueryAdapter<ParseObject>(this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
// Here we can configure a ParseQuery to our heart's desire.
ParseQuery query = new ParseQuery("Events");
query.orderByAscending("eDate");
return query;
}
});
adapter.setTextKey("eTitle");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setFastScrollEnabled(true);
listView.setAdapter(adapter);
}
}
Try changing android:layout_height="wrap_content"s to android:layout_height="match_parent". I guess it doesn't scroll because when you set the height to "wrap_content" the view will go beyond the visible area in activity, and since all items are considered displayed (in spite of not being in the visible area), there won't be scrolling available.

Android: Simpify many classes and xml

Edit: I cannot get this to work correctly. Probably because I have no idea what I am doing. Anyways, here's my code. If anyone could help, I'd be very grateful: I needs to get it to display the battery mood image for the corresponding mod...
Themes:
package com.cydeon.plasmamodz;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class Themes extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themes);
ActionBar actionBar = getActionBar();
actionBar.hide();
Button Plus = (Button) findViewById(R.id.button1);
Button Blue = (Button) findViewById(R.id.button2);
Plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Themes.this, Bmod.class);
i.putExtra("drawableResource", R.drawable.blue);
Themes.this.startActivity(i);
}
});
Blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent a = new Intent(Themes.this, Bmod.class);
a.putExtra("drawableResource1", R.drawable.plus);
Themes.this.startActivity(a);
}
});
}
}
Bmods:
package com.cydeon.plasmamodz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class Bmod extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.battery);
Intent i = getIntent();
int drawableResource = i.getIntExtra("drawableResource", R.drawable.blue);
ImageView img = (ImageView) findViewById(R.id.iv1);
img.setImageResource(R.drawable.blue);
Intent a = getIntent();
int drawableResource1 = a.getIntExtra("drawableResource1", R.drawable.plus);
ImageView img1 = (ImageView) findViewById(R.id.iv1);
img1.setImageResource(R.drawable.plus);
}
}
battery(xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/bInstall"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Install" />
<Button
android:id="#+id/bReturn"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Return" />
<ImageView
android:id="#+id/iv1"
android:layout_width="match_parent"
android:layout_height="800dp" />
</RelativeLayout>
Intent i = new Intent(this, BaseClassForMod);
i.putExtra("drawableResource", R.drawable.this_mod_drawable);
startActivity(i);
Then in that Activity's onCreate():
Intent i = getIntent();
int drawableResource = i.getIntExtra("drawableResource", R.drawable.default);
//Get a reference to your ImageView...
imageView.setImageResource(drawableResource);
Don't trust this code to compile, but that's the general idea. Use the same Activity for all of them, pass along the proper resource ID in the intent (e.g. for mod1, send the drawable ID for mod1), then in the activity, check for that resource ID and set it programmatically.
You shouldn't need 50 classes and 50 xml layouts if every one of them does the same thing. Make one activity and one layout. When the user selects something, pass an id of some kind as an Intent extra to the second activity so it can load whatever item is appropriate. I don't know how your data is modeled, but there should be a way to uniquely identify each option (and if there isn't, you should implement one).
Your first activity also doesn't need a button for each item. Use a ListView and an Adapter, and then you just need to provide a layout for one row.
make a single activity only. Inside of it get a reference to your image:
ImageView iv = (ImageView)findViewById(R.id.yourImgId);
Then set the picture to whichever one you want like:
iv.setImageResource(R.drawable.battery_img_1);

How to get multiple selected items from a ListActivity in Android

I am basically trying to get which items have been selected within a multiple choice enabled ListActivity. I am sure that there are many beginning Android programmers that would love this to be clarified. This app runs fine until it gets to the FOR loop and tries to assign the values of the multi-choice items to ArrayList 'items'. I'm simply trying to use Toast to see if the multi-choice items are being assigned to the Arraylist 'items'. The app crashes when the button is clicked. testing is done in android 2.2 emulator
Here is my Main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected Items" />
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:choiceMode="multipleChoice"
android:textFilterEnabled="true" android:fastScrollEnabled="true" >
</ListView>
</LinearLayout>
and here is the code
package com.tests.TestCode;
import android.app.ListActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] list = {"wrenches","hammers","drills","screwdrivers","saws","chisels","fasteners"};
// Initializing An ArrayAdapter Object for the ListActivity
final ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_multiple_choice, list);
setListAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ListView thelistview = (ListView) findViewById(android.R.id.list);
ArrayList<String> items = null;
SparseBooleanArray checkedItems = thelistview.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = adapter.getItem(checkedItems.keyAt(i)).toString();
items.add(item);
}
}
Toast.makeText(getBaseContext(), items.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "checkedItems == null", Toast.LENGTH_LONG).show();
}
}
});
}
}
Much obliged to anyone that can provide a good answer as to the best way to go about accomplishing this ListActivity scenario, or anyone that can explain why the app crashes at the point of assignment to the ArrayList. Thanks!
Your items list is null and you try to use it before initializing it.
You need to use items = new ArrayList<String>(); somewhere before trying to use it, or you will keep getting NullPointerExceptions.

Categories

Resources