putExtra from List into SMS body - android

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;
}
}

Related

Saving list data composed of individual buttons

I've made a list made of TextViews and Buttons, made that when a person clicks on a button, a fragment opens and there is a list of values he can select. The problem is when i press on another button to select a value again for a different field, the previous value disappears. So the question would be how to save the fragments values, and keep it saved until the app is closed ?
priceButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
PriceFragment priceFragment = new PriceFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, priceFragment).commit();
setToHideElements();
}
});
yearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
YearFragment yearFragment = new YearFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, yearFragment).commit();
setToHideElements();
}
});
this is the year fragment
yearEndListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getBaseContext(), MainMenuActivity.class);
String yearTo = yearList[i].toString();
int yearTint = Integer.valueOf(yearTo);
if (combinedYear != null) {
combinedYear = combinedYear + " " + yearTo;
intent.putExtra("Years", combinedYear);
getActivity().startActivity(intent);
} else {
combinedYear = null;
combinedYear = yearTo;
}
}
});
this is the method to retrive data
private void retriveDataFromFragment(){
Intent intent = getIntent();
String fragmentDataPrice = intent.getStringExtra("PriceData");
String fragmentDataYear = intent.getStringExtra("Years");
if(fragmentDataPrice != null){
priceButton.setText(fragmentDataPrice);
} else {}
if (fragmentDataYear != null){
yearButton.setText(fragmentDataYear);
} else {}
}
I use RetriveDataFromFragment method in OnResume method.
Thank you, for your time.
you are initiating every time a new fragment so it will never retain its state. you have to use listener while closing the fragment so you can get back your data.
I got the anwser if someone else needs a similar menu, all you have to do is create a class that extends Application, and include into your manifest (the part with application tags). From there you just use getters and setters and all is well.

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 :)

Setting On Click Listener For A Dynamic ListView

thanks for always being available...
I have been able to populate my ListView with information i have in the database.
Now, I want setOnClickListener for the items to go to different pages. Currently, I am using a "switch(position)" construct, but it doesn't function appropriately since I can't hard code how many items would be on the ListView.
Please, kindly help me out on this one.
public class SurveyActivity extends AppCompatActivity {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db;
DatabaseHelper helper = new DatabaseHelper(this);
String listItem = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Add new survey", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
PopupMenu pop = new PopupMenu(SurveyActivity.this, fab);
pop.getMenuInflater().inflate(R.menu.addsurvey_menu, pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "Your choice is to " + item.getTitle().toString().toUpperCase() + " a survey form", Toast.LENGTH_LONG).show();
switch (item.getItemId()) {
case R.id.c:
//Takes admin to page where survey is created
Intent i = new Intent(getApplicationContext(), CreateSurvey.class);
startActivity(i);
case R.id.d:
//gets ready created XML forms from server
case R.id.r:
//refreshes and updates survey list from db
}
return true;
}
});
pop.show();
}
});
db = helper.getReadableDatabase();
//Cursor crs = db.rawQuery("SELECT * FROM tbNames", null);
Cursor crs=db.query("tbNames",new String[]{ "names"},null,null,null,null,null);
if(crs.moveToFirst()){
do {
listItem =crs.getString(0);
list.add(listItem);
}while(crs.moveToNext());
}
ListView surveyList = (ListView) findViewById(R.id.surveylist);
ArrayAdapter<String> aAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
surveyList.setAdapter(aAdapter);
registerForContextMenu(surveyList);
surveyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(getApplicationContext(), hivActivity.class);
startActivity(i);
break;
case 1:
Intent intent = new Intent(SurveyActivity.this, CreatedSurveyActivity.class);
startActivity(intent);
}
}
});
}
}
My app would allow users create multiple surveys which would show up in the LIstView.
The problem is how to set Listeners for the items dynamically too.
You can try this code
surveyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i = new Intent(getApplicationContext(), hivActivity.class);
startActivity(i);
} else {
Intent intent = new Intent(SurveyActivity.this, CreatedSurveyActivity.class);
startActivity(intent);
}
}
});
First item will call hivActivity and all other items will call CreatedSurveyActivity. If you need to pass something to the CreatedSurveyActivity put it into the intent, like this intent.putExtra("position" position);
Maybe use setOnItemClickListener()
Posting your code would be helpful, however an approach that can often help in similar situations is:
Set a tag on each view, as you generate it. For example, the item ID, or just an incrementer.
The onClickListener will receive the view as a parameter. The tag can then be retrieved from it.
This tag can then be matched to page names, page URLs, or any other information you're trying to load.

How to launch new view with the clicked argument?

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");

How to pass values statically from one page to other in android?

In my projects I kept different images for categories. When I click on each category image I am passing its category id to other page statically and setting the drawable image of that category in the new page.
My Code:
Firstpage.java
public static String categoryid;
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="0";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="1";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="2";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
Nextpage.java
public static String catid = Firstpage.categoryid;
ImageView categorytype=(ImageView)findViewById(R.id.imageView1);
if(catid=="0")
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid=="1")
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid=="2")
{
categorytype.setBackgroundResource(R.drawable.image3);
}
First time when I am clicking on the category image it is passing the category id to the next page and that particular image is setting in the nextpage. After that I clicked the back button(android back button) and went to Firstpage.java and again clicked on other image. But this time also the same image stored. The category id didnt changed. The category id is not refreshing...How to refresh the category id? Any suggestion will be thankful.....
You are comparing two strings by == operator, instead you should compare by equals method, try following:
if(catid.equals("0"))
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid.equals("1"))
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid.equals(2"))
{
categorytype.setBackgroundResource(R.drawable.image3);
}
Don't use static variables for this. Pass the category ID to your Nextpage activity through the intent. In Firstpage.java:
public static final String CATEGORY_KEY = "category";
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(this,Nextpage.class);
myIntent.putExtra(CATEGORY_KEY, "0");
startActivityForResult(myIntent, 0);
}
});
Then retrieve it in the onCreate(Bundle) method of Nextpage.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String categoryid = intent.getStringExtra(Firstpage.CATEGORY_KEY);
. . .
}
The reason your method doesn't work is that Nextpage.catid is initialized when the class is loaded, but the assignment statement is not executed again unless the class is unloaded and needs to be reloaded.
I think problem is here you are comparing String values using this if(catid=="0") Which you should be compare it using if(catid.trim().equals("0"))
Update this change in your code and check it.

Categories

Resources