List have below declaration
private ArrayList<HashMap<String,String>> result=new ArrayList<HashMap<String, String>>();
Sample data:-
[{Minutes=25, Catagory=Morning, Hour=11, medName=hdodu, ImgPath=/storage/emulated/0/H/hdodu.jpg},
{Minutes=25, Catagory=Night, Hour=3, medName=hdodu, ImgPath=/storage/emulated/0/H/hdodu.jpg},
{Minutes=33, Catagory=Afternoon, Hour=16, medName=jsindj, ImgPath=/storage/emulated/0/H/jsindj.jpg}]
How do I print data of list using model class
Model.java
public class ListMedicine {
private String Medicine_name;
private String Reminder_hour;
private String Reminder_min;
private String Reminder_catagory;
private String Medicine_image_path;
public void setMedicine_name(String medicine_name)
{
this.Medicine_name=medicine_name;
}
public String getMedicine_name()
{
return Medicine_name;
}
public void setReminder_hour(String reminder_hour)
{
this.Reminder_hour=reminder_hour;
}
public String getReminder_hour()
{
return Reminder_hour;
}
public void setReminder_min(String reminder_min)
{
this.Reminder_min=reminder_min;
}
public String getReminder_min()
{
return Reminder_min;
}
public void setReminder_catagory(String reminder_catagory)
{
this.Reminder_catagory=reminder_catagory;
}
public String getReminder_catagory()
{
return Reminder_catagory;
}
public void setMedicine_image_path(String medicine_image_path)
{
this.Medicine_image_path=medicine_image_path;
}
public String getMedicine_image_path()
{
return Medicine_image_path;
}
}
MedicineAdaptor.java
Below is the code for adaptor class in which I am using recyclerView to list down the data.
public class MedicineAdaptor extends RecyclerView.Adapter<MedicineAdaptor.ViewHolder> {
List<ListMedicine> items;
DbHelper dbHelper;
Context context;
public MedicineAdaptor(Context context, List<ListMedicine> items)
{
super();
dbHelper=new DbHelper(context);
Log.i("In the MedicineAdaptor","Constructor");
this.context=context;
this.items=items;
}
#Override
public MedicineAdaptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i("Entering","onCreateViewHolder");
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.medicine,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MedicineAdaptor.ViewHolder holder, int position) {
Log.i("Entering","onBindViewHolder");
ListMedicine listMedicine=items.get(position);
Log.i("Medicine Name", listMedicine.getMedicine_name());
Log.i("Medicine Hour", listMedicine.getReminder_hour());
Log.i("Medicine Min",listMedicine.getReminder_min());
Log.i("Medicine Catagory", listMedicine.getReminder_catagory());
holder.MedicineName.setText(listMedicine.getMedicine_name());
holder.ReminderHour.setText(listMedicine.getReminder_hour());
holder.ReminderMin.setText(listMedicine.getReminder_min());
holder.ReminderCatagory.setText(listMedicine.getReminder_catagory());
}
#Override
public int getItemCount() {
Log.i("Size is", Integer.toString(items.size()));
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView MedicineName, ReminderHour,ReminderMin, ReminderCatagory;
public ImageView MedicineThumbnail;
public ViewHolder(View itemView) {
super(itemView);
MedicineName=(TextView) itemView.findViewById(R.id.medicine_name);
ReminderHour=(TextView) itemView.findViewById(R.id.reminder_hour);
ReminderMin=(TextView) itemView.findViewById(R.id.reminder_hour);
ReminderCatagory=(TextView) itemView.findViewById(R.id.medicine_catagory);
MedicineThumbnail=(ImageView) itemView.findViewById(R.id.medicine_icon);
}
}
}
Database Fetch Code:
public ArrayList<ListMedicine> fetchReminder(String date)
{
ArrayList<ListMedicine> array_list=new ArrayList<ListMedicine>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery("select * from reminders",null);
c.moveToFirst();
try {
while(c.isAfterLast() == false){
Log.i("Inside the fetch query","yes");
ListMedicine listMedicine=new ListMedicine();
listMedicine.setMedicine_name(c.getString(c.getColumnIndex("medName")));
array_list.add(listMedicine);
c.moveToNext();
}
}catch (Exception e)
{
e.printStackTrace();
}
return array_list;
}
Code of the calling Activity
private void showData() {
ArrayList<ListMedicine> list=new ArrayList<ListMedicine>();
Log.i("Show Data function","Yes");
try {
JSONArray arr = new JSONArray(result);
Log.i("Length is ",Integer.toString(arr.length()));
for(int i=0;i<arr.length(); i++){
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(bean.getMedicine_name());
// at last add this into your list
Log.i("Bean ans", bean.toString());
list.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter=new MedicineAdaptor(this,list);
reminderList.setAdapter(adapter);
}
private void getData(String fetchDate) {
//ArrayList<String> result=new ArrayList<String>();
result=db.fetchReminder(fetchDate);
Log.i("Result",result.toString());
}
For me I am using Gson:
YourModel obj = gson.fromJson(yourStringJson, YourModel.class);
You can read more about Gson here:
https://sites.google.com/site/gson/gson-user-guide
Probably, you could use Gson, Jackson, Moshi etc...
They could be parsing a Java model.
GitHub Links - Gson , Jackson , Moshi
Change your
ArrayList<HashMap<String,String>> result=new ArrayList<HashMap<String, String>>();
into
ArrayList<ListMedicine> result=new ArrayList<ListMedicine>();
Do it like this
try {
JSONArray arr = new JSONArray(result);
for(int i=0;i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(obj.getString("medName"));
.
.
.
// at last add this into your list
result.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this out..
try {
for(int i=0;i<list.size(); i++){
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(list.get(i).getString("medName"));
.
.
.
// at last add this into your list
result.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
My question is similar to this Implementing Search Filter in Adapter Class which parses a json array (without using pojo)
but I would like to try to struggle the problem differently. I have a list of elements that must be filtered based on a condition and once this condition is verified, I want to retrieve the elements that verify it from the json array. In this example, I filtered the elements based on their name, and in the setContentValue () I would set the code and the hex string taking only those elements that have that name, otherwise during filtering the name has a different index from the code and the hex strings. How could I do that?
Fragment
public class ColorViewFragment extends Fragment {
private RecyclerView recyclerView;
private JSONArray json;
private ColorListAdapter adapter;
private EditText editColor;
#Nullable #Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.color_list, container, false);
this.recyclerView = view.findViewById(R.id.recyclerView);
/*
try {
this.recyclerView.setAdapter(new ColorListAdapter(this.json));
} catch (JSONException e) {
e.printStackTrace();
}
*/
try {
adapter = new ColorListAdapter(json);
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
this.recyclerView.setLayoutManager(layoutManager);
//
editColor = view.findViewById(R.id.editText);
editColor.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ColorViewFragment.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
public void setJSON(JSONArray newJson){
this.json = newJson;
}
Adapter
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
this.colorList = json;
for (int i=0;i<json.length();i++){
//colorListFiltered.add((colorList.getString(i)));
colorListFiltered.add(json.getJSONObject(i).getString("Name"));
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorCodeText;
private TextView colorNameText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index));
//this.colorNameText.setText(((JSONObject) colorList.get(index)).getString("Name"));
this.colorCodeText.setText(((JSONObject) colorList.get(index)).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(((JSONObject) colorList.get(index)).getString("HexString")));
}
}
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrColorList = new ArrayList<>();
for (int i = 0; i < colorList.length(); i++) {
try {
arrColorList.add(colorList.getJSONObject(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrColorList;
Result.count = arrColorList.size();
return Result;
}
/*if(constraint.length() == 0 ){
Result.values = colorList;
Result.count = colorList.length();
return Result;*/
else {
List<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.length(); i++) {
try {
filterableString = (colorList.getJSONObject(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
I am near solution, list loads and get filtered, but when I delete word, I get a ClassCastException: String cannot be cast to JSONObject (in setContentValue).
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
for(int i=0; i<json.length(); i++) {
JSONObject jsonObj = json.getJSONObject(i);
colorList.add(jsonObj);
colorListFiltered = colorList;
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorNameText;
private TextView colorCodeText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(final int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString")));
}
}
//filtro su Name
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrNameList = new ArrayList<>();
for (int i = 0; i < colorList.size(); i++) {
try {
arrNameList.add(colorList.get(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrNameList;
Result.count = arrNameList.size();
return Result;
}
else {
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<JSONObject>) results.values;
notifyDataSetChanged();
}
}
}
You use colorListFiltered for names but you use colorList for hex codes in setContentValue. First two lists are same but when you filter colorListFiltered they are getting different.
Change this,
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
to
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
and your performFiltering
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
setContentValue:
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString"));
}
i have listview that changes according to the number i type in edittext, the list doesn't change when i type another number and keeps the same items from the previous number typed.
here is the adapter:
public class ElectorListAdapter extends BaseAdapter{
private Context activity;
private LayoutInflater inflater;
private List<Electors> DataList;
private ArrayList<Electors> arraylist=null;
// private ItemFilter mFilter = new ItemFilter();
public ElectorListAdapter(Context activity, List<Electors> electors) {
this.activity = activity;
this.DataList = electors;
this.arraylist = new ArrayList<Electors>();
this.arraylist.addAll(electors);
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.elector_info_cell_list, null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView status = (TextView)convertView.findViewById(R.id.status);
Electors m = DataList.get(position);
//97697691
name.setText(m.getName());
status.setText(m.getStatus().toString());
return convertView;
}
}
and here is the implantation in the MainActivity:
adapter = new ElectorListAdapter(this, list);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
and here where i clear the list:
serial.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
serialno = serial.getText().toString();
if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
getlist();
}else if(serial.getText()==null){
lv.setVisibility(v.GONE);
}
}
}
});
here is the getlist();
public void getlist(){
//list = new ArrayList<>();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://gickuwait-dev.com/electionapi/api/electors";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("SerialNo", serialno.toString().trim());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ElectorResponse> list_response = new ArrayList<ElectorResponse>();
Type listType = new TypeToken<List<ElectorResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
Electors listItemData = new Electors();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setStatus(list_response.get(i).getExpr1());
listItemData.setId(list_response.get(i).getPKID());
if (listItemData.getName().startsWith(classletter)){
list.add(listItemData);
}
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
here where i use filter to filter the list
name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
//Vote.this.adapter.getFilter().filter(theWatchedText.toString());
String text = name.getText().toString().toLowerCase(Locale.getDefault());
// Vote.this.adapter.getFilter().filter(text);
search_model(name.getText().toString());
}
});
private void search_model(String key){
search = new ArrayList<>();
for(int i = 0;i<list.size();i++){
Electors electors = list.get(i);
if(electors.getName().toLowerCase(Locale.getDefault()).startsWith(key)){
search.add(electors);
}
}
adapter = new ElectorListAdapter(this, search);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
}
how can i make it change its values when i type another number, is there something missing in the adapter? thanks in advance
You need to notify the list of changes to the dataset via notifyDatasetChanged()
you should have clear array list when data is changed. Then add your new text to the array list and update it.
arraylist.clear(); //to clear array list
arraylist.add(); //to add new text
adapter.notifyDataSetChanged(); //to notify adapter
if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
// since you removed the item you need to inform the adapter to
//refresh view
adapter.notifyDataSetChanged();
// also as soon as getlist(); gets new list , set that list on adapter and call
// adapter.notifyDataSetChanged();
getlist();
}
Am an newbie to android ...kindly help me guys...I have 2 strings in my sample webservice(Not in an array) and I want to populate it in the listview .I wrote code to populate with a single string.But I don't know how to populate with 2nd strings below to 1st string in listview.Any suggestion will be appreciated.
Here is my complete code
HTTPURLCONNECT
class HttpULRConnect {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2","test");
String line;
while ((line= reader.readLine())!=null) {
sb.append(line+"\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally{
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}}}
Here is my FETCH.java
public class Fetch extends Activity {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch);
new BackTask().execute(url);
}
public class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content =HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonobject = ar.getJSONObject(i);
Flowers flowers = new Flowers();
flowers.setName(jsonobject.getString("NAME"));
flowersList.add(flowers);
}
}
catch (JSONException e){
e.printStackTrace();
}
FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flower_lis_item, flowersList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
}
static class Flowers {
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
private String NAME;
}
public static class FlowerAdapter extends ArrayAdapter<Flowers> {
private ArrayList<Flowers> items;
private Context mContext;
public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
super(context,textViewResourceID,items);
mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Flowers flowers = items.get(position);
if(v==null){
LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.flower_lis_item,null);
}
TextView title = (TextView)v.findViewById(R.id.textView3);
TextView text =(TextView)v.findViewById(R.id.textView2);
if (title != null) {
title.setText(flowers.getName());
text.setText(flowers.getName());
}
return v;
}
}
}
i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
I want to show json data in listview.The json array is shown in
console.but i am not able to set the adapter value in listview.It
always return null value.
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Here category_listview.setAdapter(category_detail); giving null value.
Here model file is
public class Category_Detail_Model{
private String category_title;
private String category_description;
private String category_url;
private String category_image;
public Category_Detail_Model() {
// TODO Auto-generated constructor stub
}
public Category_Detail_Model(String category_title, String category_description, String category_url, String category_image) {
super();
this.category_title = category_title;
this.category_description = category_description;
this.category_url =category_url;
this.category_image = category_image;
}
public String getCategory_Title() {
return category_title;
}
public void setCategory_Title(String category_title) {
this.category_title = category_title;
}
public String getCategory_Description() {
return category_description;
}
public void setCategory_Description(String category_description) {
this.category_description = category_description;
}
public String getCategory_Url() {
return category_url;
}
public void setCategory_Url(String category_url) {
this.category_url = category_url;
}
public String getCategory_Image() {
return category_image;
}
public void setImage(String category_image) {
this.category_image = category_image;
}
}
And here is Adapter class code
public class Category_Dashboard_Adapter extends ArrayAdapter<Category_Detail_Model> {
ArrayList<Category_Detail_Model> category_detail_list;
LayoutInflater vi;
int Resource;
ViewHolder holder;
Typeface font1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/cabin.regular.ttf");
public Category_Dashboard_Adapter(Context context1, int resource1, ArrayList<Category_Detail_Model> objects1) {
super(context1, resource1, objects1);
vi = (LayoutInflater) context1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource1;
category_detail_list = objects1;
}
public View getView(int position1, View convertView1, ViewGroup parent1)
{
// convert view = design
View v = convertView1;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.category_imageview = (ImageView) v.findViewById(R.id.category_details_ivImage);
holder.category_title_holder = (TextView) v.findViewById(R.id.category_detail_title_view);
holder.category_desc_holder = (TextView) v.findViewById(R.id.category_detail_desc_view);
holder.category_url_holder = (TextView) v.findViewById(R.id.category_detail_url_view);
holder.category_title_holder.setTypeface(font1); holder.category_title_holder.setTextSize(16.0f);
holder.category_desc_holder.setTypeface(font1); holder.category_desc_holder.setTextSize(14.0f);
holder.category_url_holder.setTypeface(font1); holder.category_url_holder.setTextSize(10.0f);
// holder.txtCategory.setTypeface(font1); holder.txtCategory.setTextSize(10.0f);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new CategoryDownloadImageTask(holder.category_imageview).execute(category_detail_list.get(position1).getCategory_Image());
holder.category_title_holder.setText(category_detail_list.get(position1).getCategory_Title());
holder.category_desc_holder.setText(category_detail_list.get(position1).getCategory_Description());
holder.category_url_holder.setText(category_detail_list.get(position1).getCategory_Url());
return v;
}
static class ViewHolder {
public ImageView category_imageview;
public TextView category_title_holder;
public TextView category_desc_holder;
public TextView category_url_holder;
}
}
Bacause you set value for the adapter before load json so it give null values:
Try this:
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Or maybe you forget to init your ArrayList before set json data to it. Remember to do this:
ArrayList<String> cate_list = new ArrayList<>();
before you set data for it.
You are parsing your json and adding data to your cate_list after setting the adapter. Add the code for setting data to ListView after you parse your json:
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);