Select item in ListView using value from Intent - android

I'm trying to select an item in a ListView based on a value I get from an Intent. I've tried ListView.setSelection, but it's not working.
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
Here is the rest of the code, for context:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sport_item);
ListView listView = findViewById(R.id.listview);
String[] sports = new String[] {
"Soccer",
"Running",
"Swimming",
"Volleyball",
"Tennis"
};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.listview, R.id.textView, sports);
listView.setAdapter(arrayAdapter);
Button btnSelect = findViewById(R.id.btnSelect);
listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ListView.getCheckedItemPosition() != -1) {
Intent i = new Intent(SportActivity.this, InformationActivity.class);
i.putExtra("Sport", sports[listView.getCheckedItemPosition()]); |
i.putExtra("Position", listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, i);
finish();
} else
Toast.makeText(SportActivity.this, "Ban chua lya chon", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SportActivity.this, "Sport selected :" + sports[i], Toast.LENGTH_SHORT).show();
}
});
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
}

show more code, post it in here. you should call setSelected only after setting adapter, before there is no content on list so nothing gets selected
in your case your problem is caused probably by comparing Strings with == operator. in Java it compares objects and one obtained from intent and second one from array arent same objects, even if they have same content (they still are two objects in two separated placed in memory). use equals method for comparing only content
if(sports[position].equals(sp))

Related

Passing checked items in a list view to an arraylist/array

Hey I'm new to android app development and in this situation I'm creating a mobile application which stores data in SQLite database and show it in a list view and the items in the list can be checked by check boxes.
In here I want to get the position of the checked items so I can pass them to the database, and when the application opens again previously checked items will be already checked. I want to save the position when the button is clicked.
I've used a SparseBooleanArray to store the checked items but I've no idea to pass the values of SparseBooleanArray to DB and I'm stuck there.
Help me with this and thanks in advance.
*
public class Subscribe extends AppCompatActivity {
ListView lanList;
DatabaseHelper translateDB;
TextView textView;
Button button;
ArrayList<String> list = new ArrayList<>();
String clicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribe);
translateDB = new DatabaseHelper(this);
textView = findViewById(R.id.textView);
lanList = findViewById(R.id.listView);
button = findViewById(R.id.subscribeBtn);
showLang();
}
public void showLang(){
final Cursor cursor = translateDB.retriveLang();
System.out.println("1");
if (cursor.getCount() == 0){
Toast.makeText(Subscribe.this, "No data", Toast.LENGTH_LONG).show();
return;
}
System.out.println("2");
while (cursor.moveToNext()) {
list.add(cursor.getString(1));
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_multiple_choice,list);
lanList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lanList.setAdapter(arrayAdapter);
lanList.setItemChecked(1,true); <--- used this to check the functioning
lanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
clicked = adapterView.getItemAtPosition(i).toString();
Toast.makeText(Subscribe.this,"You selected '"+ clicked+"' " , Toast.LENGTH_LONG).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checkedItems =lanList.getCheckedItemPositions();
System.out.println("1 - " +checkedItems);
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = lanList.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
System.out.println("2 - " +item);
translateDB.subscribedLang(item);
}
}
}
}
});
}
*
SO what I'm planning to do is pass the checked positions to db and get the positions and lanList.setItemChecked(x,true); and pass position values to this code.
Help me with this.

select mutiple contact list by searchview and send to another activity

