Android Listview Search function - android

Am having problem with my code.. am trying to add a search function to my list view in android.. it is somehow working but when i search it gave me other activity not the real result.. Like in my listview if i search for sale i.e the 5th activity it shows the result but when i click to open the activity it open Sani activity i.e the first activity on the list...
Here is the Activity Java Code
package com.example.bati;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class MainActivity extends Activity {
ListView lv;
SearchView sv;
String[] teams = {"Sani", "Bali", "Sati", "Umam", "sale"};
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teams);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), Sani.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), Bali.class);
startActivityForResult(myIntent, 1);
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), Sati.class);
startActivityForResult(myIntent, 2);
}
}
});
}
}

When you filter your adapter and notify with the result your item's positions change you you cannot use position as an identifier to open activity. Your search data changes but you're always clicking the position 0 so always Sani activity gets opened.
Here i modified your code a bit:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String item = (String)parent.getItemAtPosition(position);
if ("Sani".equals(item)) {
Intent myIntent = new Intent(view.getContext(), Sani.class);
startActivityForResult(myIntent, 0);
}
if ("Bali".eqauls(item)) {
Intent myIntent = new Intent(view.getContext(), Bali.class);
startActivityForResult(myIntent, 1);
}
if ("Sati".equals(item)) {
Intent myIntent = new Intent(view.getContext(), Sati.class);
startActivityForResult(myIntent, 2);
}
}
});
I think this'll help you.

The position the ListView gives you in onItemClick is the position of the clicked item from the top of the currently visible items in the ListView. Since the list view is filtered, the position may not be equal to the item position in teams array.
You can get the item at the position from the adapter itself. Following code will work for you.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = adapter.getItem(position);
switch (item) {
case "Sani":
startActivityForResult(new Intent(view.getContext(), Sani.class), 0);
return;
case "Bali":
startActivityForResult(new Intent(view.getContext(), Bali.class), 1);
return;
case "Sati":
startActivityForResult(new Intent(view.getContext(), Sati.class), 2);
return;
}
}
});

Related

Implement searchview on string type listview Android

I have a list of items and i want to start different activity on the basis of item, when i click it opens the correct activity but when i try to search list items from search view bar then it opens wrong activities.
listView = (ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView1);
String[] values = new String[]{item1,item2,item3,item4,}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
listView.setAdapter(adapter);
//linking from 1 item to other activity stars with if options//
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
I don't know much about coding but can any one solve my problem..
you are starting your activity on the basis of position but the position will be changed when you do the search because list will shrink and positions will change so to get data associated with the specified position in the list use getItemAtPosition
so changes conditions on the basis of data
if (parent.getItemAtPosition(position).equals("item1")) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (parent.getItemAtPosition(position).equals("item2")) { // use any item value here you want
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
Note : you can use switch as well instead of long if or else-if ladder
e.g You have three string
item 1 position 0
item 2 position 1
item 3 position 2
after searching item 2 you have two values in your list close to your search
item 2 position 0
item 3 position 1
so position will change so don't use it instead use the data
Code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = null;
// global string to class
selectedValue = String.valueOf(parent.getItemAtPosition(position));
if (selectedValue.equals("item1")) {
// ^^^ use any item value here you want
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (selectedValue.equals("item2")) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});

listview item open activity

I have an error when i click on item in activity they all show me the same string which his name: "name_0"
the activity which is open when we click:
public void handle() {
TextView var3 = (TextView) this.findViewById(R.id.name);
TextView var2 = (TextView) this.findViewById(R.id.meaning);
TextView var5 = (TextView) this.findViewById(R.id.proof);
Intent var4 = this.getIntent();
int var1 = var4.getIntExtra("name", 0);
switch (var1) {
case 0:
var3.setText(R.string.name_0);
var2.setText(R.string.meaning_0);
var5.setText(R.string.proof_0);
break;
case 1:
var3.setText(R.string.name_1);
var2.setText(R.string.meaning_1);
var5.setText(R.string.proof_1);
break;
case 2:
var3.setText(R.string.name_2);
var2.setText(R.string.meaning_2);
var5.setText(R.string.proof_2);
break;
}
}
and the activity who open the item onclick:
String[] values = { "test", "list", "ok", "bon" };
protected void onCreate(Bundle var1) {
super.onCreate(var1);
this.setContentView(R.layout.activity_main);
this.listView = (ListView) this.findViewById(R.id.list);
listView.setAdapter(new ArrayAdapter<String>(this, R.layout.listview_item,
R.id.textView_list, values));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent Start = new Intent(MainActivity.this, Asma2Ma3anihaActivity.class);
startActivity(Start);
}
});
The problem is that you are not sending the position of the clicked item
Intent start = new Intent(MainActivity.this, Asma2Ma3anihaActivity.class);
start.putExtra("name", position);
startActivity(start);
That should work.
You always got 0 because you set 0 here (var4.getIntExtra("name", 0);) as the default value when the "name" key is missing.
You never set the 'name' extra on your Intent when you create it in the setOnItemClickListener, so when you try and retrieve the int in the 'handle()' method, you will always get 0.
You have to set the extra on the intent before you do 'startActivity'.
Intent startIntent = new Intent(MainActivity.this, Asma2Ma3anihaActivity.class);
startIntent.putExtra("name", position);
startActivity(startIntent);
In order to get the text from the item you need to get the value from the view you get from the itemclicklistener
i.e
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
String text = ((TextView)view.findViewById(R.id.name)).getText();
Intent Start = new Intent(MainActivity.this, Asma2Ma3anihaActivity.class).putExtra("name",text);
startActivity(Start);
}
});

