How to launch new view with the clicked argument? - android

I am new to android development - what I am not familiar with is how to send the user to a new view and include an argument (such as an item object) along with it. I would like to teach myself but I'm not quite sure what I am looking for. I think I need to send an intent to create a new view. In the overloaded "onItemClick" function you can see comments specifying exactly where I need to add code - this is the part I am not sure how to proceed on. Thanks for all help!
public class RoomActivity extends Activity {
GlobalClass globalClass;
TextView roomName;
TextView roomDescription;
Room thisRoom;
Button north;
Button south;
Button east;
Button west;
// this list view holds the options available in the room, each option is clickable and should
// bring up it's own subview
ListView listy;
// adaptor used to bind a string array of options to the list view
ArrayAdapter la;
/**
* Populates the main list view with the contents of list
* #param list an array of strings that are put into the list view
*/
public void populateList (int listID, ArrayList<String> list){
listy = (ListView) findViewById(listID);
la = new ArrayAdapter(this.getBaseContext(), R.layout.list_item, R.id.list_item_text, list.toArray());
listy.setAdapter(la);
listy.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Item item = thisRoom.getItem(position);
// Verified that the item object is correctly populated.
// Send "item" as argument to the "activity_item" layout
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
globalClass = (GlobalClass) getApplicationContext();
if(thisRoom == null)
thisRoom = globalClass.getRoom(1);
roomName = (TextView) findViewById(R.id.room_name);
roomDescription = (TextView) findViewById(R.id.room_description);
north = (Button) findViewById(R.id.north_button);
south = (Button) findViewById(R.id.south_button);
east = (Button) findViewById(R.id.east_button);
west = (Button) findViewById(R.id.west_button);
setRoomView();
}
public void setRoomView () {
roomName.setText(thisRoom.getName());
roomDescription.setText(thisRoom.getDescription());
populateList(R.id.character_list, globalClass.getCharacterNames((thisRoom.getCharacters())));
populateList(R.id.item_list, globalClass.getItemNames(thisRoom.getItems()));
}
public void onClickMove (View view) {
Button button = (Button) view;
switch (button.getId()){
case (R.id.north_button):
if (thisRoom.northRoomId != 0){
thisRoom = globalClass.getRoom(thisRoom.northRoomId);
setRoomView();
}
break;
case (R.id.south_button):
if (thisRoom.southRoomId != 0){
thisRoom = globalClass.getRoom(thisRoom.southRoomId);
setRoomView();
}
break;
case (R.id.east_button):
if (thisRoom.eastRoomId != 0){
thisRoom = globalClass.getRoom(thisRoom.eastRoomId);
setRoomView();
}
break;
case (R.id.west_button):
if (thisRoom.westRoomId != 0){
thisRoom = globalClass.getRoom(thisRoom.westRoomId);
setRoomView();
}
break;
}
}
}

at your onItemClick()
Intent intent = new Intent(RoomActivity.this, ItemActivity.class);
String extra = "YOUR PASSED DATA";
intent.putExtra(EXTRA, extra);
startActivty();
at the RoomActivity class
public static final String EXTRA = "MY_EXTRA";
at ItemActivity.onCreate()
String item = getIntent().getStringExtra(RoomActivity.EXTRA);
I don't know if the Item class is Serializable or not, but in case it not: use Gson library to serialize/deserialize your Item object. It's easy to use; just read their guide.
At any case, I don't recommend this way of serializing and deserializing, you may extract the important fields (indeed primitives) from your Item at the RoomActivity and pass them using the Intent; and in the ItemActivity, just re-construct the Item.

Add this where you want to pass your data:
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra("MyData1", obj);
Add this where you want to retrieve you data:
getIntent().getSerializableExtra("MyData1");
Anyway, there's a good explanation on the official page on Android Developers here: http://developer.android.com/training/basics/firstapp/starting-activity.html

So here you go starting new Activity (view):
Intent i = new Intent(this, AnotherViewActivity.class);
i.putExtra("ExampleString", "Hello")
startActivity(i);
Getting sent data in the activity:
String data = getIntent().getExtras().getString("ExampleString");

Related

Pass Values to ListView by Clicking a Button