OK I have a multiple choice ListView that works fine. I check the boxes for the contacts (held in a String[]) and can return the values fine. Because some people have a bunch of contacts I wanted to create a search bar kind of like the stock one for the Android phone book. I created an EditText and aligned it above my list. I found the filtering code here on StackOverflow and it works wonderfully.
My Problem:
When you filter someones name out, and you select the name, when you either backspace from the EditText or continue typing, the correct position of the name you selected is not saved. For example, if I start typing "Adam" and get to "Ada" and select it, if I backspace to type in "Carol", whatever position "Ada" was at is selected. It gathers the place that "Adam" was at from the click (Let's say 2) and when the list is restored checks that position (2) even though Adam is not there anymore. I need a way to gather the name.. then when the list is restored or searched again, the NAME Adam is checked and not the POSITION Adam was previously at. I have absolutely no ideas other than creating tons of Arrays and could really use some help.
public class MainActivity extends Activity {
private static final String[] items={"lorem1", "ipsum1", "dolor1",
"sit1", "amet1","lorem2", "ipsum2", "dolor2",
"sit2", "amet2","lorem3", "ipsum3", "dolor3",
"sit3", "amet3","lorem4", "ipsum4", "dolor4",
"sit4", "amet4","lorem5", "ipsum5", "dolor5",
"sit5", "amet5","lorem6", "ipsum6", "dolor6",
"sit6", "amet6","pigeon","victory"};
ListView list;
Button save;
EditText inputSearch;
SearchView searchview;
ArrayAdapter<String> adapter;
int textlength=0;
// private String my_sel_items;
ArrayList<String> selectedItems1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items));
list = (ListView) findViewById(R.id.list);
list.setEmptyView(findViewById(R.id.empty));
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
inputSearch = (EditText) findViewById(R.id.inputSearch);
save = (Button) findViewById(R.id.save);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
textlength = inputSearch.getText().length();
selectedItems1.clear();
for (int i = 0; i < items.length; i++) {
if (textlength <= items[i].length()) {
if (inputSearch.getText().toString().equalsIgnoreCase(
(String)
items[i].subSequence(0,
textlength))) {
selectedItems1.add(items[i]);
}
}
}
list.setAdapter(new ArrayAdapter<String>
(MainActivity.this,
android.R.layout.simple_list_item_multiple_choice, selectedItems1));
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
if (selectedItems.size() < 1) {
Toast.makeText(getApplicationContext(), "Select atleast one ", Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
intent.putExtras(b);
startActivity(intent);
}
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
}
});
}
}
Perhaps you can use unique ID's.
In every list item you can have an invisible TextView that will store the ID.
On click assign to some variable the ID and you can use it later.
Hope that helps.
Lets say your list items XML are as so:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Contact name -->
<TextView
android:id="#+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Contact Unique ID -->
<TextView
android:id="#+id/contactID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
In your activity class add the following variables:
static int uid;
int selectedId;
Then before initializing the list add:
uid = 0;
In the adapter or whatever way you add views to list do:
TextView id = (TextView)yourListItem.findViewById(R.id.contactID);
id.setText(String.valueOf(uid));
uid++;
And finally in the onClickListener of the list item add:
TextView id = (TextView)yourListItem.findViewById(R.id.contactID);
selectedId = Integer.parseInt(id.getText().toString());
That way you can fetch the selected list item later - by comparing the selected id.

How to start an activity from a custom ListView?

I have a custom listview in which I can add as many elements as I want. All of these elements must open an activity (which is called "Compile" in my project) with a few edittext stuff to fill. The problem is that I don't actually know what to write in my code to tell the app to open the Compile activity when one of the elements is clicked.
//(Obviously every element must open its Compile activity with its relative informations. For example: element "Pizza" must open the activity Compile in which there are all the infos I previously put about Pizza.)//
Thanks for the support
This is my code for the listview:
public class Sheet extends Activity {
private static final int DIALOG_ALERT = 10;
ListView list;
ImageView addBtn;
EditText input;
String[] items;
MyListAdapter adapter;
AlertDialog alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheet);
list = (ListView) findViewById(R.id.list);
addBtn = (ImageView) findViewById(R.id.addPlanBtn);
input = new EditText(this);
items = new String[1];
alert = new AlertDialog.Builder(Sheet.this).create();
alert.setTitle("Activity name: ");
alert.setMessage("Type a name for your activity: ");
alert.setView(input);
alert.setButton("add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String value = input.getText().toString();
items[items.length - 1] = value;
adapter = new MyListAdapter(Sheet.this, items);
list.setAdapter(adapter);
String[] temp = new String[items.length +1];
for(int i = 0; i< items.length; i++)
temp[i] = items[i];
items = temp;
alert.dismiss();
adapter.notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.show();
}
});
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Object selectedItem = parent.getItemAtPosition(position);
//Do something with your object. If it's a String and you want to send it to CompileActivity, do it like this:
Intent intent = new Intent(MainActivity.this, CompileActivity.class);
intent.putExtra("some-data-id", (String)selectedItem)
startActivity(intent);
}
}
In CompileActivity, you can use the sent data like so:
String selectItem = getIntent().getStringExtra("some-data-id");
Please keep in mind that Intents send copies of your data across activities. Changing this string does not change the one from the previous activity. It is just a copy.
Intents are basic building blocks for Android, so it is worth learning more about them. Here is a place to start
Add this to your listView's OnItemClickListener:
Intent newActivity = new Intent(MainActivity.this, CompileActivity.class);
//You could pass extra info here using newActivity.putExtra().
// Like newActivity.putExtra("Pizza", "Pizza name");
startActivity(newActivity);
In your list view activity class set "setOnItemClickListener" for your listview. And from there start a new activity.
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(view.getContext(),yourActivity.class);
//you can add some extras if you want like this
intent.putExtra("Key",Value);
startActivity(intent);
}
});
You can retrieve the value in called activity like this :
int variable = getIntent().getIntExtra("Key", someDefaultIntValue);
Please note you can replace int here with your datatype.

