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)
{};
});
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 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.
There has a listView and a add button in Activity A. The listView data is retrieved from MySQL.
[![http://i.stack.imgur.com/wVmSK.png][1]][1]
When list is clicked, it will pass the data to Activity B, if add button is clicked, it will go to Activity B for user to add data. I use mClickedPosition to differentiate whether is list clicked or button clicked.
Activity A
ListView listViewUpdate;
ListAdapter adapter;
Button add;
String ID, iD;
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
int mClickedPosition;
String ReceiveProject, ReceiveDescription, ReceiveTimeIn, ReceiveTimeOut;
Integer ReceiveProgress;
ArrayList<DetailsBean> results = new ArrayList<DetailsBean>();
String myJSON;
JSONArray details = null;
ArrayList<HashMap<String, String>> EditDetails;
listViewUpdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position; // listView click
HashMap<String, String> clickedItem = EditDetails.get(position);
iD = clickedItem.get(Configs.TAG_ID);
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("iD", iD);
intent.putExtra("ID", ID);
intent.putExtra("mClickedPosition",mClickedPosition);
//Toast.makeText(getActivity(),"This is"+iD+ID,Toast.LENGTH_LONG).show();
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickedPosition = -1; // if button clicked
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("ID", ID);
startActivity(intent);
}
});
Assume user click add button.(mClickedposition==-1)
Activity B
When save button is clicked, data will get inserted into MySQL since mClickedPosition==-1 After that, I want the new data return to Activity A and adding a new list in A, which mean the Activity A should have 2 list now. How can I achieve this ?
save.setOnClickListener(new View.OnClickListener() { // if save button clicked
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
project1 = Project2.getSelectedItem().toString();
description = Description.getText().toString();
progress = seekBar.getProgress();
timeIn = TimeIn.getText().toString();
timeOut = TimeOut.getText().toString();
if(mClickedPosition==-1)
{
Add(project1,description,progress,timeIn,timeOut);
}
else
{
Update(project1, description, progress, timeIn, timeOut);
}
returnIntent.putExtra("project1", project1);
returnIntent.putExtra("description", description);
returnIntent.putExtra("progress", progress);
returnIntent.putExtra("timeIn", timeIn);
returnIntent.putExtra("timeOut", timeOut);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
Toast.makeText(getActivity(),ReceiveProject+ReceiveDescription+ReceiveProgress+ReceiveTimeIn+ReceiveTimeOut,Toast.LENGTH_LONG).show();
if(mClickedPosition==-1)
{ // add list
HashMap<String, String> clickedItem = new HashMap<>();
clickedItem.put(Configs.TAG_PROJECT, ReceiveProject);
clickedItem.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
clickedItem.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
clickedItem.put(Configs.TAG_IN, ReceiveTimeIn);
clickedItem.put(Configs.TAG_OUT, ReceiveTimeOut);
EditDetails.add(clickedItem);
((BaseAdapter) adapter).notifyDataSetChanged();
}
else
{ // update list
HashMap<String, String> clickedItem =EditDetails.get(mClickedPosition);
clickedItem.put(Configs.TAG_PROJECT, ReceiveProject);
clickedItem.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
clickedItem.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
clickedItem.put(Configs.TAG_IN, ReceiveTimeIn);
clickedItem.put(Configs.TAG_OUT, ReceiveTimeOut);
((BaseAdapter) adapter).notifyDataSetChanged();
}
//((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
}
Now I can see a new list added in Activity A. But when I click the new
list and go to Activity B, no data are passed. But if I click the old
list, I can see data passed...
You need add or update the new data in the List and then call notifiDataSetChanged();
Change the code in the onActivity result method of your activity A as below-
HashMap<String, String> item = new HashMap<>();
item.put(Configs.TAG_PROJECT, ReceiveProject);
item.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
item.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
item.put(Configs.TAG_IN, ReceiveTimeIn);
item.put(Configs.TAG_OUT, ReceiveTimeOut);
if(mClickedPosition==-1)
{ // add list
EditDetails.add(item);
}
else
{ // update list
EditDetails.remove(mClickedPosition);
mEventsList.add(mClickedPosition,item)
}
((BaseAdapter) adapter).notifyDataSetChanged();
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 :)