I want to pass values to list view by clicking a button. Problem is I want to make a list by gaining values from different activities with several buttons.
For Example :
In EnglandActivity if I click Button Visit I want to pass "England" to ListView in MainActivity,
In MalaysiaActivity pass "Malaysia" to ListView in MainActivity.
I dont know how to do that, Can you help me??
First Of All, You should write this on your onCreate() method of MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data;/*For Storing Country Name*/
ListView listview = (ListView)findViewById(R.id.listView); /*Finding ListView From Layout*/
ArrayList<String> list = new ArrayList<String>(); /*ArrayList To Store All The Data Of ListView*/
ArrayAdapter adapter= new ArrayAdapter<String>(this,R.layout.android.R.layout.simple_list_item_1,list);/*Defining ArrayAdapter For ListView*/
listview.setAdapter(adapter); /*Setting Adapter To ListView*/
Bundle intentExtras = getIntent().getExtras(); /*Getting The Intent Extras Sent By The Activity Which You Had Navigated From*/
if(intentExtras != null) {/*Checking For Null*/
data= intentExtras.getString("countryName");/*Extracting The Data From The Intent Extras*/
list.add(0,data);/*You Can Replace 0 With The Position Of Your Wish*/
} else {
data=null;
}
}
Now Write This In The OnClickListener() Method Of Button On Each CountryNameActivity.java
btn.setOnClickListener(new OnClickListener() {/*Setting The Click Listener*/
#Override
public void onClick(View v) {
Intent intent = new Intent(this,MainActivity.this)/*Defining The Intent*/
intent.putExtra("countryName","CountryName");/*Putting The Data To Pass To The Next Activity*/
startActivity(intent);/*Starting The Activity*/
}
});
Make an object shared by all of your activity, put your data there and read them when you must put data into your ListView's adapter
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent listIntent = new Intent(getApplicationContext(), YourActivity.class);
listIntent.putExtra("country", yourList.get(position));
startActivity(listIntent);
}
});
in next activity onCreate:
String country;
Bundle extras = getIntent().getExtras();
if(extras == null) {
country= null;
} else {
country= extras.getString("country");
}

How to access a TextView located in a Table Layout

I made a TableLayout 3x3 in "Activity A"(Chose a Table Layout, because I thought it suits my needs)
7 of the 9 cells are clickable and open "Activity B" which is a custom number picker I made.
I used an intent to pass an array and other data to activiy B
The idea of my number picker is to set a value in the cell I just clicked in Activiy A(I wanted something like the calendarDatePicker)
In "Activity B" I have a method to update the values from "Activity A" and finish() "Activity B" when an image View is clicked wich works very fine except that it does not set the value for the clicked Text View
How can I set the TextValue from another activity when the TextValue is contained in a Table Layout?
I don't use intent, because honestly I don't know how to handle it when the "Activity B" is closed.
I mean where in "Activity A" should I handle this intent from "Activity B"
Using the debugger I found out that trying to set the text using the TextView Id does not works as it shows a "null" object in the debugger.
Activiy A
package com.example.racu.threebythree;
public class threebythree extends AppCompatActivity {
public static ArrayList<Integer> ColumnA = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnB = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnC = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_by_three);
for (int i = 1; i < 28; i++) {
if (i > 0 && i < 10)
ColumnA.add(i);
if (i > 10 && i < 19)
ColumnB.add(i);
if (i > 19 && i < 28)
ColumnC.add(i);
}
}
public void openNumberPicker(View v) {
// I used this to "guess" the location of the cell in the table layout as I could not find a way to do it.
String cellName = v.getResources().getResourceName(v.getId());
String cellLetter = cellName.substring(cellName.lastIndexOf("/") + 1);
// Send intent
Intent intent = new Intent(this, NumberPicker.class);
intent.putExtra("Id", (cellLetter.substring(0, 1) + cellLetter.substring(2)).toUpperCase());
switch (cellLetter.substring(0, 1)) {
case ("a"):
intent.putIntegerArrayListExtra("Column", ColumnA);
break;
case ("b"):
intent.putIntegerArrayListExtra("Column", ColumnB);
break;
case ("c"):
intent.putIntegerArrayListExtra("Column", ColumnC);
break;
}
intent.putExtra("Cell ID", v.getId());
startActivity(intent);
}
}
Avtivity B
package com.example.racu.threebythree;
public class NumberPicker extends AppCompatActivity {
GridView numberPicker;
ArrayList<Integer> numbersToDisplay;
TextView viewToDisplay;
ImageView ok, cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_picker);
numberPicker = (GridView) findViewById(R.id.arrayNumbers);
viewToDisplay = (TextView) findViewById(R.id.number_to_select);
ok = (ImageView) findViewById(R.id.add_number_to_card);
ok.setClickable(false);
Intent intent = getIntent();
String idFromIntent = intent.getStringExtra("Id");
numbersToDisplay = intent.getIntegerArrayListExtra("Letter");
TextView numberPosition = (TextView) findViewById(R.id.numberPosition);
numberPosition.setText(idFromIntent);
final TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, R.layout.number_for_picker, numbersToDisplay);
numberPicker.setAdapter(adapter);
numberPicker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
chosenNumber.setText(((TextView) v).getText());
ok.setImageResource(R.drawable.ok_blue);
ok.setClickable(true);
}
});
}
public void updateThreByThree(View v) {
Intent intent = getIntent();
int currentCell = intent.getIntExtra("Cell ID", 0);
String idFromIntent = intent.getStringExtra("Id").substring(0, 1);
TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
// Here I try to Set the text to the cell in Activity A, using its R.id, but in the debugger I get a null reference, therefore my app crashes
TextView currentCellToEdit = (TextView) findViewById(currentCell);
currentCellToEdit.setText(chosenNumber.getText());
int temp = Integer.parseInt(chosenNumber.getText().toString());
switch (idFromIntent) {
case "A":
threebythree.ColumnA.remove(Integer.valueOf(temp));
break;
case "B":
threebythree.ColumnB.remove(Integer.valueOf(temp));
break;
case "C":
threebythree.ColumnC.remove(Integer.valueOf(temp));
break;
}
finish();
}
public void cancel(View view) {
finish();
}
}
Thanks to Pavan for the hint I found two more very helpful post here and this one was EXACTLY what I was looking for.
Like that ( make sure you give the TableLayout an id ):
TableLayout tl = (TableLayout)findViewById( R.id.tableLayout );
TextView tv = (TextView)tl.findViewById( R.id.textView );