how to change color of list item when it is selected in listview?

i have one main activity class in which i define string array which fetch list from XML file saved in res/value which contain list of item . now i want that when any item selected it color change to yellow . how to do this please help :)
thanks in advance ::)
my two file's are list_data.XML and Main Activity.java
List_data.XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="tias_list">
<item>About us</item>
<item> Offered</item>
<item> year </item>
<item>Process</item>
<item>item1</item>>
<item>item2</item>>
<item>item3</item>>
<item>item4</item>
</string-array>
</resources>
MY Main Activity class code is
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] tias_list = getResources().getStringArray(R.array.tias_list);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label,tias_list));
ListView lv = getListView();
lv.setCacheColorHint(0);
lv.setBackgroundResource(R.drawable.black);
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view,int position, long id) {
if (position == 0)
{
Intent myIntent = new Intent(getApplicationContext(), SingleListItem.class);
startActivity(myIntent);
}
else if(position == 1)
{
Intent myIntent = new Intent(getApplicationContext(), lastyear.class);
startActivity(myIntent);
}
else if(position == 2)
{
Intent myIntent = new Intent(getApplicationContext(), la.class);
startActivity(myIntent);
}
else if(position == 3)
{
Intent myIntent = new Intent(getApplicationContext(),la.class);
startActivity(myIntent);
}
else if(position == 4)
{
Intent myIntent = new Intent(getApplicationContext(), SingleListItem.class);
startActivity(myIntent);
}
else if(position == 5)
{
Intent myIntent = new Intent(getApplicationContext(), SingleListItem.class);
startActivity(myIntent);
}
else if(position == 6)
{
Intent myIntent = new Intent(getApplicationContext(), SingleListItem.class);
startActivity(myIntent);
}
else if(position == 7)
{
Intent myIntent = new Intent(getApplicationContext(), SingleListItem.class);
startActivity(myIntent);
}
}
});
}
The adapter that you are currently using is the Default Adapter. However, now you want to modify it's properties. To do so you'll need to implement a custom adapter - an adapter of your own. Just Google Custom ListView Adapter if you don't know how to do that.
And in that custom adapter, there'll be a getView() method and in the getView() method of the custom adapter check if the position of item is same as the selected item. If yes, set background colour.
Here's a complete answer : https://stackoverflow.com/a/16978159/1239966
IN your getView method, you have to do some code over there.
int currentPosition=0;
if (position == currentPosition) {
convertView.setBackgroundColor(Color.YELLOW);
} else {
convertView.setBackgroundColor(Color.YOUR DEFAULT COLOR);
}
//click item code:
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentPosition = position;
adapter.notifyDataSetChanged();
}
});
To set color of selected Item use
view.setBackgroundColor(Color.YELLOW);
i.e in your code as
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view,int position, long id) {
view.setBackgroundColor(Color.YELLOW);
// your code

Start Activities from onItemClick of ListView in fragments

So I have two fragments linking to layout files which display ListViews. The ListViews are defined in the xml and have entries from a string array. I want to click on items in the ListView and open new activities. There are 8 items in one ListView and 9 in the other. In the onItemClick code, how do I create intents to start activities based on the item clicked? I will create 1 class per item as its own activity. How can I start the activities in the classes via intents inside the onItemClick methods of this code?
class CommunityFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.community_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.communityListView);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
// TODO Auto-generated method stub
}
});
return view;
}
}
class ResourcesFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.resources_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.resourcesListView);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Implement your OnItemClickListener() like below
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
}
});
Make switch statement for each items click and open activities accordingly as below:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int itm=arg0.getItemAtPosition(arg2);
switch (itm) {
case 0:
Toast.makeText(m_context, "Position Zero", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), FirstActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(getActivity(), SecondActivity.class);
startActivity(intent1);
break;
case 2:
//..............................
}
});
on Item Click you will get Position based on position you can start fragment
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
switch(position) {
case CONST_FRAGMENT_1 :
//Start fragment 1
...
...
}
}
});
one Generic solution can be ..
Create an array of items that hold class name of activity you want to open ..
like ..
Class[] activityArray = new Class[numberOfItemsInListView];
activityArray[0] = Activity1.class;
//add all activities like that..............
now on ListView onItemCLick :
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
Intent intent = new Intent(CommunityFragment.this.getActivity(), activityArray[postion]);
CommunityFragment.this.getActivity.startActivity(intent);
}
});
Use this to start next intent in your onItemClickListener:
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
I think following code help you.
public class PdfListViewFragment extends Fragment {
ListView listView;
Activity rootView;
Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View rootView = inflater.inflate(R.layout.pdf_list_view, container, false);
context = getActivity();
// Get ListView object from xml
listView = (ListView) rootView.findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[]{"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 3) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 5) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 6) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 7) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(context.getApplicationContext(), "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("XYZ");
}
}
If you use an adapter to display the items in a list, it is important to differentiate the following:
The ID of the list AdapterView#getId() is different than the ID of the items in the list ArrayAdapter<String>#getId(), because the view of the list contains the views of the elements.
Suppose an example where you are going to launch activities with user roles. You will have to do the transformation for your particular case.
public class SignInFragment extends Fragment implements AdapterView.OnItemClickListener {
//TODO: Declare constants (GUEST, HOST, EMPLOYEE...)
private ArrayAdapter<String> userRolesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_sign_in, container, false);
// ListView Instance
ListView userRolesList = root.findViewById(R.id.user_roles_list);
String[] userRoles = {
GUEST,
HOST,
EMPLOYEE
};
// Initialize the adapter
userRolesAdapter = new ArrayAdapter<>(
getActivity(),
android.R.layout.simple_list_item_1,
userRoles
);
// Link to the list with the adapter. This reference starts the process of filling the list.
userRolesList.setAdapter(userRolesAdapter);
// Events
userRolesList.setOnItemClickListener(this);
return root;
}
/**
* #param adapterView: View using the adapter from the list
* #param view: View of the item that has been pressed
* #param i: Refers to the position of the item that the adapter handles
*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getId() == R.id.user_roles_list) {
// Obtain the item pressed on the adapter with the entry position
String currentUserRol = userRolesAdapter.getItem(i);
assert currentUserRol != null;
switch (currentUserRol) {
case GUEST:
startActivity(Host.class);
break;
case HOST:
startActivity(Host.class);
break;
case EMPLOYEE:
startActivity(Employee.class);
break;
default:
Log.d("Error", "The activity passed as an argument to startActivity() does not exist");
break;
}
}
}
/**
* PRECONDITION: The class given as an argument exists.
*/
public void startActivity(Class<?> cls) {
Intent intent = new Intent(getActivity(), cls);
startActivity(intent);
}
}
Best :)

