Android Adapter notifyDataSetChanged works only on loading (second adapter) - java

I have little trouble with my adapter. After I add new content to my list and refreshing with notifyDataSetChanged the onClickListener doesn't work for that new item. After I do click back and go back to the add menu, the item works fine.
So the loading part works perfectly.
The first Adapter with list it do works perfectly. Its pretty much the same code.
In onCreate function...
Button addContent = (Button)findViewById(R.id.addContent_button);
final ListView myList = (ListView)findViewById(R.id.mainMenuList);
final boolean deleteMode = false;
String[] liegenSchaften = new String[] {};
final List<String> content = new ArrayList<String>(Arrays.asList(liegenSchaften));
final ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, content);
myList.setAdapter(adapter);
//load the Save Data
Map<String, ?> map = getSaveMap();
//add exists data to list
for (Map.Entry<String, ?> entry : map.entrySet()) {
content.add(entry.getValue().toString());
}
// Update adapter, this works fine!
adapter.notifyDataSetChanged();
addContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
content.add(editedText.getText().toString());
/* This adapter dont Update the new Content, the item display and is not clickeble */
adapter.notifyDataSetChanged();
editor.putString(editedText.getText().toString(), editedText.getText().toString());
editor.commit();
}
});
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//load the Save Data
Map<String, ?> map = getSaveMap();
Object obj = myList.getAdapter().getItem(position);
String value = obj.toString();
//add exists data to list
for (Map.Entry<String, ?> entry : map.entrySet()) {
if(entry.getValue().toString() == value) {
if(deleteMode) {
editor.remove(value);
editor.commit();
content.remove(position);
adapter.notifyDataSetChanged();
} else {
selectedContent = entry.getValue().toString();
addMessage.setText(entry.getValue().toString() + " Wurde gewählt.");
addMessage.show();
}
}
}
}
});

I have found the problem:
The query was wrong. Now I have used equals and the ArrayAdapter works beautifully!
if(entry.getValue().toString().equals(value))

Related

How putExtra in RecyclerView with arraylist from JSON

I'm try to go another activity, from RecyclerView with determined position, and i need putExtra for load info in the destin activity.
I'm based in this example, but i have problem when I call JSON file.
The Sample code is this:
JsonObjectRequest jreq = new JsonObjectRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int success = response.getInt("success");
if (success == 1) {
JSONArray ja = response.getJSONArray("infoRecy");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
HashMap<String, String> item = new HashMap<String, String>();
// item.put(ITEM_ID, jobj.getString(ITEM_ID));
item.put(ITEM_RUTA,
jobj.getString(ITEM_RUTA));
item.put(ITEM_VEH,
jobj.getString(ITEM_VEH));
Item_List.add(item);
} // for loop ends
String[] from = {ITEM_RUTA, ITEM_VEH};
int[] to = {R.id.i_ruta, R.id.i_veh};
adapter = new SimpleAdapter(
getApplicationContext(), Item_List,
R.layout.message_list_row, from, to);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new ListitemClickListener());
} // if ends
} catch (JSONException e) {…
I have problema in this line, I not know like fix
listview.setOnItemClickListener(new ListitemClickListener());
Show me this error:
Cannot resol symbol 'ListitemClickListener'
since my click method is different
#Override
public void onMessageRowClicked (int i) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > i) {
enableActionMode(i);
} else {
Toast.makeText(getApplicationContext(), "Read: hola" + message.getParadas() + message.getVehiculo(), Toast.LENGTH_SHORT).show();
Intent saag_intent = new Intent(ge_MainActivity.this,
ge_Traker_maps.class);
saag_intent.putExtra("ruta", Item_List.get(i));
saag_intent.putExtra("vehiculo", Item_List.get(i));
startActivity(saag_intent);
}
}
how could putExtra in my recyclerView, with this code for sample that i use
try this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// do on item click
}
});
it will fix below issue
Cannot resol symbol 'ListitemClickListener'