passing data from custom adapter to another activity

I have a listview which consist of items with prices. My listview also has a Delete button. I also have a textview at the bottom part of the layout which is not part of the listview and it shows the total amount. I can successfully remove the item from my listview. What I want is that when the item is removed, the total amount will also change.
Here is a part of my adapter where i must do some actions
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(getItem(position));
}
});
and here is my Activity where my textview of amount is found.
public class Cart extends MainActivity {
TextView amount_total;
ListView cartList;
CartCustomAdapter cartCustomAdapter;
String name, price;
static ArrayList<Order> cartArray = new ArrayList<Order>();
static Double total_amount = 0.00d;
static Double temp = 0.00d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
amount_total = (TextView) findViewById(R.id.total_tv);
Bundle bundle = getIntent().getExtras();
Button checkout = (Button) findViewById(R.id.check_out);
Button add_item = (Button) findViewById(R.id.add_item);
name = bundle.getString("i_name");
price = bundle.getString("i_price");
temp = Double.parseDouble(price);
total_amount = (total_amount + temp);
amount_total.setText("Php" + total_amount.toString());
add_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cart.this,MainActivity.class);
startActivity(intent);
}
});
cartList = (ListView) findViewById(R.id.cart_list);
cartCustomAdapter = new CartCustomAdapter(Cart.this,R.layout.list_cart,cartArray);
cartList.setItemsCanFocus(false);
cartList.setAdapter(cartCustomAdapter);
cartArray.add(new Order(name,price,"1"));
cartCustomAdapter.notifyDataSetChanged();
}
}
Define an interface with method like below to update text view in your activity :
updateDeletedItemCount();
and in this method take integer and increase its count like
deletedCount++;
and then update it on text view like this
tvDeletedCount.setText("Deleted Item Count : "+ deletedCount);
This is the easiest way to do that:
//Add a method to your Cart
public void changeTotal(int totalPrice){
if(textView != null) // set total price
}
// Call after remove an item in your listener:
if(getContext() instanceOf Cart){
((Cart)getContext()).changeTotal(newTotalPrice);
}
This is not the best way, but I think it's ok for now :)