android How to send listview item to another activity

I am trying to send row item from list view to another activity but maybe I do something wrong.
I made one app for food.
And I want when the user click to "First Activity" the list item from this listview to be send to "Second Activity" and when the user click to "Add to cart" the listview item go to Cart.class
But when I click to "Add to cart" the Activity is send me tо Cart.class but there have nothing.
In cart.xml I have listvew.
Sorry for my bad english
Thanks in advance.
First Activity.
public class UnderCal extends Activity {
String classes[] = {"Grilled chicken","Asiago","Spicy"};
int[] meal = new int[]{
R.drawable.grilledchicken,
R.drawable.asiago,
R.drawable.spicy
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.under_menu);
final List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<3;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("food", Integer.toString(meal[i]));
hm.put("txt", "" + classes[i]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"food","arrow","txt"};
// Ids of views in listview_layout
int[] to = { R.id.food,R.id.arrow,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_layout, from, to);
// Getting a reference to listview of main.xml layout file
final ListView listView = ( ListView ) findViewById(R.id.mylist);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setDivider(new ColorDrawable(0xffffffff));
listView.setDividerHeight(1);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if (position == 0)
{
Intent intent = new Intent(UnderCal.this,GrilledChicken.class);
// intent.putExtra("get", aList.get(position));
String result = (String) listView.getItemAtPosition(position).toString();
intent.putExtra("get",result);
startActivity(intent);
overridePendingTransition(R.anim.animation3, R.anim.animation4);
}
}
});
}
Second Activity.
public class GrilledChicken extends Activity {
Button butadd;
//HashMap<String, String> hm;
String list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.grilled_chicken);
//hash
// hm =(HashMap<String, String>)getIntent().getSerializableExtra("get");
Bundle extras = getIntent().getExtras();
list = extras.getString("get");
butadd=(Button) findViewById(R.id.butadd);
butadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(GrilledChicken.this,Cart.class);
// intent.putExtra("hm",hm);
intent.putExtra("list",list);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
Cart.class
public class Cart extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cart);
Bundle extras = getIntent().getExtras();
String pos = extras.getInt("list");
}
}
For get item from your listview you have to write following code.
String item = food.get(position).toString();
Write this on your Itemclick method
Put the following code in your Cart.class
Bundle extras = getIntent().getExtras();
String list_data = extras.getString("list");
Now list_data contains the data.
There is another way through which you can do the task also.
Create a separate Global Class
Global.class
public class Globalclass {
public static String list_data;
}
And then in your FirstActivity replace the following
intent.putExtra("get",result);
with
Globalclass.list_data=result;
Now you can access the list_dataanywhere like the following
String data=Globalclass.list_data;
Try this once I hope this will help you.
First of all do this in YourFirstActivity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), YourSecondActivity.class);
YourModel yourModel = (YourModel) parent.getItemAtPosition(position);
intent.putExtra("yourModel", yourModel);
startActivity(intent);
}
});
At another Activity do this.
YourModel yourModel= (YourModel) getIntent().getSerializableExtra("yourModel");
From yourModel object you will get all the data of your ListView selected item of YourFirstActivity to YourSecondActivity.
Multiple Send ListView Item:-
ArrayList<String>checked11 = new ArrayList<String>();
SparseBooleanArray checked = listView1.getCheckedItemPositions();
final ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.get(i))
selectedItems.add(checked11.get(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
use Bunddle :
Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(),
OtherActivity.class);
bundle.putStringArray("selectedItems", outputStrArr);
intent.putExtra("screen2", "sub");
intent.putExtras(bundle);
intent.putExtra(EXTRA_RESPONSE, selected);
startActivity(intent);

Using Checkbox array in android

I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.
If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.
can anybody guide me on that..?
This is the java code:
public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btn1;
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tailoredtwo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.listViewcity);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Change your onClick to
Delcare the below as a class variable
StringBuilder builder;
Then
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
builder = new StringBuilder();
for(int index = 0; index <array.length; index++) {
if(positions.get(index)==true)
{
builder.append(array[index]);
builder.append("\n");
}
}
Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}

Categories

Resources