I am new to android i am using the search in my android using edittext search is working fine and code of search is as follow:
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
// When user changed the Text
arrayAdapter.getFilter().filter(s);
arrayAdapter.notifyDataSetChanged();
}
..........
}}
I am using simpleadapter to display the data in listview having two colomn col1,col2
say:
arrayAdapter = new SimpleAdapter(LabelUser.this, mylistData,
R.layout.two_col_row, columnTags, columnIds);
list.setAdapter(arrayAdapter);
on click of list:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
// TODO Auto-generated method stub
String selectedFromList = (list.getItemAtPosition(position).toString());
System.out.println(selectedFromList);
startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
}
});
And gives output as:
{col1=A K JOHN, col2=21.45}
My Question is how to get a string from above i.e. of col1
example var = "A K JOHN"
listview creation:
final ListView list = (ListView) findViewById(R.id.listView1);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] { "col1", "col2" };
int[] columnIds = new int[] { R.id.column1, R.id.column2 };
for (int i = 0; i < labelIdArray.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("col1", labelArray[i]);
map.put("col2", labelRateArray[i]);
mylistData.add(map);
list.setAdapter(arrayAdapter);
}
If you want to fetch the value of first Column, I think the following code will work,
String selectedFromList = columnTags[position];
Just give it try and tell if it worked or not.
Related
I am pulling data from a SQLite database and storing it in an arrayList to display info on the contact through listView. The user can then type in an EditText and the TextWatcher filters the listView. But, when this happens the position of the listview items do not update in my onClickListener.
The ID I send to my CRUD activity is always the position after they have been filtered not their position when originally listed. How can I make my ListView items hold their original position after they have been filtered? Or a better way to give my CRUD activity the correct ID not via position.
public class Search extends AppCompatActivity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<String> arrayList = new ArrayList<>();
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
db = new DBHelper(this);
arrayList = db.getAllContacts();
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Search.this.adapter.getFilter().filter(cs);
}
#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
adapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int id_To_Search = pos + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt(EXTRA_FLAG, id_To_Search);
// The flag value > 0 is used to signal that the upcoming operation
// is not adding, but updating or deleting
Intent intent = new Intent(getApplicationContext(), CRUDActivity.class);
intent.putExtras(dataBundle); //Intent.putExtras(Bundle extras
startActivity(intent);
}
});
}
I ended up just creating a second array and then splitting it, compared it to the item selected, and then parsed the id from a String to an int. After that, I sent to id to my Crud activity so it could populate the contact searched.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String split = (String) parent.getItemAtPosition(pos);
// Split this into sections then compare the name with arrayList2, then take the ID from arratList2
// parse it to an int and set it as the ID to search
int id_To_Search = 0;
String array[] = split.split(" ");
for ( int i = 0; i < arrayList2.size(); i++) {
String split2[] = arrayList2.get(i).split(" ");
if (split2[1].equals(array[0])) {
//print item the same way as you did
id_To_Search = Integer.parseInt(split2[0]);
}
}
Bundle dataBundle = new Bundle();
dataBundle.putInt(EXTRA_FLAG, id_To_Search);
// The flag value > 0 is used to signal that the upcoming operation
// is not adding, but updating or deleting
Intent intent = new Intent(getApplicationContext(), CRUDActivity.class);
intent.putExtras(dataBundle); //Intent.putExtras(Bundle extras
startActivity(intent);
}
});
}
I need to replace "gold" in Listview
AndroidListView1= "gold" > "goldennnnnnn" AndroidListView2= "gold" > "golderrrrrrrrr"
when i set it in edittext then its work!! but when i set it in List view then print only 1 item("goldennnnnnn")##
this.et3.setText(AndroidListView); (edittext work) but this.Listview.setText(AndroidListView1);not work
this is my code thanks in advance
ListView listView ;
EditText myTextBox,myOuttext,et3;
Button btn;
ClipboardManager myClipboard;
private Object adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextBox = (EditText) findViewById(R.id.editText1);
myOuttext = (EditText) findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
btn=(Button)findViewById(R.id.button1);
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.listView1);
// Defined Array values to show in ListView
String[] values = new String[]
{ "AndroidListView1",
"AndroidListView2",
"AndroidListView3",
"AndroidListView4",
"AndroidListView5",
"AndroidListView6",
"AndroidListView7",
"AndroidListView8",
"AndroidListView9",
"AndroidListView10",
"AndroidListView11",
"AndroidListView12",
"AndroidListView13",
"AndroidListView14",
"AndroidListView15",
"AndroidListView16",
"AndroidListView17",
};
// 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
ArrayList<?> yourlist = new ArrayList<Object>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
// Assign adapter to ListView
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, values));
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#SuppressLint("NewApi")
public void onTextChanged(CharSequence s, int start,
int before, int count) {
MainActivity.this.my1(s);
MainActivity.this.AndroidListView(s);
}
});
}
private String my1(CharSequence arg) {
String str = "";
str = arg.toString().replace(" ", " " ).replace("gold", "goldennnnnnn");
this.myOuttext.setText(str);
System.out.println(str);
return str;
}
private String AndroidListView(CharSequence arg) {
String AndroidListView = "";
AndroidListView= arg.toString().replace(" ", "").replace("gold", "golderrrrrrrrr");
this.et3.setText(AndroidListView);
System.out.println(AndroidListView);
return AndroidListView;
}
}
Try this code to change listView item at particular position:
ArrayList<?> yourlist = new ArrayList<Object>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
//listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
// android.R.layout.simple_list_item_1, values));
values[3] = "myNewItem";
adapter.notifyDataSetChanged();
Response of above code is:
EDIT: To search a particular item and to change that:
for(int i =0; i<values.length; i++){
if(values[i].equals("myNewItem")){
values[i] = "A_Newer_One";
}
}
adapter.notifyDataSetChanged();
this is the script :
public class LecturAct extends ListActivity {
private static final String AR_ID = "id_lec";
private static final String AR_LC = "lec_nm";
private static final String AR_CLS = "class";
private static final String EXTRA_DATA = "idr";
JSONArray lec = null;
ArrayList<HashMap<String, String>> lec_list = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_lec);
Intent quiz = getIntent();
String id = quiz.getStringExtra(EXTRA_DATA);
String link_url = "http://xxxx/xxxx.php?id="+id;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.gtJson(link_url);
try {
lec = json.getJSONArray("lec");
for(int i = 0; i < lec.length(); i++){
JSONObject ar =lec.getJSONObject(i);
String lectid = ar.getString(AR_ID);
String lecname = ar.getString(AR_LC);
String class = ar.getString(AR_CLS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, lectid);
map.put(AR_LC, lecname);
map.put(AR_CLS, class);
lec_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
ive tried to make a clickable item on my listview, this is the script:
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, lec_list,
R.layout.list_item,
new String[] { AR_ID, AR_CLS, AR_LC}, new int[] {
R.id.title, R.id.content, R.id.code});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cd = ((TextView) view.findViewById(R.id.code)).getText().toString();
Intent in = new Intent(LecturAct.this, Quis.class);
in.putExtra(AR_ID, cd);
startActivity(in);
}
});
}
but when i click an item, it keep take me to the wrong direction, always take me to the last item. if the items on the list are
physic
biology
sport
social
math
then when i click biology or whatever i choose, it will always lead me to the "math" page. so what should i do? am i using a wrong adapter? please help me, give me solution to make this right :(
This answer is like Amin's but with few differences. Sample code:
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String mlecture p = (String) l.getItemAtPosition(position);
...
in.putExtra(AR_ID, lecture);
startActivity(in);
}
Notes:
Get the ListView parameter (l), and get the row/item position to begin with.
You cannot use view.findViewById method since ListView (l) already has the UI object.
Use the override onListItemClick since ListActivity is used.
Just override protected void onListItemClick (ListView l, View v, int position, long id) in LecturAct for example
protected void onListItemClick (ListView l, View v, int position, long id) {
String cd = getListAdapter().getItem(position);
Intent in = new Intent(LecturAct.this, Quis.class);
in.putExtra(AR_ID, cd);
startActivity(in);
}
I reviewed your code more closely. I suspect the data is not arranged correctly.
Change FROM:
new String[] { AR_ID, AR_CLS, AR_LC},
new int[] { R.id.title, R.id.content, R.id.code});
TO:
new String[] { AR_ID, AR_CLS, AR_LC},
new int[] { R.id.code, R.id.title, R.id.content });
I switched R.id.code. I think this is compatible with in.putExtra(AR_ID, cd). There is no good way for me to make sure since I don't know Quiz.class.
My example like yours.Just change your object casting.Or String.
catalogListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj=(Object)((String) parent.getAdapter().getItem(position));
String ss=obj.toString();
Intent i = new Intent(getActivity(), PdfReader.class);
i.putExtra("catalogPdfUrl", "" +ss;
getActivity().startActivity(i);
}
});
I have a ListActivity class. It has a button which sorts the item according to one of their attributes. But it so happens that the item are getting sort by their name but upon clicking the item of its original position is getting executed.
Here is the code snippet :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
mButton = (ToggleButton) findViewById(R.id.mButton);
ArrayList<myObject> ListData = new ArrayList<myObject>();
back = (ImageButton) findViewById(R.id.backButton);
label = (TextView) findViewById(R.id.likethis);
label.setText("List");
inputSearch = (EditText) findViewById(R.id.inputSearch);
//Manager -- class that reads from the sdcard
Manager plm = new Manager();
// get all files from sdcard
//getList() function of Manager class
//List declared outside oncreate()
this.List = plm.getList();
final ArrayList<myObject> backUp = new ArrayList<myObject>(songsList);
if(sortCalled) {
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
mButton.setChecked(true);
Collections.sort(List);
notifyDataChanged(List);
}
else {
mButton.setBackground(getResources().getDrawable(R.drawable.m_unchecked));
mButton.setChecked(false);
notifyDataChanged(backUp);
}
back.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
//ArrayList <Song> temp;
((SimpleAdapter) PlayListActivity.this.adapter).getFilter().filter(s, new Filter.FilterListener() {
public void onFilterComplete(int count) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
});
adapter.notifyDataSetChanged();
}
});
mButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mButton.isChecked()){
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
Collections.sort(List);
sortCalled = true;
notifyDataChanged(List);
}
else{
sortCalled = false;
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_unchecked));
notifyDataChanged(backUp);
}
}
});
}
public void settingListAdapter(SimpleAdapter adapter){
setListAdapter(adapter);
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending Index to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
}
public void notifyDataChanged(ArrayList<Song> songsList) {
// TODO Auto-generated method stub
setListAdapter(null);
sortCalled = true;
ArrayList<myObject> songsListData = new ArrayList<myObject>();
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
myObject ob = sList.get(i);
// adding HashList to ArrayList
ListData.add(ob);
}
ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String,String>>();
// int j = 0;
for(myObject i : ListData){
HashMap<String, String> feed = new HashMap<String, String>();
feed.put("Title", i.getTitle());
array.add(feed);
}
BaseAdapter adapter1;
// int i = 0;
// Adding menuItems to ListView
adapter1 = new SimpleAdapter(this, array,
R.layout.list_item, new String[]{"Title" }, new int[] {
R.id.Title });
setListAdapter(adapter1);
adapter1.notifyDataSetChanged();
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending songIndex to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
I think you should try this.when you sort the data of your listview.it is working me perfectly
adapter.notifyDataSetChanged();
Everytime you make a change to adapter you should call notifyDataSetChanged() in UIThread
Please check this video to understand listView better
Edit
For an ArrayAdapter, notifyDataSetChanged only works if you use the add, insert, remove, and clear functions on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add, insert, remove, clear, etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged every time the list is update. To call it on the UI-Thread use the runOnUiThread method of the Activity. Then notifyDataSetChanged will work.
You could try the Adapter.notifyDataSetChanged() function. It might work.
If you are using a SimpleCursorAdapter, calling requery() on the cursor attached to the adapter will automatically refresh the adapter and attached view.
If it's BaseAdapter content changes, you call BaseAdapter.notifyDataSetChanged() which will tell the ListView to update itself.
In other words you only need to make the following tiny change:
public void setValue(Object newValue) {
this.value = newValue;
notifyDataSetChanged();
}
Actually, since you're changing the state of an existing item (rather than adding new ones etc) then notifyDataSetInvalidated() would be a better choice.
I'm writing a news-app and I'm having some trouble with displaying a custom list. All I want is that list items have 2 TextViews in them:
News-Title and
News-Description
These are contained in 2 static arrays: homeScreen.title[] and homeScreen.descriptionLong[].
Lower you have my code for the HashMap and the Adapter:
final static ArrayList> data = new ArrayList>();
static{
HashMap<String, String> row = new HashMap<String, String>();
for (int i = 0; i<HomeScreen.arrayLength; i++){
row.put("Title", HomeScreen.title[i]);
row.put("Description", HomeScreen.descriptionLong[i]);
data.add(row);
}
}
SimpleAdapter adapter = new SimpleAdapter(this,
data,
R.layout.mainmenu,
new String[] {"Title", "Description"},
new int[] { R.id.textView1, R.id.textView2});
setListAdapter(adapter);
}
public void onItemClick(SimpleAdapter arg0, View arg1, int position,
long id) {
selectedNews = position;
Toast.makeText(getApplicationContext(), "This is: " + selectedNews, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainMenu.this, ReadNews.class);
startActivity(intent);
}
The problem I'm having is that it only displays my 20'th (last) news information and also the default OnItemClick isn't working anymore. I'd appreciate your help...
You should put the row instantiation inside the for loop:
for (int i = 0; i<HomeScreen.arrayLength; i++){
HashMap<String, String> row = new HashMap<String, String>();
row.put("Title", HomeScreen.title[i]);
row.put("Description", HomeScreen.descriptionLong[i]);
data.add(row);
}
Update:
Your OnItemClickListener registration should look something like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// your code here
}
});