I have a menu (fishcombovaluemeals), and when the user select more than 1 item i want those
items to appear in a list in another activity (shopping cart) ,i have tried alot but the data
never appears in the shopping cart ! what is wrong in the onitemclick !? ,
I have
fishcombovaluemeal.java
RowItem.java
CustomListViewAdapter.java
fishcombovaluemealsactivitycode:
package com.example.newlist;
public class FishComboValueMeals extends Activity implements
OnItemClickListener {
ImageButton Ib2;
public static final String[] titles = new String[] {
" Fillet-O-Fish (Medium Value Meals) ",
"Fillet-O-Fish (Large Value Meals) ",
"Double Fillet-O-Fish (Medium Value Meals)",
" Double Fillet-O-Fish (Large Value Meals) ",
};
public static final String[] descriptions = new String[] {
"Light, flaky filet of white fish topped with tangy tartar ",
"Light, flaky filet of white fish topped with tangy tartar ",
"2 patties of tender fish filet over a layer of cheese, ",
" 2 patties of tender fish filet over a layer of "
};
public static final Integer[] images = {
R.drawable.imfc1,
R.drawable.imfc2,
R.drawable.imfc3,
R.drawable.imfc4 };
public static final Double[] prices = { 20.0, 22.73, 24.77, 27.04 };
ListView listView;
List<RowItem> rowItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breakfast);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem (images[i], titles[i], descriptions[i],
prices[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
Ib2 = (ImageButton) findViewById (R.id.Button02);
Ib2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generatedmethod stub
Intent openStartingPoint = new Intent (getApplicationContext(),ShoppingCart.class);
startActivity (openStartingPoint);
}
});}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtra("EXTRA", "Item " + (position + 1) + ": " + rowItems.get(position));
startActivity(i);
}
}
get the selected item of list view and send the value via intent
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = lv1.getItemAtPosition(position).toString();
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtra("EXTRA", value);
startActivity(i);
}
and get the value in other activity
Bundle bundle=getIntent().getExtras();
String value=bundle.getString("EXTRA");
You can use a very simple Class which will store your data into it.
I warn you that this class is just a simple proposition how to solve your problem.
It has many weaknesses but it works ; )
You can improve it : )
Just init it at Application Class.
Here is example:
/**
* Manager to handle passing data between Activities
*
* #author Klawikowski
*
*/
public class ManagerBundle implements IConstants
{
public static final String TAG = "ManagerBundle";
private static Hashtable< Integer , Object > sDataTable;
public static void init()
{
Log.i( TAG , "[ManagerBundle] Initializing ..." );
sDataTable = new Hashtable< Integer , Object >();
}
public static void addBundle( int pKey , Object pObjectToPass )
{
Log.i( TAG , "[ManagerBundle] Adding Object to Manager using key: " + pKey );
sDataTable.put( pKey , pObjectToPass );
}
public static Object getBundle( int pKey )
{
Log.i( TAG , "[ManagerBundle] Getting Object from Manager using key: " + pKey );
Object lData = sDataTable.get( pKey );
sDataTable.remove( pKey );
return lData;
}
}
Just simply put an Table / Array or any other container before starting Activity, and collect it from 2nd one ; )
You need to create a singleton array of the menu items. When user performs multi select jst store the selectedindex to an array and then pass that array to the intent.
Here is the tutorial for multi-select listview
http://www.vogella.com/articles/AndroidListView/article.html
Here is the code to send array in intent
Bundle b=new Bundle();
b.putStringArray(key, new String[]{value1, value2});
Intent i=new Intent(context, Class);
i.putExtras(b);
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
You can try this
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
RowItem selItem = rowItems.get(position);//get the selected RowItem from the list
String[] selValues= selItem.getMethodName();//your method name in RowItem.java class
//which returns array
//if you have getter and setters you can access them and put them in array
//String[] selArray = new String[size];//size = number of value you want to supply
//String[0]= selItem.getTitle();//for title
//String[1] = selItem.getDescription();//for description and so on
//then send the array as parameter
// remaining is same as answered by the Jay Gajjar
Bundle b=new Bundle();
b.putStringArray("EXTRA", selArray);
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtras(b);
startActivity(i);
}
and to retrieve the values in the ShoppingCart class
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray("EXTRA");
Related
I want to retrieve an objectID of an item (to be specific, it's a class called "Room" in our Parse Model) clicked within a ListView.
And after that, I want to pass the retrieved ObjectID to another class using Intent.
I tried parse docs' getObjectId(); method but seems like it won't work.
How should I retrieve it?
Here's my code.
Button createBtn;
Button searchBtn;
Button myGroupBtn;
Button settingBtn;
String[] courses;
List<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
TextView textView;
// when CREAT button is tapped
public void createBtn(View view){
Intent i = new Intent(getApplicationContext(), Create.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
// when Setting button is tapped
public void settingBtn(View view) {
Intent i = new Intent(getApplicationContext(), Setting.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String courseName = intent.getStringExtra("courseName");
String courseNumber = intent.getStringExtra("courseNumber");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Making Links to Buttons on Create
createBtn = (Button) findViewById(R.id.createBtn);
searchBtn = (Button) findViewById(R.id.searchBtn);
myGroupBtn = (Button) findViewById(R.id.myGroupBtn);
settingBtn = (Button) findViewById(R.id.settingBtn);
//Chaning the button colors
searchBtn.setTextColor(0xFFFFFFFF);
createBtn.setTextColor(0xFFBFBFBF);
myGroupBtn.setTextColor(0xFFBFBFBF);
settingBtn.setTextColor(0xFFBFBFBF);
listView= (ListView)findViewById(R.id.listView);
textView= (TextView)findViewById(R.id.textView2);
textView.setText(courseName + " " + courseNumber);
listItems = new ArrayList<>();
ParseQuery<ParseObject> roomQuery = ParseQuery.getQuery("Room");
roomQuery.whereEqualTo("course" , courseName);
roomQuery.whereEqualTo("number" , courseNumber);
roomQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject room : objects) {
Log.i("Appinfo", String.valueOf(room.get("title")));
String stringToAdd = "";
String opened = String.valueOf(room.get("opened"));
String x;
if(opened.equals(true)){
x = "Open";
}else{
x = "Closed";
}
stringToAdd = stringToAdd + String.valueOf(room.get("studyDate")) + " " +
String.valueOf(room.get("category")) + " " + x + "\n"
+ String.valueOf(room.get("title")) +
" "
;
listItems.add(stringToAdd);
Log.i("Appinfo", "A");
}
} else {
Log.i("Appinfo", "B");
e.printStackTrace();
}
}
});
initList();
}
public void initList() {
Log.i("Appinfo", "C");
adapter = new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), Room.class);
String category = listItems.get(position);
}
}
Your problem is that you loose the objectId of Parse in your "Adapter": you use Strings and the basic android Adapter (there: new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);) to display your elements; the problem is that converting your complicated Room object into String which does not contain a lot of informations makes you loose the objectId you want to keep.
The solution to your problem is a very Android-ish pattern called Adapter or more specifically for this case a Custom Adapter which will explain to the device how to render your Room elements into every cell of your app's ListView.
It is extremely well documented (much better that everything I could possibility write in this post) so here is the generic official doc and here is, to me, the best tutorial to get the concept.
PS: for a beginner, I recommend the Base Adapter, it is, to me, the simplest :)
I am showing captured images in one layout using different gridView for each category (Shirts , Trousers e.t.c). The number of the gridViews is 6.
I am trying to select one image from each gridView and via onClick method in the button to show them in another activity but the code i wrote doesn't work.
I suppose something is wrong with the strings.
Can anyone help me to fix this? Thnak you in advance!
public class CreateOutfit extends Activity implements View.OnClickListener {
private DatabaseHandler handler;
GridView grid1;
GridView grid2;
ArrayList<Clothes> clothes = new ArrayList<Clothes>();
GridviewAdapter GridAdapter;
String image1;
String image2;
public static final String ITEM_IMAGE1 = "image1";
public static final String ITEM_IMAGE2 = "image2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clothes_grids);
handler = new DatabaseHandler(getApplicationContext());
grid1 = (GridView) findViewById(R.id.grid1);
grid1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
image1 = String.valueOf(view.findViewById(R.id.cloth_image_grid).getContext().toString());
}
});
fillGrid1();
grid2 = (GridView) findViewById(R.id.grid2);
grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
image2 = String.valueOf(view.findViewById(R.id.cloth_image_grid));
}
});
fillGrid2();
ImageButton btn_in = (ImageButton)findViewById(R.id.btn_insert);
btn_in.setOnClickListener(this);
}
public void fillGrid1() {
clothes = (ArrayList<Clothes>) handler.readGridShirts();
GridAdapter = new GridviewAdapter(this, R.layout.grid_row, clothes);
grid1.setAdapter(GridAdapter);
for (Clothes c : clothes) {
String record = "ID=" + c.getID() + " | Category=" + c.getCategory() + " | " + c.getSize();
Log.d("Record", record);
}
}
public void fillGrid2() {
clothes = (ArrayList<Clothes>) handler.readGridTrousers();
GridAdapter = new GridviewAdapter(this, R.layout.grid_row, clothes);
grid2.setAdapter(GridAdapter);
for (Clothes c : clothes) {
String record = "ID=" + c.getID() + " | Category=" + c.getCategory() + " | " + c.getSize();
Log.d("Record", record);
}
}
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), ViewOutfit.class);
in.putExtra(ITEM_IMAGE1 , image1);
in.putExtra(ITEM_IMAGE2, image1);
startActivity(in);
}
}
public class ViewOutfit extends Activity {
DatabaseHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_outfit);
Intent i = getIntent();
handler = new DatabaseHandler(getApplicationContext());
ImageView im1 = (ImageView) findViewById(R.id.im1);
String image1 = i.getStringExtra("image1");
im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra(image1)));
ImageView im2 = (ImageView) findViewById(R.id.im2);
String image2 = i.getStringExtra("image2");
im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra(image2)));
}
The main problem here is: the string's values which are not getting the image path.
According to this line:
image1 = String.valueOf(view.findViewById(R.id.cloth_image_grid).getContext().toString());
It'll never return the image's path... Did you try to display this value in Logcat? It should display the memory's address of the widget's ImageView, and not the image's path.
You should override Object getItem(int position) in GridView's adapter, get the item's model (known as Clothes) and retrieve its image's path. Thus, the adapter should has this:
public Object getItem(int position) {
return clothes.get(position); // return the item by its position
}
Then, in the class, when you set the listener, it should be as this:
grid1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// retrieve the model's item
Clothes selectedItem = (Clothes) tShirtGridAdapter.getitem(position);
// then, get the image's path and save it
image1 = selectedItem.image_url; // "image_url" is the String path's value in model
}
});
Beside, you saw adapterTShirt in the above code, because you used the same variable of the adapter GridAdapter and you set a new instance of the adapter on this line for both GridViews:
GridAdapter = new GridviewAdapter(this, R.layout.grid_row, clothes);
This might be better to not re-initialize the adapter and display the same for two gridviews. You'd have two variables (two instances) of the adapter as:
GridviewAdapter tShirtsGridAdapter, troussersGridAdapter;
// then
tShirtsGridAdapter = new GridviewAdapter(this, R.layout.grid_row, clothes);
// and
troussersGridAdapter = new GridviewAdapter(this, R.layout.grid_row, clothes);
With this, you will have two separate instances and you can't retrieve the image 's path in click listener from the right clicked item like my snippnet code above.
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 have a listView which loads data from SQLite database and right now I would want to implement an onclicklistener to the list. When users click on the list, it should bring them to the next activity and load the corresponding data into TextView. My question is how would I pass the data of the list for example it is a list of "Topics" and user click on the topic "My Home". I want to pass the topic "My Home" to the next activity so that I know which corresponding data to be retrieved respectively.
How do I go about it? Do I "putExtras" to the new Intent? or there is another way. Below are part of my codes which display the listview:
ListView listContent = (ListView) findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
int[] to = new int[] { R.id.text };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
//Onclick ListView setlistener
listContent.setTextFilterEnabled(true);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
EDITED:
This part is on the next activity.
Intent i = getIntent();
extraTopic = i.getStringExtra("SummTopic");
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic = \" " + extraTopic + " \" " , null);
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
I got an error while retrieving from database:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Please help.
Thank you.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
Cursor c = (Cursor)parent.getItemAtPosition(position);
summaryIntent.putExtra("SummTopic", c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT)));
startActivity(summaryIntent);
}
or you can pass id (summaryIntent.putExtra("SummTopicId", id);) of this row and "ask db" in next Activity for Topic with this id
EDIT:
protected void onCreate(Bundle savedInstanceState){
Intent i = getIntent();
String extraTopic = i.getStringExtra("SummTopic");
//or long extraTopic = i.getLongExtra("SummTopic"); if you put id there (which is better)
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
String[] args = new String[] { extraTopic };
//or String[] args = new String[] { Long.toString(extraTopic) }; with id version
Cursor singleRow = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic=?" , args);
//args is better then escaping special chars in query
//and it should be single row so we've changed var name :)
if(singleRow.moveToFirst()){ //we should do moveToFirst before we can use Cursor
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
//setup views and stuff ....
}else{
Toast.makeText(this, "Oops we did not find topic, detail activity was closed", Toast.LENGTH_SHORT).show();
finish();
}
}
After you have used setContentView(...) you need to reference your String and get the text such as...
EditText et = (EditText) findViewById(R.id.my_edit_text);
String theText = et.getText().toString();
To pass it to another Activity you use an Intent. Example...
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", theText);
startActivity(i);
In the new Activity (in onCreate()), you get the Intent and retrieve the String...
public class MyNewActivity extends Activity {
String uriString;
#Override
protected void onCreate(...) {
...
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
}
}
EDITED :
to get String From Listview you can apply below code and get ITEM String and Pass it to Next Activity:
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ITEM=listContent.getItemAtPosition(position);
//Intent summaryIntent = new Intent(DocumentListActivity.this, // ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
You can use Intent for this.
Intent intent= new Intent(context,classname.class);
intent.putExtra("name",string);
You can get it in the target class name using intent.getextra().
I guess you are using an adapter to fill your list with some data. So you need to override getItem(int position) method in your adapter:
#Override
public Object getItem(int position) {
//Note that return type should be the same you you use to initilise items oof the adapter. E.g. String or some custom Topic class
Object someObject = mObjects[position];
return someObject;
}
Then you need to set an item click listener to you list
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object someObject = adapterView.getItemAtPosition(i);
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", someObject.toString());
startActivity(i);
}
});
ok so i have an array adapted listview (the array adapting is done in another class).. i just got the click listener working for the list but now i want set it up so that when i click an item it pulls the strings from the clicked item and piggybacks them on the intent to a new activity.. i figure im supposed to use intent.putextra however im not sure how to pull the correct strings corresponding to the item that i click on.. my code is below.. im simply lost to be honest
//Initialize the ListView
lstTest = (ListView)findViewById(R.id.lstText);
//Initialize the ArrayList
alrts = new ArrayList<Alerts>();
//Initialize the array adapter notice with the listitems.xml layout
arrayAdapter = new AlertsAdapter(this, R.layout.listitems,alrts);
//Set the above adapter as the adapter for the list
lstTest.setAdapter(arrayAdapter);
//Set the click listener for the list
lstTest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int item, long arg3) {
Intent intent = new Intent(
HomePageActivity.this,
PromotionActivity.class
);
finish();
startActivity(intent);
}
});
my alerts class..
public class Alerts {
public String cityid;
public String promoterid;
public String promoshortcontent;
public String promocontent;
public String promotitle;
public String locationid;
public String cover;
#Override
public String toString() {
return "City: " +cityid+ " Promoter: " +promoterid+ "Short Promotion: " +promoshortcontent+ "Promotion: " +promocontent+ "Title: " +promotitle+ "Location: " +locationid+ "Cover: " +cover+ "$";
}
}
anddddd my alertsadapter class..
public class AlertsAdapter extends ArrayAdapter<Alerts> {
int resource;
String response;
Context context;
//Initialize adapter
public AlertsAdapter(Context context, int resource, List<Alerts> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout alertView;
//Get the current alert object
Alerts al = getItem(position);
//Inflate the view
if(convertView==null)
{
alertView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, alertView, true);
}
else
{
alertView = (LinearLayout) convertView;
}
//Get the text boxes from the listitem.xml file
TextView textPromo =(TextView)alertView.findViewById(R.id.txtPromo);
TextView textPromoter =(TextView)alertView.findViewById(R.id.txtPromoter);
TextView textLocation =(TextView)alertView.findViewById(R.id.txtLocation);
//Assign the appropriate data from our alert object above
textPromo.setText(al.promocontent);
textPromoter.setText(al.promoterid);
textLocation.setText(al.locationid);
return alertView;
}
}
You need to use the onItemClick event's parameters
a full more readable param enum with param name is
(AdapterView<?> parent, View view, int pos, long id)
that means you have the pos param that indicated the position in the adapter.
What you have to do is:
jump to pos in the adapter
read out the values from the adapter
use putExtra to signup for the intent
had an epiphany over the weekend about how to fix this problem and i finally found a good work around for my app.. i know it isnt optimal because i hard coded the number 100 into it but for my uses as of now i know i wont ever have that many list items..
i added these 2 bits of code to my alertsadapter class
int startzero = 0;
public static String[][] promomatrix = new String[6][100];
and
promomatrix[0][startzero] = al.cityid;
promomatrix[1][startzero] = al.promoterid;
promomatrix[2][startzero] = al.promocontent;
promomatrix[3][startzero] = al.promotitle;
promomatrix[4][startzero] = al.locationid;
promomatrix[5][startzero] = al.cover;
startzero++;
then went to my homepageactivity class and added this to the click listener
Intent intent = new Intent(
HomePageActivity.this,PromotionActivity.class);
intent.putExtra("listitemcity", AlertsAdapter.promomatrix[0][pos]);
intent.putExtra("listitempromoter", AlertsAdapter.promomatrix[1][pos]);
intent.putExtra("listitemcontent", AlertsAdapter.promomatrix[2][pos]);
intent.putExtra("listitemtitle", AlertsAdapter.promomatrix[3][pos]);
intent.putExtra("listitemlocation", AlertsAdapter.promomatrix[4][pos]);
intent.putExtra("listitemcover", AlertsAdapter.promomatrix[5][pos]);
finish();
startActivity(intent);
and finally went to my promotionactivity (where i was trying to send the strings) and added this
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
}
String listitemcity = extras.getString("listitemcity");
String listitempromoter = extras.getString("listitempromoter");
String listitemcontent = extras.getString("listitemcontent");
String listitemtitle = extras.getString("listitemtitle");
String listitemlocation = extras.getString("listitemlocation");
String listitemcover = extras.getString("listitemcover");
worked like a charm.. i hope this helps someone :)