Listview , open new activity onClick

Hey everyone I've looked for hours trying to find a solution to this, my goal is to have a Listview when it opens well open another activity. Well actually I got it to be able to open another activity when its click but how do I get it so that each list item will open its own activity? I am terribly sorry if this question is already answered but the links I found doesn't really describe what the code is doing [Yes i am a newbie :)]
this is the code im using
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] countries = getResources().getStringArray(R.array.countries_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.newfile, countries));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Intent myIntent = new Intent(view.getContext(), Html_file.class);
startActivityForResult(myIntent, 0);
}
});
}
}
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 1) {
//code specific to first list item
Intent myIntent = new Intent(view.getContext(), Html_file1.class);
startActivityForResult(myIntent, 0);
}
if(position == 2) {
//code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(), Html_file2.class);
startActivityForResult(myIntent, 0);
}
}
});
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position ) {
case 0: Intent newActivity = new Intent(this, i1.class);
startActivity(newActivity);
break;
case 1: Intent newActivity = new Intent(this, i2.class);
startActivity(newActivity);
break;
case 2: Intent newActivity = new Intent(this, i3.class);
startActivity(newActivity);
break;
case 3: Intent newActivity = new Intent(this, i4.class);
startActivity(newActivity);
break;
case 4: Intent newActivity = new Intent(this, i5.class);
startActivity(newActivity);
break;
}
}
If you have some limited number of list you can use switch case here on position
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Intent myIntent = new Intent(view.getContext(), Html_file.class);
startActivityForResult(myIntent, 0);
}
});
If you know which activity is to be opened when different list items are clicked, then just assign id or tag to the list items.
In the callback of onItemClick, you have a parameter View,
use it to get id or tag to differentiate them and call respective Activity.
// Add ArrayList and ArrayAdapter:
final ArrayList<String> listItems = new ArrayList<String>();
listItems.add("image_one");
listItems.add("image_two");
listItems.add("image_three");
ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listItems);
myListView.setAdapter(myArrayAdapter);
// Add ArrayList of Classes:
final ArrayList<Class> intents = new ArrayList<Class>();
intents.add(image_one.class);
intents.add(image_two.class);
intents.add(image_three.class);
// Click on list item to open Class from ArrayList of Classes:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent listIntent = new Intent(getApplicationContext(),
intents.get(position));
startActivity(listIntent);
}
});
SEE IMAGE OF CLASS NAMES HERE

Categories

Resources