My spinner loads only the first data(string) from the List

Courseprof.java:
This is iterating my data and putting it onto the spinner, but when i run the app it only loads the first data from the list. For example: i have strings on my list which are ["r12 cs100 a20","r02 cs120 a40","r90 cs001 a30". Only "r12 cs100 a20"] was loaded in my spinner. but I want to load all the data in my list :'(
#SuppressWarnings({ "rawtypes" })
public void addData(ArrayList<Properties> courseusers) {
for (Iterator i = courseusers.iterator(); i.hasNext();) {
Properties p = (Properties) i.next();
Spinner mySpinner = (Spinner) findViewById(R.id.spincourse);
List<String> itemList = Arrays.asList(p.getCourseId()+" "+p.getRoom()+" "+p.getSection());
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item,
itemList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
}
}
Properties.java:
String roomid,courseid,sectionid;
int profid;
public String getRoom() {
return roomid;
}
public void setRoom(String roomid) {
this.roomid = roomid;
}
public String getCourseId() {
return courseid;
}
public void setCourse(String courseid) {
this.courseid = courseid;
}
public String getSection() {
return sectionid;
}
public void setSection(String sectionid) {
this.sectionid = sectionid;
}
Because you are creating list with single element in every iteration of loop along with adapter and spinner initialization .
Solution : Move spinner and adapter code outside loop (at the end) and use mutable list to add data in loop.
// move initialization of references before loop
Spinner mySpinner = (Spinner) findViewById(R.id.spincourse);
List<String> itemList = new ArrayList<>();
for (Iterator i = courseusers.iterator(); i.hasNext();) {
Properties p = (Properties) i.next();
// add items to list
itemList.add(p.getCourseId()+" "+p.getRoom()+" "+p.getSection());
}
// data list is ready so setup adapter and display spinner
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item,
itemList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);

Listview prints Object not string java

I'm trying to display a listview with data out of openERP / odoo.
OpenERP returns an list of objects that I'm trying to use into a listview, but it prints out "Ljava.lang.object#number".
listOfValues return the list of objects, in my onPostExecute I want to connect it with the listview. But it doesn't work, anyone suggestion?
private class ListViewLoaderTask extends AsyncTask{
#Override
protected SimpleAdapter doInBackground(String... strJson) {
connector=new OpenerpRpc(getBaseContext());
connector.Config();
current_page += 1;
listOffValues = getListOffFieldValues(current_page, false, listOffValues);
String[] from = { "project_id"};
int[] to = { R.id.tv_address};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), listOffValues, R.layout.lv_gps_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(final SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object[]> hm = (HashMap<String, Object[]>) adapter.getItem(i);
final HashMap<String, String> companyDetails = new HashMap<String, String>();
Object po_ids = (Object[]) hm.get("project_id");
Object[] ret=(Object[]) hm.get("project_id");
Integer number = ((Integer) hm.get("project_id")[0]);
String projectId = ((String) hm.get("project_id")[1]);
companyDetails.put("project_id",projectId);
adapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String listName;
HashMap<String, String> hmDownload = new HashMap<String, String>();
String l = companyDetails.get("project_id");
Intent myIntent = new Intent(MainActivity.this, YardActivity.class);
myIntent.putExtra("id", Long.toString(id));
myIntent.putExtra("position", Integer.toString(position)); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
});
}
progress.dismiss();
Log.d("/****","Data from odoo is finished");
}
}
Here is the output when i debug:
http://i62.tinypic.com/24esx87.png
I updated my example where you can see that I can get the name of the project out of the list. But when I try to visulize that It print that java.lang string. Is your solution the only solution? When I hit on an item in my listview I get the projectId that I hit, so why it dont what to visiulize the string value?
HashMap<String, Object[]> hm = (HashMap<String, Object[]>)adapter.getItem(i);
change to
HashMap<String, MyModel[]> hm = (HashMap<String, MyModel[]>) adapter.getItem(i);
where my model is a class you create that describe your data,
take a look at ObjectItem.java
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html