How do I pass an integer to an instance of a class and use it to call the method of another class?

here's activity 1 which is a listview. when the user clicks on an item, I want the item clicked to launch an instance of a class and pass an int value to it, which will later be used in a switch.
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
switch(position){
case 0:
Intent g = new Intent(books.this, SpecificBook.class);
Bundle b = new Bundle();
b.putInt("dt", 0);
g.putExtras(b);
books.this.startActivity(g);
break;
case 1:
Intent ex = new Intent(books.this, SpecificBook.class);
Bundle b1 = new Bundle();
b1.putInt("dt", 1);
ex.putExtras(b1);
books.this.startActivity(ex);
break;
//etc.
here's activity 2, which is supposed to retrieve the int value and call the appropriate method from the database helper class.
public class SpecificBook extends Activity {
private DatabaseHelper Adapter;
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
int dt = myBundle.getInt("dt");
#SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listy);
ListView lv = (ListView)findViewById(R.id.listview);
Adapter = new DatabaseHelper(this);
Adapter.open();
Cursor cursor = null;
switch(dt){
case 0:cursor = DatabaseHelper.getbook1Data(); break;
case 1:cursor = DatabaseHelper.getbook2Data(); break;
//etc.
}
startManagingCursor(cursor);
etc.
The database methods are queries.
Basically, I want each item in the book class listview to run it's own query based on the item selected and display the results.
I get a "source not found" and runtimeexception error. where am i going wrong? is there a better way to go about this?
I have already tried the "getter and setter" way to no avail. I've also tried the "putextra" method on the instance of the intent but that didn't work.
The earliest you can access an Intent is in onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listy);
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
int dt = myBundle.getInt("dt");
You should check if the Intent or Bundle is null and if you only want the one item from your Intent you can use:
Intent myLocalIntent = getIntent();
if(myLocalIntent != null) {
int dt = myLocalIntent.getIntExtra("dt", -1); // -1 is an arbitrary default value
}
Lastly, you don't need to create a new Bundle to pass values in an Intent and it looks like you simply want to pass the position... So you can drastically shorten your onItemClick() method:
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent g = new Intent(books.this, SpecificBook.class);
g.putInt("dt", position);
books.this.startActivity(g);
}

putExtra from List into SMS body

I'm trying to put the contents of List mCartList; into a the sms_body below, eg: Cheeseburger, Hamburger, Fries (so it can be sent through sms). I can pass a string so I know it works. I'm not a programmer at all and it's been a month of me doing trial & error.
Below the activity calls the contents of mCartList into a List so they can be removed. Tell me whatever else you need to help me solve this. Thank you in advance.
private ProductAdapter mProductAdapter;
// This List into the order button below
private List<Product> mCartList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCart();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
}
});
Button orderButton = (Button) findViewById(R.id.orderButton);
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
// The above List<Product> mCartList ia displayed in the window of the app
intent.putExtra("sms_body", "mCartList"); // I want the results of List<Product> mCartList to go here - I can not just insert the variable I just get errors and can't compile
startActivity(intent);
}
});
Button removeButton = (Button) findViewById(R.id.ButtonRemoveFromCart);
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
}
}
mProductAdapter.notifyDataSetChanged();
}
});
}
Here is how this works. It's a 4 tab list with different items in each tab, 3 of which or products. Customer clicks on the item and they see a description, click add to cart, then your back at the menu. The 4th tab is a the order of what was just selected that is to populate the sms body. I have been able to pass a variable with the text "Hello World". I'm figuring the result of List mCartList can populate the sms body. I'm assuming the List can not just be inserted into the body of a forn without being converter. Let me know if you need anymore info. I'm not a programmer, I have seen similar but nothing that doesn't work without writing other files I got from a tutorial. Thank you in advance.
If all the products are added to your mCartList, it's just a matter of concatenating the String output of the Products together as follows:
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
StringBuilder builder = new StringBuilder();
for(Product p : mCartList){
builder.append(p.toString());
builder.append('\n');
}
intent.putExtra("sms_body", builder.toString());
startActivity(intent);
}
});
make sure your Product has a toString() method defined as follows (example Product guess):
public class Product{
String productName;
public String toString(){
return productName;
}
}

Categories

Resources