I have a listview which when clicked on listitem opens a new singleitenview activity
The singleitenm view consists of a button which is used to add the corresponding listitem to favorites activity(if not yet added) and changes the button color to yellow indicating it is added to favoorites or else gray if not in favorites
Till here everything works fine but if i close the singleitemview and reopen it the button color changes back to previous color but still in facvorites
What shall i do to the button color not getting changed
favbtn of singleitemview activity
final Button btn = (Button) findViewById(R.id.singleitemButton1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
products=new ArrayList<Product>();
Bundle extras = getIntent().getExtras();
String jsonObj = extras.getString("selected item");
ObjectMapper mapper = new ObjectMapper();
try
{
Product pro = mapper.readValue(jsonObj, Product.class);
if (checkFavoriteItem(pro)) {
sharedPreference.removeFavorite(SingleItemView.this, pro);
btn.setBackgroundColor(Color.GRAY);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.addFavorite(SingleItemView.this, pro);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(Color.YELLOW);
}
}
catch (IOException e)
{};
});
onitemclick of my list activity
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ObjectMapper mapper = new ObjectMapper();
Product pro = productListAdapter.getItem(position);
String favimg = ((ImageView) view.findViewById(R.id.imgbtn_favorite)).toString();
try
{
String hi = "this is testint";
String jsonInString = mapper.writeValueAsString(pro);
Intent intent = new Intent(activity.getApplicationContext(), SingleItemView.class);
intent.putExtra("selected item", jsonInString);
;
startActivityForResult(intent, 1);
// startActivity(intent);
}
catch (JsonProcessingException e)
{}
}
In the onCreate() method of your singleitemview activity, after you inflate the view that has the favorite button, you simply need to check if the item is in favorites and set the button's background color accordingly.
Related
I have a listview which when clicked on listitem opens a new singleitenview activity
The singleitenm view consists of a button which is used to add the corresponding listitem to favorites activity(if not yet added) and changes the button color to yellow indicating it is added to favoorites or else gray if not in favorites
Till here everything works fine but if i close the singleitemview and reopen it the button color changes back to previous color but still in facvorites
What shall i do to retain the button color
onitemclick of my list activity
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ObjectMapper mapper = new ObjectMapper();
Product pro = productListAdapter.getItem(position);
String favimg = ((ImageView) view.findViewById(R.id.imgbtn_favorite)).toString();
try
{
String hi = "this is testint";
String jsonInString = mapper.writeValueAsString(pro);
Intent intent = new Intent(activity.getApplicationContext(), SingleItemView.class);
intent.putExtra("selected item", jsonInString);
;
startActivityForResult(intent, 1);
// startActivity(intent);
}
catch (JsonProcessingException e)
{}
}
favbtn of singleitemview activity
final Button btn = (Button) findViewById(R.id.singleitemButton1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
products=new ArrayList<Product>();
Bundle extras = getIntent().getExtras();
String jsonObj = extras.getString("selected item");
ObjectMapper mapper = new ObjectMapper();
try
{
Product pro = mapper.readValue(jsonObj, Product.class);
if (checkFavoriteItem(pro)) {
sharedPreference.removeFavorite(SingleItemView.this, pro);
btn.setBackgroundColor(Color.GRAY);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.addFavorite(SingleItemView.this, pro);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(Color.YELLOW);
}
}
catch (IOException e)
{};
});
Android newbie here.
The scenario
I am using my website's api to populate data for Android ListView
for the first screen it is called GameFragment. Game fragment loads the games from my website url
I was able to successfully list all games. So my next step would be to show all articles related to the game when user clicks on the game. Using my websites api http://www.gamerzwiki.com/api/news.json?game_id=qwert133 (whatever the id of the item is)
Loading Contents from url
try {
JSONArray games = gp.loadGamesFromApi();
ArrayList<Games> listData = new ArrayList<Games>();
if(games != null){
for(int x = 0 ; x<games.length() ; x++){
JSONObject game = games.getJSONObject(x);
try {
Games game1 = new Games();
game1.title=game.getString("title");
game1.id = game.getInt("id");
listData.add(game1);
//free game 1
game1 = null;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ArrayAdapter<Games> adapter = new ArrayAdapter<Games>(getActivity(),android.R.layout.simple_list_item_1, listData);
setListAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
so I have a listener
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Object item = l.getSelectedItem();
Toast.makeText((Context)getActivity(),item.title.toString() , Toast.LENGTH_LONG).show();
Intent intent = new Intent(v.getContext(), NewsActivity.class);
startActivity(intent);
}
but it seems I can't get the attribute of the item
but I don't know how I can do that on my ListView. So I would like to ask your expert advise
what you can do is implement onClick listener on your listview which has all the games:-
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Games game = adapter.getItem(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
intent.putExtra("id",game.id);
startActivity(intent);
}
});
in your other activity retrieve this as:-
String id=getIntent.getStringExtra("id");
and now you can use this id to make webservice call in your activity,here ItemClicked is your model class which your are using to populate your listview with your all games
You can pass data between activities by using putExtra in the intent
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Games item = adapter.getItem(position);
Intent intent = new Intent(v.getContext(), NewsActivity.class);
intent.putExtra("id", item.id);
startActivity(intent);
}
In your receiving activity do this
String id = getIntent().getStringExtra("id");
You can pass basic datatypes through putExtra. If you want to pass custom objects you'll have to implement Parcelable http://developer.android.com/reference/android/os/Parcelable.html
I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");
I am trying to set the text of an EditText via a ListView. Once the user chooses a product from the ListView, it will then go back to the activity that holds the EditText, and change the text within the EditText.
I am relatively new to Android and Java, so excuse me for being an absolute nub.
List Java:
final ListView listViewCPU = (ListView) findViewById(R.id.listViewCPU);
listViewCPU.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
String CPUList[] = {
"Products go here", "Products go here", "Products go here", "Products go here", "Products go here", "Products go here" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, CPUList);
listViewCPU.setAdapter(adapter);
listViewCPU.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View myView,
int pos, long mylng) {
String CPU = (String) listview.getAdapter().getItem(pos);
Intent i = new Intent(getApplicationContext(), ListmenuActivity.class);
i.putExtra(" ", CPU);
startActivity(i);
}
});
}
}
EditText Java:
I am getting the error on "EditText4" defining "Syntax error on token "EditText4", delete this token"
EditText CPU = (EditText) findViewById(R.id.autoCompleteTextView4);
CPU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent CPUList = new Intent(getApplicationContext(),
CPUList.class);
startActivityForResult(CPUList, 0);
}
Intent i = getIntent();
String product = i.getStringExtra(" ");
EditText CPU = ((EditText)findViewById(R.id.EditText4));
EditText4.setText(getIntent(i).getStringExtra(""));
});
Should be CPU.setText not EditText4 as you dont really have that defined (as long as I can see)
you set this way
#Override
public void onItemClick(AdapterView<?> listview, View myView,
int pos, long mylng) {
String CPU = (String) listview.getAdapter().getItem(pos);
Intent i = new Intent(getApplicationContext(), ListmenuActivity.class);
i.putExtra("key", CPU);
startActivity(i);
}
});
get the value like that
Intent i = getIntent();
String product = i.getStringExtra("key");
EditText CPU = ((EditText)findViewById(R.id.EditText4));
CPU.setText(product);
EditText CPU = ((EditText)findViewById(R.id.EditText4));
You are mising a semicolon on this line :)
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;
}
}