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.
Related
Please help me out
I am fetching image from a JSON API to my android app for each item in my arraylist. The images are fetching correctly, but instead of setting only the image that is meant for each list item, it is looping and interchanging all the images in all the list on one item and all the list items respectively, thereby making the image in each list item to be changing to different images in seconds.
See the JSON file
{ "data":[
{
"sno":1,
"id":"3",
"title":"This Is Great Again",
"desc":"The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.The details of...",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/145277f3d0499ee8e0dafbac384ca9b4.jpg",
"date_added":"2017-10-12 10:26PM",
"no_comment":3,
"comments":[ ]
},
{
"sno":2,
"id":"6",
"title":"Money Makes The World Go Round",
"desc":"On this realm, nothing works without money. You need to get some of it or else you'll be grounded.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/546a4c29a94f3d70ae9a075ce8afcc6b.jpg",
"date_added":"2018-02-18 10:06AM",
"no_comment":0,
"comments":[ ]
},
{
"sno":3,
"id":"7",
"title":"No One Is Destined To Be Poor",
"desc":"You will not be poor.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/8f19b9cebd1ca4dec74fafcfe23ae0f0.jpg",
"date_added":"2018-02-18 01:03PM",
"no_comment":0,
"comments":[ ]
},
{
"sno":4,
"id":"8",
"title":"What Is Your Money?",
"desc":"Understand the true definition of your money.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/49b35ffb5cabcb7e01dab2d452ec6025.jpg",
"date_added":"2018-02-18 01:30PM",
"no_comment":0,
"comments":[ ]
},
Here is my code for fetching each item and the image
private static ArrayList<nauget> extractFeatureFromJson(String freeNaugetJson) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(freeNaugetJson)) {
return null;
}
ArrayList<nauget> naugets = new ArrayList<nauget>();
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;
}
Here is my custom adapter code where am setting the image and its text data for each list item.
public class NaugetAddapter extends ArrayAdapter<nauget> {
ArrayList<nauget> naugets;
private nauget currentNauget;
private ImageView naugetImage;
private TextView naugetTitle;
private TextView naugetBody;
private TextView commentCount;
public NaugetAddapter(#NonNull Context context, ArrayList<nauget> naugets) {
super(context, 0, naugets);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if the convert view is null and inflate the view
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.free_nauget_item, parent, false);
}
currentNauget = (nauget) getItem(position);
//find the nauget title textView and set the text
naugetTitle = (TextView) convertView.findViewById(R.id.nauget_title);
naugetTitle.setText(currentNauget.getNauget_title());
//find the nauget body textView and set the text
naugetBody = (TextView) convertView.findViewById(R.id.nauget_body);
naugetBody.setText(currentNauget.getNauget_body());
//set the nauget total comment count
commentCount = (TextView) convertView.findViewById(R.id.comment_count);
commentCount.setText(currentNauget.getNaugetTotalComments());
//set the comment text
TextView commentText = (TextView) convertView.findViewById(R.id.comment_text);
commentText.setText(currentNauget.getNaugetCommentText());
//set the nauget image
naugetImage = (ImageView) convertView.findViewById(R.id.nauget_image);
new DownloadImageTask().execute(currentNauget.getImageUrl());
//set the share icon
ImageView shareIcon = (ImageView) convertView.findViewById(R.id.share_icon);
shareIcon.setImageResource(currentNauget.getNaugetShareIcon());
//set share functionality on the share icon
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
shareIntent.putExtra(Intent.EXTRA_TEXT,
naugetTitle.getText()
+ "\n" + naugetBody.getText()
+ "\n" + naugetImage.getDrawable());
startActivity(getContext(), Intent.createChooser(shareIntent, "Share via"), null);
}
});
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// mLoadingIndicator.setVisibility(View.VISIBLE);
}
protected Bitmap doInBackground(String... urls) {
Bitmap image = null;
HttpURLConnection urlConnection = null;
try {URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != 200) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.e("Error", e.getMessage());
e.printStackTrace();
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
// mLoadingIndicator.setVisibility(View.INVISIBLE);
naugetImage.setImageBitmap(result);
}
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<nauget> filteredResults = new ArrayList<>();
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};
}
void setFilter(ArrayList<nauget> listItem){
naugets = new ArrayList();
naugets.addAll(listItem);
notifyDataSetChanged();
}
}
This should solve the issue! you are trying everything fine but you have the comment ArrayList inside of a loop getting instantiated each time newly just put it before the outer loop as I did here and the error should go! TRY IT
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
//put it here so you won't get a new array for each comment in the loop
**ArrayList<Comment> comments = new ArrayList<Comment>();**
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
//here after every comment check its making a new comment ArrayList for each comment and filling it out so this can be the cause of the bug! bcz its in the loop
// ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;
I have two spinners the first one for month and the second for years.I am trying to call a method send_date() if on Item Selected is called for any of the 2 spinners.
So I have two problems:- 1)send_date() gets called twice the first
time it gets the correct data as expected but the 2nd time it returns
a empty array. 2)When I select another month or year the old data does
not get removed that is the list does not refresh.
The following is my code for on Item Selected :-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int i = spinYear.getSelectedItemPosition();
selected_year = years.get(i);
Log.d("Selection Year",selected_year);
tv_year.setText(selected_year);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
And for the month spinner:-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int j = spinMonths.getSelectedItemPosition();
selected_month = Months[j];
Date date = null;
try {
date = new SimpleDateFormat("MMMM").parse(selected_month);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
tv_month.setText(String.valueOf(cal.get(Calendar.MONTH)+1));
Log.d("Selection Month",selected_month);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
On response I call the following method for populating the list view with data:-
public void showBS(String response)
{
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
bl = new BS_allList(getActivity(),ParseBS_all.doc_no,ParseBS_all.balance,ParseBS_all.total,ParseBS_all.vat,ParseBS_all.profit);
lv_bsall.setAdapter(bl);
}
This is the code for the send_date method:-
//This method is used to send month and year
private void send_date() throws JSONException {
final String year = tv_year.getText().toString();
final String month = tv_month.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, SEND_DATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//display.setText("This is the Response : " + response);
String resp = response.toString().trim();
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
// bl.clear();
lv_bsall.setAdapter(bl);
bl.notifyDataSetChanged();
}else
{
Toast.makeText(getContext(), "Response" + response, Toast.LENGTH_LONG).show();
Log.d("RESPONSE for date", response.toString().trim());
showBS(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
GlobalClass gvar = (GlobalClass) getActivity().getApplicationContext();
String dbname = gvar.getDbname();
Map<String, String> params = new HashMap<>();
params.put(KEY_DBNAME, dbname);
params.put(KEY_MONTH, month);
params.put(KEY_YEAR,year);
return params;
}
};
RequestQueue requestQ = Volley.newRequestQueue(getContext());
requestQ.add(stringRequest);
}
Adapter code for list view.
public class BS_allList extends ArrayAdapter<String>
{
private String[] doc_no;
private String[] balance;
private String[] total;
private String[] vat;
private String[] profit;
private Activity context;
public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
{
super(context, R.layout.bs_list_all, doc_no);
this.context =context;
this.doc_no= doc_no;
this.balance = balance;
this.total = total;
this.vat=vat;
this.profit = profit;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
tv_docNo.setText(doc_no[position]);
tv_balance.setText(balance[position]);
tv_tot.setText(total[position]);
tv_vat.setText(vat[position]);
tv_pf.setText(profit[position]);
return listViewItem;
}
}
Also note that I have set the spinner to point to the current month and year so the first time it works properly.
I am new to programming so any help or suggestion is appreciated.Thank you.
Hi #AndroidNewBee,
As per our discussion made following changes in your code and you will get proper output and it will resolve your issues.
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
bl = new BS_allList(getActivity(),{""},{""},{""},{""},{""});
lv_bsall.setAdapter(bl);
}
And second is check validation as below,
try {
if((selected_year != null & selected_year.length > 0 ) & (tv_month.getText().toString() != null & tv_month.getText().toString().length > 0))
{
send_date();
}
} catch (JSONException e) {
e.printStackTrace();
}
First you shouldn't be using so many String[], instead wrap them in a class
Class BSDataModel{
private String doc_no;
private String balance;
private String total;
private String vat;
private String profit;
//getters and setters
}
Now the reponse result should be added as in ,it returns List<BSDataModel>
List<BSDataModel> reponseList = new ArrayList<>();
//for example adding single response
for(int i=0;i<jsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(jsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(jsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
BS_allList.java
public class BS_allList extends ArrayAdapter<BSDataModel>
{
private List<BSDataModel> bsList;
private Activity context;
public BS_allList(Activity context,List<BSDataModel> bsList)
{
super(context, R.layout.bs_list_all, bsList);
this.context =context;
this.bsList = bsList;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
BSDataModel bsData = bsList.get(position);
tv_docNo.setText(bsData.getDoc());
tv_balance.setText(bsData.getBalance());
tv_tot.setText(bsData.getTot());
tv_vat.setText(bsData.getVat());
tv_pf.setText(bsData.getPF());
return listViewItem;
}
}
Now in your class
BS_allList bl = new BS_allList(getActivity(),responseList);//which you got above
After receiving new Response
// remove old data
responseList.clear(); // list items in the sense list of array used to populate listview
if(newresponseArray.size() > 0){
for(int i=0;i<newjsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(newjsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(newjsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
}
//refresh listview
bl.notifyDataSetChanged();
Try this way,
1. adapter.clear();
2. Add/Remove your list Items.
3. listview.setAdapter(adapter);
4. adapter.notifyDatasetChanged();
this procedure should work.
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());
}
I am using this code to get data from JSON.
public class ShowContacts extends ListActivity{
private static String url = "http://192.168.0.103/contacts.json";
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_NAME = "name";
private static final String TAG_IMAGE = "image";
JSONArray contacts = null;
int index = 0;
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showjson);
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_NAME, name);
contact.put(TAG_IMAGE, image);
contactList.add(contact);
}
} catch (JSONException e){e.printStackTrace();}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String[] from = { TAG_NAME, TAG_IMAGE };
int[] to = { R.id.name, R.id.image };
ListAdapter adapter = new SimpleAdapter(
ShowContacts.this, contactList, R.layout.list_item, from , to );
setListAdapter(adapter);
}
}
}
I want to get the name and image from JSON. I am getting the name and it is displaying on the list, but I can't get the image. This is my JSON:
{
"contacts": [
{
"name": "John Smith",
"image": "http://192.168.0.103/image1.png"
},
{
"name": "John Wayne",
"image": "http://192.168.0.103/image2.png"
}
]
}
I think it is not working because the image is online and the it tries to add it as Drawable. I am not sure how to do this. Is there any way?
You are supposed to download the image using the LazyLoading and load that into the ImageView. You can not directly load the image just simply parsing and setting url into ImageView.
Use the Concept of LazyLoading or Universal ImageLoader
Check the simple demostration of Loading Image from URL
1)you can use Universal ImageLoader to download image from specific URL and Disply in to your List.
you do not use direct imageURL to show it in list item
please check this universal image loader reference link
public class ItemImagesAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> contactList;
private ImageLoader iml;
public ItemImagesAdapter(Context ctx, ArrayList<String> image_paths) {
context = ctx;
contactList = image_paths;
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(activity).build();
ImageLoader.getInstance().init(config);
iml = ImageLoader.getInstance();
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Object getItem(int position) {
return contactList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_image, parent, false);
}
String imagepath = contactList.get(position).getImagePaths();
ImageView image = (ImageView) convertView.findViewById(R.id.image1);
TextView tv = (TextView) convertView.findViewById(R.id.text1);
tv.setText(contactlist.get(position).getText);
iml.displayImage(imagepath, image);
return convertView;
}
}
inside onPostExecute()
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ItemImagesAdapter adapter = new ItemImagesAdapter(getAppicationContext(), contactlist);
listViewobj.setAdapter(adapter);
}
call this from you mainactivity. i hope you know how to set to adapter..
hope this helps you
One and the best method for downloading images from server is Android Query. you can download upto 5k images without any memory error.
Download Android query jar from Here and put in libs folder of your project.
AQuery aq = new AQuery(_scontext); // Android query object
ImageView _imageObject= (ImageView) itemView.findViewById(R.id.product_image); // your imageview onbject
// and using below code you can set the image in imageview.
aq.id(_imageObject).image("image url as 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.