I'm attempting to set an array in the ImageAdapter (pics) equal to JSON contents in the arrayList called mComments. I cannot seem to accomplish this by using a toArray() method on the mComments and also typecasting didn't work. I'm trying to use the JSON content to set the images in the GridView instead of the hard-coded resources. See my ImageAdapter class below and also the relevant calling class. Full classes available upon request and here is the JSON URL if that helps: https://shipstudent.com/complaint_desk/androidImageFetch.php. Please let me know if you need more information.
ImageAdapter:
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context=c;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView iv;
if (convertView == null) { // if it's not recycled, initialize some attributes
iv = new ImageView(context);
iv.setLayoutParams(new GridView.LayoutParams(350,350));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setPadding(8, 8, 8, 8);
} else {
iv = (ImageView) convertView;
}
iv.setImageResource(pics[position]);
return iv;
}
public Integer[] pics={
R.drawable.menu ,R.drawable.dog,
R.drawable.favorites,R.drawable.pmlimage,
R.drawable.progress,R.drawable.hearsay,
// R.drawable.sample_6,R.drawable.sample_7
};
}
Calling Class:
private JSONArray mComments = null;
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
categoryList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
// when parsing JSON stuff, we should probably
// try to catch any exceptions:
try {
// I know I said we would check if "Posts were Avail." (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String comment = c.getString(TAG_COMMENT);
String filename = c.getString(TAG_FILENAME);
String IDUser = c.getString(TAG_IDUser);
System.out.print(comment);
System.out.print(filename);
System.out.print(IDUser);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COMMENT, comment);
map.put(TAG_FILENAME, filename);
map.put(TAG_IDUser, IDUser);
// adding HashList to ArrayList
categoryList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
// ListAdapter adapter = new SimpleAdapter(this.getActivity(), categoryList,
// R.layout.categories_list, new String[] { TAG_CATEGORY_NAME }, new int[] { R.id.title });
//
// // I shouldn't have to comment on this one:
// setListAdapter(adapter);
//imageAdapter.pics = (Integer[]) categoryList.clone();
System.out.print(categoryList.toString());
}
Related
I have a DataList jsonarray with a jsonobject as Data , the string has different values which is seprated by character "´" , the values are respectively corresponding
to the "Headers" object , i need to display this in a recycler view as SL.,InNo,etc., how can i achieve this by spliting the characher "´" which gives a string array,i
furthur need to display this data from adapter to different textview, any ideas would be really helpful.
"MainData": {
"Headers": "SL.>´InNo. - Supp<´InvNo.<´Date^´Value>´Disc.>´Rate´Others>´Amount>",
"FieldSeparator": "´",
"DataList": [
{
"Data": "1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´",
"DataInputType": 1
},
{
"Data": "2. ´19111 / Textiles´7041´01-sep-2019´8,895.00´0.00´444.75´173.25´513.00´",
"DataInputType": 1
},
You have multiply approaches in order to preform that task,
first of all extract the needed information into string then you can use
replace function to change '`' into '' read more about string handling in java
extraction:
Converting JSON data to Java object
replace function: How to remove special characters from a string?
Assuming you want your data to be in a usable structure like that.
[
{
"SL" : "1"
"InNo": "19910"
...
},
{
"SL" : "2"
"InNo": "19911"
...
}
]
As others have mentioned the idea is to use the split("´") the rest are how you want to structure you data.
Use a class or a method to create the above structure:
public class DefineData {
// Assuming the below desired structure
// [
// {
// SL : 1
// InNo: 19910
// ...
// },
// {
// SL : 2
// InNo: 19911
// ...
// }
//
// ]
private ArrayList<HashMap<String, String>> dataArrayList;
// Helper method please use your own JsonObject instead of that method
public JSONObject getJsonObject() {
String json = "{ \"MainData\":{ \"Headers\":\"SL.>´InNo. - Supp<´InvNo.<´Date^´Value>´Disc.>´Rate´Others>´Amount>\", \"FieldSeparator\":\"´\", \"DataList\": [ { \"Data\": \"1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´\", \"DataInputType\":1 }, { \"Data\":\"2. ´19111 / Textiles´7041´01-sep-2019´8,895.00´0.00´444.75´173.25´513.00´\", \"DataInputType\":1 }] } }";
try {
JSONObject obj = new JSONObject(json);
return obj;
} catch (Throwable tx) {
Log.e("TAG", "getJsonObject: ", tx.getCause());
throw new RuntimeException("");
}
}
public DefineData() throws JSONException {
dataArrayList = new ArrayList<>();
// Assuming everything is a String for now
JSONObject obj = getJsonObject();
JSONObject mainData = obj.getJSONObject("MainData");
String headers = mainData.getString("Headers");
// In your case "´" but it's a good practise to grab that from the JsonObject
String fieldSeparator = mainData.getString("FieldSeparator");
JSONArray dataList = mainData.getJSONArray("DataList");
// Loop through dataList and populate the data map and split the data using the FieldSeparator
String[] headersArray = headers.split(fieldSeparator);
for (int i = 0; i < dataList.length(); i++) {
JSONObject dataJsonObject = dataList.getJSONObject(i);
String dataString = dataJsonObject.getString("Data");
String[] dataArray = dataString.split(fieldSeparator);
// Loop through the dataArray
HashMap<String, String> dataMap = new HashMap<>();
for (int j = 0; j < dataArray.length; j++) {
String dataItem = dataArray[j];
String header = headersArray[j];
dataMap.put(dataItem, header);
}
dataArrayList.add(dataMap);
}
}
public ArrayList<HashMap<String, String>> getDataArrayList() {
return dataArrayList;
}
}
Your Adapter for the RecyclerView should look similar to that:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<HashMap<String, String>> dataArrayList;
public MyAdapter(ArrayList<HashMap<String, String>> dataArrayList) {
this.dataArrayList = dataArrayList;
}
#Override
public int getItemCount() {
return dataArrayList.size();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// Your root layout here instead of view..
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_item, parent, false);
// TextView txtView = view.findViewById(R.id.textView);
MyViewHolder vh = new MyViewHolder(view);
// vh.textView = txtView;
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
// The position will be similar to DataList position but this time we have the
// information from the header
HashMap<String, String> key = dataArrayList.get(position);
//String slVal = key.get("SL");
//String inNoVal = key.get("InNo");
// Or simply iterate through them whatever works best
holder.textView.setText("The desired value");
// Do the same for the rest..
}
// VIEW HOLDER
public static class MyViewHolder extends RecyclerView.ViewHolder {
public View view;
public TextView textView;
// Views....
// Pass in your view or layout - RelativeLayout, ConstraintLayout
public MyViewHolder(View view) {
super(view);
this.view = view;
}
}
public ArrayList<HashMap<String, String>> getDataArrayList() {
return dataArrayList;
}
public void setDataArrayList(ArrayList<HashMap<String, String>> dataArrayList) {
this.dataArrayList = dataArrayList;
}
}
Then it should be as simple as:
MyAdapter myAdapter;
RecyclerView recyclerView;
// ...
// ...
DefineData defineData = null;
try {
// Don't forget to pass in the jsonObject you want!!
defineData = new DefineData();
} catch (Exception e) {
Log.e("TAG", "MyAdapter: ", e.getLocalizedMessage());
}
mAdapter = new MyAdapter(defineData.getDataArrayList());
recyclerView.setAdapter(mAdapter);
First get the datalist from the MainData JSON object by converting the JSON to POJO Class object. Then for each Data string in the datalist, split the Data string and store/copy each split value to respective variables (i.e. Sl. No., InNo., etc.).
For splitting the string into an array, use split function of Strings.
String data = "1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´";
String[] dataArray = str.split("´", 0);
I would suggest you create a class named DataClass ( or some other name that suits it) and add all headers as data members. Once you have the dataArray, create a new DataClass object and add it to the recycler view list.
In my application I have an activity named Hospitals that extends an AppCompatActivity and I'm using parse to store my data. In parse I have a table called "Hospitals" with column called "Name"....I'm trying to retrieve the hospital names and display it in a list view for the users....but my code is only retrieving the first row from the table.
This is my code
public class Hospital extends AppCompatActivity {
private static final String Hospitals = "Hospitals";
private static final String HospitalName = "Name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital);
ListView list1 = (ListView)findViewById(R.id.list1);
ParseQuery query = new ParseQuery(Hospitals);{
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
final String[] str = {test.get(x).getString(HospitalName)};
final ArrayAdapter A1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,str);
list1.setAdapter(A1);
}
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Replace code
Problem is you are doing everything inside loop
You can use HashMap<String, String> for multiple column.
List<String> listHospital = new ArrayList<String>();
HashMap<String, String> mapHospital = new HashMap<String, String>();
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
mapHospital.clear();
mapHospital.put("hospitalName", test.get(x).getString(HospitalName));
mapHospital.put("address", test.get(x).getString("addressColumnName"));
mapHospital.put("number", test.get(x).getString("addressColumnNumber"));
list1.add(mapHospital);
}
final ArrayAdapter A1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list1);
list1.setAdapter(A1);
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You must have custom Adapter. if you want key/value means multiple column data
I'm pretty new to Android development, I feel like I have a relatively simple question here and have managed to tie down the more complex parts but overlook the more simple bits. I've setup an ImageAdapter class which handles displaying images into a GridView in another one of my Fragments. Originally I was following a tutorial that simply displayed a list of items in an Array.
I'm using an AsyncTask to populate an ArrayList, and then converting the ArrayList to a standard array that Picasso can deal with when displaying content.
My problem is that the AsyncTask section of my ImageAdapter is just not getting executed, thus my imageArr[] that Picasso uses is just remaining empty.
How can I make sure that the AsyncTask section of my Adapter is actually executed?
I've tried this, but it just doesn't seem to be working and I think I'm a little bit off...
public void onCreate() {
new GetProjects().execute();
}
I've attached my code bellow, any help would be really appreciated!
Note; ServiceHandler is just retrieving the data at the URL and then turning it into a string which can be parsed.
public class ImageAdapter extends BaseAdapter {
//JSON URL
private static String url = "www.myjsonsourceurl.com";
//JSON NODES
private static final String TAG_LOGO = "logopath";
ArrayList<String> imageUrls = new ArrayList<String>();
String[] imageArr = imageUrls.toArray(new String[imageUrls.size()]);
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return imageArr.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public void onCreate() {
new GetProjects().execute();
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).setIndicatorsEnabled(true);
Picasso.with(mContext).setLoggingEnabled(true);
Picasso.with(mContext).load(imageArr[position]).placeholder(R.drawable.ajaxloader).error(R.drawable.imageunavailable).into(imageView);
return imageView;
}
// references to our images
//ASYNC task to get json by making HTTP call
public class GetProjects extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Nothing right now
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray json = new JSONArray(jsonStr);
// looping through All Applications
for (int i = 0; i < json.length(); i++) {
JSONObject p = json.getJSONObject(i);
String logopath = p.getString(TAG_LOGO);
imageUrls.add(logopath);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
You need to call in activity or fragment where list is defined not in adapter like this. move asynctask class to your activity and call it from there.
AsyncTask gives methods
onPreExecute() and onPostExecute() where you can toast message that task is started or completed. And you should call setAdapter() in onPostExecute() of class.
There`s no onCreate method for BaseAdapter which you can override. Execute your code
new GetProjects().execute();
either in contructor or call your onCreate function (I suggest changing its name) manualy from outside of the adapter.
I am trying to populate data from my main activity using the adapter below. When i run the activity the screen remains blanked. I believe it has to do with the ArrayList which is null perhaps. Can someone tell me why my data is not being displayed. am on this bug for three days now :/
public class CopyOfSecondWheelAdapter extends AbstractWheelTextAdapter {
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
public ImageLoader imageLoader;
Convertor main;
public CopyOfSecondWheelAdapter(Context context) {
super(context, R.layout.count_layout, NO_RESOURCE);
setItemTextResource(R.id.country_name);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
ImageView img = (ImageView) view.findViewById(R.id.flag);
imageLoader.DisplayImage(PostList.get(index).getDevise(), img);
System.out.println("get item count:"+getItemsCount() );
TextView text = (TextView)view.findViewById(R.id.lib);
text.setText(PostList.get(index).getQuotite());
return view;
}
#Override
public int getItemsCount() {
return PostList.toArray().length;
}
#Override
protected CharSequence getItemText(int index) {
return PostList.get(index).getDevise().toString();
}
}
UPDATE:
In my Main class i have already an
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
which is populated.
Here is my main class that is my convertor.class
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.convertor);
context = this;
text_devise_two = (TextView)findViewById(R.id.text_spacetwo);
final WheelView country = (WheelView) findViewById(R.id.country);
country.setVisibleItems(10);
country.setViewAdapter(new FirstWheelAdapter(this));
edt_validate = (EditText)findViewById(R.id.edt_validate);
current_type_loc = (TextView)findViewById(R.id.current_type_loc);
refresh_header= (TextView)findViewById(R.id.refresh_header);
//set current time
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
String formattedDate = df.format(c.getTime());
refresh_header.setText(getResources().getString(R.string.mise_a_jour)+" "+formattedDate);
image_one = (ImageView)findViewById(R.id.image_one);
image_two = (ImageView)findViewById(R.id.image_two);
final WheelView currency = (WheelView) findViewById(R.id.currency);
currency.setVisibleItems(10);
currency.setViewAdapter(new CopyOfSecondWheelAdapter(this));
country.addChangingListener(new OnWheelChangedListener() {
#Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!scrolling) {
}
}
});
country.addScrollingListener( new OnWheelScrollListener() {
#Override
public void onScrollingStarted(WheelView wheel) {
scrolling = true;
}
#Override
public void onScrollingFinished(WheelView wheel) {
scrolling = false;
//1.
wheelSelector(country.getCurrentItem());
}
});
currency.addScrollingListener( new OnWheelScrollListener() {
#Override
public void onScrollingStarted(WheelView wheel) {
scrolling = true;
}
#Override
public void onScrollingFinished(WheelView wheel) {
scrolling = false;
//1.
secondWheel(currency.getCurrentItem());
}
});
country.setCurrentItem(1);
currency.setCurrentItem(3);
new loadingTask().execute();
}
/*1. Change currency */
public void wheelSelector (int id){
if (id==0){
current_type_loc.setText("EUR");
image_one.setBackgroundResource(R.drawable.eur);
}else {
current_type_loc.setText("USD");
image_one.setBackgroundResource(R.drawable.usd);
}
}
class loadingTask extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(Convertor.this, "", "Chargement en cours..", true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
doc = Jsoup.parse(getxml,"", Parser.xmlParser());
taux = doc.select("taux");
for (int i = 0; i < taux.size(); i++) {
PostList.add(new convertor_pst(taux.get(i).getElementsByTag("devise").text().toString(),
taux.get(i).getElementsByTag("dateCours").text().toString(),
taux.get(i).getElementsByTag("libelle").text().toString(),
taux.get(i).getElementsByTag("quotite").text().toString(),
taux.get(i).getElementsByTag("fixing").text().toString()));
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
envelope =
"soap content"
String requestEnvelope=String.format(envelope, "28-03-2013","true");
getxml = Util.CallWebService(URL,SOAP_ACTION,requestEnvelope);
System.out.println(getxml);
return null;
}
}
public void secondWheel(int index){
text_devise_two.setText(PostList.get(index).getDevise());
edt_validate.setText(" "+PostList.get(index).getFixing());
}
/*
*
* (non-Javadoc)
* #see android.app.Activity#onPause()
* check if activity go to background
*/
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Util.isApplicationBroughtToBackground(Convertor.this)==true){
startActivity(new Intent(Convertor.this,Compte.class));
}
}
}
This is the original wheel adapter class
public class CopyOfSecondWheelAdapter extends AbstractWheelTextAdapter {
ArrayList<convertor_pst> PostList;
public ImageLoader imageLoader;
// Countries names
private String countries[] =
new String[] {"EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD"};
// Countries flags
private int flags[] = new int[] {R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd};
/**
* Constructor
*/
Convertor main;
public CopyOfSecondWheelAdapter(Context context) {
super(context, R.layout.count_layout, NO_RESOURCE);
setItemTextResource(R.id.country_name);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
ImageView img = (ImageView) view.findViewById(R.id.flag);
img.setImageResource(flags[index]);
TextView text = (TextView)view.findViewById(R.id.lib);
text.setText("code");
return view;
}
#Override
public int getItemsCount() {
return countries.length;
}
#Override
protected CharSequence getItemText(int index) {
return countries[index];
}
}
As far as I understand
currency.setViewAdapter(new CopyOfSecondWheelAdapter(this));
this line creates the adapter, but you fill it up at this line :
new loadingTask().execute();
which is after, so you must call
yourAdapter.notifyDataSetChanged();
on your adapter to update the data.
Android Developer Help says
notifyDataSetChanged()
Notifies the attached observers that the
underlying data has been changed and any View reflecting the data set
should refresh itself.
So in your case you must
create an adapter (yourAdapter = new CopyOfSecondWheelAdapter ....)
assign it with the setViewAdater (WheelView.setViewAdapter(yourAdapter))
in the "postExecute" of your async task, do a call with yourAdapter.notifyDataSetChanged();
By the way, I am not sure to understand what you are doing, but in case you need to have a set of data displayed at two different locations, you don't need to duplicate (create a copy). The two list display can share the same adapter.
UPDATE
You have done an update to your question and I answer to that update :
In the original adapter the countries are not loaded in the async task. So when you assign the adapter, the display show the correct values because they are present in the adapter at the moment you assign it.
In your case, you load the values in the async task. When you create the adapter it is empty and you assign it empty, so the display shows an empty list. You should notify your display of the data change.
So in the original, no need to notify as the data is the correct one at the time of assignment. In your case you have to implement a notifyDataSetChanged(). Or change the type of adapter you are extending.
If I see it correctly, you have 2 times a variable name PostList which confuses you. One is created in your activity and one in your adapter and ass you call add() to the variable of your activity, the list in your adapter never gets the items.
Create a setter for the list in your adapter and set the list in your onPostExecute().
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.