Pass Values to ListView by Clicking a Button - android

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

Related

How to Pass the Data from Listview A to ListView B?

I have my Cart Activity which contains the items that the user wanted to purchase.
What I want is if I click the "CHECK OUT" button, all of the data in the cart will be sent to the next Activity having ListView B.
Here is a part of my CartCustomerAdpater.class where i set the textview fields
final Order data = items.get(position);
holder.cart_name.setText(data.getName());
holder.cart_price.setText("Php "+data.getPrice());
holder.cart_qty.setText(data.getQty());
Here is a part of my Cart.class where my CHECK OUT button is located.
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT SHOULD I DO HERE?
}
});
Suppose you declared your ListView:
ListView lv =(ListView) findViewById(R.id.lv);
For the case of a listView use setOnItemClickListener() , this is my sample code for sending data to the next Activity.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ModelClass jhild = (ModelClass) adapter.getItem(position);
Intent in = new Intent(getApplicationContext(), BuyApartmentsInformation.class);
in.putExtra(KEY_DISTRICT_NAME, jhild.getDistrict());
in.putExtra(KEY_FLOORS, jhild.getFloors());
in.putExtra(KEY_AREA, jhild.getArea());
in.putExtra(KEY_BUYLAND_CODE, jhild.getBuyno());
in.putExtra(KEY_PRICES, jhild.getPrice());
in.putExtra(KEY_INFORMATION, jhild.getInformation());
startActivity(in);
}
});
But my piece of Advice you have to update to RecyclerView
Hope it works well.
use intent
send
Intent intent = new Intent(A.this, B.class);
intent.putextra("keyName","value");
startActivity(intent);
recieve
String data = getIntent().getExtras().getString("keyName");
1. You need to implement Serializable or Parcelable in your **Order.java** class so that you can pass the ArrayList of Order through Bundle or Intent .
public class Order implements Serializable{
}
2. Pass the list of items through intent and start new activity
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newActivity = new Intent(this , NewActivity.class);
newActivity.putExtra("orderList" , items);
startActivity(newActivity);
}
});
3. Get the list in NewActivity class
List<Order> itemsList = (List<Order>)getIntent.getSerializableExtra("orderList");
Hope it helps!

get user inputs from an editText and populate listView

How can i get user inputs from one activity and populate the listView with user data in another activity. I am able to get user input and populate the listView in the same activity. but now i want to get user inputs in one form and populate the list in another activity.
the code that i used to populate the listView by getting user input is as follows
public class MainActivity extends ListActivity {
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
String name=edit.getText().toString();
list.add(name);
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
you can store your user input / data into a local database; that will allow you to access your data anywhere in the app
(recommended since you are dealing with listview).
you can use shared preferences to store data if your data is relatively small.
In your current Activity (activity contains your button), create a new Intent:
String name = "";
name = edit.getText().toString();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("keyword",name);
startActivity(i);
Then in the NewActivity (activity contains your Listview), retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String name = extras.getString("keyword");
if(name != ""){
// adapter.notifyDataSetChanged();
}
}
It is simple way, hope this help
Declare a public method in second Activity like
SecondActivity.class
public static ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter
onCreate()
{
...
;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
...
}
public static void ModifyList()
{
adapter.notifyDataSetChanged();
}
FirstActivity.class
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
String name=edit.getText().toString();
SecondActivity.list.add(name);
edit.setText("");
SecondActivity.ModifyList();
}
};
Send your ArrayList like this from FirstActivity :
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("Datalist",list);
startActivity(intent);
In secondActivity Recieve the list using :
Intent i = getIntent();
list = i.getStringArrayListExtra("Datalist");
Then display it in your SecondActivitys listview

Android Passing values from one activity to other activity (string) or from one class to another