How to clear all items in a ListView while using List Adapter onTextChange?

I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back

Populate a ListView from an ArrayList<HashMap<String, String>>

I have an ArrayList<HashMap<Contact, Name>> and I want to populate a ListView with it. Here's my attempt (which is not working)
ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String, String>>();
// Array of strings "titulos"
String titulos[] = { "Dolar (Transferencia)", "Euro (Transferencia)",
"Dolar (Efectivo)", "Euro (Efectivo)", "Dolar (cúcuta)",
"Euro (cucuta)" };
try {
JSONObject json = result; // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
JSONObject root = json.getJSONObject("root");
JSONArray items = root.getJSONArray("item");
int j = 0;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String key = item.getString("key");
String mount = item.getString("mount");
if (key.equals("TS") || key.equals("TE") || key.equals("EE")
|| key.equals("CE") || key.equals("ES")
|| key.equals("CS")) { // i did this since i only need the items where the key is equal to TS, TE, EE, CE, ES or CS.
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", String.valueOf(i));
map.put(key, mount);
lista.add(map);
System.out.println(titulos[j] + "(" + key + "). BsF = " + mount); // just for debugging purposes
j++; // add 1 to j if key is equal to TS, TE, EE, CE, ES or CS. In this way i can associate the two arrays (item and titulos)
}
}
ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view
lv.setAdapter(new ArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, lista)); // set adapter to the listview (not working)
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
That last line is throwing an error in eclipse:
The constructor ArrayAdapter<String>(Context, int, ArrayList<HashMap<String,String>>) is undefined
I've tried everything but I still couldn't make it work, could you help me please?
Thanks in advance.
PS: Full source: https://gist.github.com/4451519
Just use a SimpleAdapter.
String[] from = new String[] { /* all your keys */};
int[] to = new int[] { /* an equal number of android.R.id.text1 */};
ListAdapter adapter = new SimpleAdapter(contexto, lista, android.R.layout.simple_list_item_1, from, to);
It would be simple (and more logical) if each item of your list contained a similarly formed object, not a different key every time.
I would replace
map.put(key, mount);
by
map.put("key", key);
map.put("value", mount);
and then the from and to are simply:
String[] from = new String[] { "value" };
int[] to = new int[] { android.R.id.text1 };
You'll have to create your own adapter if you really want to pass the whole list of HashMaps, as the ArrayAdapter<String> expects the third parameter in your case to be of the type List<String>.
You should follow #Tomislav Novoselec's suggestion in the comments, and create a List<String> from the HashMap values.
You need to use your own CustomArrayAdapter like below and consume this class in your code.
public class CustomArrayAdapter extends BaseAdapter {
private JSONArray jsonArray = null;
public ImageAdapter(Context c, JSONArray jsonArray) {
context = c;
this.jsonArray = jsonArray;
}
public int getCount() {
return jsonArray.length();
}
public View getView(int position, View convertView, ViewGroup parent) {
//DO YOUR CODE HERE
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_view, null);
}else{
//Set values for your listview on the list item.
convertView.findViewById(R.id.someID).setText("GetJSONTEXT");
}
}
}
MY SUGGESTION FOR YOUR MAINACTIVITY
package com.kustomrtr.dolarparalelovenezuela;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.loopj.android.http.*;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.1.5/dolar.json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
try {
JSONObject json = new JSONObject(response); // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
JSONObject root = json.getJSONObject("root");
JSONArray items = root.getJSONArray("item");
ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view
lv.setAdapter(new CustomArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, items));
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You have to create you own Custom Adapter by Extending BaseAdapter in Android. Then you can set your custom adapter to the ListView by using the setAdapter method of the list view.
For your reference of please see the below small example of BaseAdapter. You need to pass your ArrayList< HashMaP > to the Adapter.
http://jimmanz.blogspot.in/2012/06/example-for-listview-using-baseadapter.html
Hope this helps.

Categories

Resources