I have two class Profile.class and Details.class,
In profile class i have used a spinner with values like (ATM,Banking,Personal,Others etc)
and a button (OK).
on clicking ok button it will go to next activity that is details activity where i will be taking some details like-name,description etc.
after filling the details i have given a button (save).
on clicking button save i will be saving the name and description in database but i want to save the profile name also along with details. i am unable to transfer selected spinner text from Profile.class to Details.class
how to transfer?
create.class code
public class Create extends Activity {
public ArrayList<String> array_spinner;
Button button4;
String spinnertext;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
array_spinner=new ArrayList<String>();
array_spinner.add("ATM");
array_spinner.add("Bank");
array_spinner.add("Mail");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, array_spinner);
adapter.setNotifyOnChange(true);
spinner.setAdapter(adapter);
spinner.setLongClickable(true);
spinner.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}}
);
button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent4 = new Intent(view.getContext(), Details.class);
startActivityForResult(myIntent4, 0);
myIntent4 .putExtra("key", array_spinner.getSelectedItem().toString());
startActivity(myIntent4);
}
});
}}
details.class code
public class Details extends Activity {
EditText editText4,editText5,editText6;
Button button8,button9,button10;
TextView textView7;
String et4,et5,et6;
//SQLite Database db;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
String spinnervalue = getIntent().getExtras().getString("Key");
please kindly explain me what is this "key"?
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", yourData.getText().toString());
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
example
this is what you have to write in your first activity
Intent i = new Intent(getApplicationContext(), Product.class);
i.putExtra("productname", ori);
i.putExtra("productcost", position);
i.startActivityForResult(i,0);
then in your next activity you need to have this code
String productname,productcost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product);
tv1= (TextView)findViewById(R.id.tv1);
tv2= (TextView)findViewById(R.id.tv2);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
position = extras.getString("position"); // get the value based on the key
tv1.setText(productname);//use where ever you want
productname = extras.getString("productname"); // get the value based on the key
tv2.setText(productname);
}
First of all take a spinner and provide value to them what you want and then the selected spinner value change it to string value and this string variable will be used in OK button to pass value through use of Intent or Shared preference to take this value to another activity and through there you can use it in database to display this value.
If you want to send data to another activity, you can do it using intent.
Bundle bund = new Bundle();
bund.putString("myKey",name);
Intent intent = new Intent(Profile.this, Detail.class);
intent.putExtras(bund);
startActivity(intent);
Now in Detail class, receive this data in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
.......
String nameReceived = getIntent().getExtras().getString("myKey");
}
I have given the example of passing String to another activity however, you can pass boolean, int, double etc to another activity. See the full list on here

Refresh ListView after updating in another Activity

I have two simple Activities -
Activity1: ListView from an Array
Activity2: EditText for editing the clicked row in Activity1
When I edit the value in Activity2 and returning to Activity1, the ListView doesn't reload the new value.
I want to refresh the ListView when I return from Activity2 or resume Activity1 or something that will update the list.
My code:
static ArrayAdapter<String> dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
setListAdapter(dataAdapter);
}
#Override
public void onResume() {
super.onResume();
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
dataAdapter.notifyDataSetChanged();
}
loadArrays() is just method that converts from SharedPreferences to String Array. Activity2 saves the new data in SharedPreferences and than Activity1 can read it (with the new data).
If I return to the "main activity" (it is not Activity1) and than come back to Activity1 - the new data is shown, but I want this data will be updated when I return from Activity2 immediately.
loadArrays() method: pastebin.com/MHwNC0jK
Thanking you in advance!
On clicking the item in your first Activity, start your second Activity with startActivityForResult()
And then in Second Activity, after entering in EditText, probably there is a button. And in onClick of that button call,
intent.putExtra("edittextvalue", findViewById(R.id.edittext).getText().toString());
setResult(RESULT_OK, intent);
finish();
Now you come back to your first Activity and here you have to implement onActivityResult() callback. You can extract data from that intent's extras and set that respective item in your array and call notifyDataSetChanged().
This is ideally how you should be doing it.
If you want more info on how to use startActivityForResult() try this link - http://manisivapuram.blogspot.in/2011/06/how-to-use-startactivityforresult.html
1) Get reference ListView
mListView = (ListView)findViewById(R.id.auto_listview);
2) Create adapter One more time with changed values
MyAdapter myAdapter = new MyAdapter(getApplicationContext(),
R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
myAdapter = new MyAdapter(getApplicationContext(),
//pass changed values vlues array R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Declare fulllist as Globle Variable and used static arraylist .

Android - Change View when alertdialog button is clicked

I have a listview with a couple of strings in at the moment. when a user selects one it brings up an alertdialog box which gives the option to book(this is going to be a taxi app) or cancel. What i cant work out is how to get it so that when the user clicks "Book" it takes the information they've selected and loads up a new view with more contact information.
My Code is currently this -
public class ListTaxi extends ListActivity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", null);
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
Any help or pointers with this would be immensely appreciated as its the last bit i need to get working before its almost done.
Thanks everyone
Oli
You need to put an onClickListener onto your positive button, which will launch the new activity and pass the data to it. Your code would become something like:
public class ListTaxi extends ListActivity{ /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("booking", taxi[selectedPosition];
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
In your target activity, have something like this:
Intent intent = getIntent();
String booking = "";
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
booking = extras.getString("booking");
}
}
One way could be to get your item out of your taxi list:
taxi.get(position);
and pass it through an intent to a next activity:
Intent intent = new Intent(this, YOUR_NEXT_ACTIVITY.class);
intent.putExtra("booking", taxi.get(position);
on the next activity you can get it with:
intent = getIntent();
inten.getExtra("booking");
// could be (not sure): inten.getExtraString("booking");
You can use this method from alertDialog class
public void setButton (int whichButton, CharSequence text, DialogInterface.OnClickListener listener)
Refer link
http://developer.android.com/reference/android/app/AlertDialog.html
depending on positive response, say book is positive response then start another activity which shows details contact info, pass the select item from list as Bundle or extra with intent while starting another activity.

Categories

Resources