Updating ListView JsonParsing by using Volley - android

I'm getting the json response in logcat window, which does not update the listview. When I set breakpoints in the addcontent() method, first time it doesn't get json,but third time it does(I stepped over few times in the debug perspective window). Below is my Adapter
public class DaibeticRegAdapter extends BaseAdapter implements ListAdapter{
private Context mContext;
//DiagRegPojo pojo = new DiagRegPojo();
DiabeticRegJson drJson = new DiabeticRegJson();
public DaibeticRegAdapter(Context c){
super();
this.mContext = c;
drJson.addContent();
}
#Override
public int getCount() {
return drJson.getName_list().size();
}
#Override
public Object getItem(int position) {
return drJson.getName_list().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = convertView;
if(convertView==null)
{
view = new View(mContext);
view = inflater.inflate(R.layout.diagnostic_reg_list, null);
TextView textView = (TextView)view.findViewById(R.id.diabetic_reg_item);
System.out.println("ArtraYlist Size fom Adapter"+drJson.name_list.size());
System.out.println("Array LIst Options"+drJson.getName_list().get(position));
textView.setText(drJson.getName_list().get(position));
}else{
view =(View)convertView;
}
return view;
}
}
and this is a Java class to parse Json by using volley
public class DiabeticRegJson {
String tag_json_arry = "json_array_req";
String TAG = "TESTING";
String diag_url= Urllist.digRegJson;
private static final String DIAG_REG_NAME = "content";
public static final String savedCookie = "savedCookie";
public ArrayList<String> name_list=new ArrayList<String>();
public ArrayList<String> getName_list() {
return name_list;
}
public void setName_list(ArrayList<String> name_list) {
this.name_list = name_list;
}
public void addContent() {
JsonArrayRequest req = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
//name_list.clear();
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String diagName = person.getString(DIAG_REG_NAME);
name_list.add(diagName);
//pojo.name_list.add(diagName);
Log.i("VOLLEY GETTING URLS", diagName);
Log.i("VOLLEY GETTING URLS FROM ARRAYLIST", name_list.get(i));
}
System.out.println("Size of List " + name_list.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.i("ERROR JSON PARSING", error.getMessage());
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);
}
}
Plz let me know what is missing. Thanks in advance.

I think the problem is that you're not notifying your adapter when new data is retrieved, so it's not updating the UI. To fix it with your existing code you could pass a reference of your BaseAdapter to DiabeticRegJson and call BaseAdapter.notifyDataSetChanged() it from your listener after you set the response.
The other option would be to use an ArrayAdapter, and let that manage your String list for your -- and just add the Strings to the adapter rather than having your request object encapsulate the response.

Related

How to get the original item json array id when autocompletetextview setOnItemClickListener

I have an Autocomplete text view in an Android activity, the view gets data from an arrayadapter from json array. I want to get the original JSON array id when someone selects an option in the autocomplete text view. I am getting the selected string but I wan the actual ID not the selected pos id
Here is my code:
private void LoadSearchData() {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url_class.Search_Dist, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("place_info");
data_list=new String[jsonArray.length()];
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String dis_name=jsonObject1.getString("store_name" );
String dis_id=jsonObject1.getString("store_id");
Toast.makeText(getApplicationContext(),"District name="+dis_name,Toast.LENGTH_SHORT).show();
district_name.add(dis_name);
/// district_whole.add(dis_name+"-"+dis_id);
data_list[i]=dis_name+"-"+dis_id;
}
//spinner_search.setAdapter(new ArrayAdapter<String>(Dashboard.this, android.R.layout.simple_spinner_dropdown_item, district_name));
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(Dashboard.this, android.R.layout.simple_spinner_dropdown_item, district_name));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
OnSelectItemlistner:
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String place_name=autoCompleteTextView.getText().toString();
int txt_indx =i;
//Toast.makeText(getApplicationContext(),"ID="+i,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),"ID="+i,Toast.LENGTH_SHORT).show();
GetstockInfo(place_name);
textViewDist.setText(place_name);
}
});
First of all, this is not recommended. But if you want then give a try
if(data_list.length > i) {
String id = data_list[i].split("-")[1];
}
Suggestion: You should use a custom adapter with custom object to achieve this
Custom model:
class Store {
String name;
String id;
// getter - setter
}
Custom Adapter:
class StoreAdapter extends ArrayAdapter<Store> {
}
Create a POJO class matching the data from your json response
public class Store {
private final String storeId;
private final String storeName;
public Store(String storeId, String storeName) {
this.storeId = storeId;
this.storeName = storeName;
}
public String getStoreId() {
return storeId;
}
public String getStoreName() {
return storeName;
}
}
Construct a list of Store's in your response method:
private final List<Store> stores = new ArrayList<>();
...
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("place_info");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
final String dis_name=jsonObject1.getString("store_name" );
final String dis_id=jsonObject1.getString("store_id");
stores.add(new Store(dis_id, dis_name));
}
// Create your custom adapter here and pass it "List<Store> stores"
autoCompleteTextView.setAdapter(stores);
} catch (JSONException e) {
e.printStackTrace();
}
}
You will also need to create a custom adapter class for your Spinner. There are plenty of tutorials for custom adapters.
go through this link
AutoCompleteTextView detect when selected entry from list edited by user

JSONArray to Android ListView

I am new to programming and my current app gets data from my server for a single data only and input it into textview. But now I have successfully created a php script that encodes JSONArray with multiple values but I dont know how to get the values to the android code via looping and I also dont know how to populate my listview.
Sample JSON
[{"lnumber":"2","violation":"2"},{"lnumber":"2","violation":"No Helmet"}]
PHP Script
$result = array();
$sql = "SELECT lnumber,violation FROM violators WHERE
lnumber='".$lnumber."'";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($lnumber, $violation);
while($stmt->fetch())
{
$temp = [
'lnumber'=>$lnumber,
'violation'=>$violation
];
array_push($result, $temp);
}
echo json_encode($result);
How am I currently getting data from server and displaying it using only textview.
Android Code
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getViolation.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response)
{
try
{
String lnumber;
String violation;
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(getConfig.JSON_ARRAY);
JSONObject violationData = result.getJSONObject(0);
lnumber = violationData.getString(getConfig.KEY_LNUMBER);
violation = violationData.getString(getConfig.KEY_VIOLATION);
textViewResult.setText("License Number:\t"+lnumber+"\nViolation:\t"+violation);
}
PS:
My Listview id is listView. If anyone can help me how to display multiple data from the server to the listview would be a very great help!
1.Your JSON root tag is [] . You must use JSONArray . It is not JSONObject .
2.Your sample did not contain datetime key in your JSONObject .
Try this
DataBean
public class DataBean {
/**
* lnumber : 2
* violation : 2
*/
private String lnumber;
private String violation;
public String getLnumber() {
return lnumber;
}
public void setLnumber(String lnumber) {
this.lnumber = lnumber;
}
public String getViolation() {
return violation;
}
public void setViolation(String violation) {
this.violation = violation;
}
}
Adapter
public class MyAdapter extends BaseAdapter {
private List<DataBean> beanList;
private LayoutInflater inflater;
private Context context;
public MyAdapter() {
}
public MyAdapter(List<DataBean> beanList, Context context) {
this.context = context;
this.beanList = beanList;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return beanList == null ? 0 : beanList.size();
}
#Override
public Object getItem(int position) {
return beanList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.your_layout, null);
DataBean dataBean = beanList.get(position);
text.setText(dataBean.getLnumber() + dataBean.getViolation());
return view;
}
}
Activity
private List<DataBean> beanList = new ArrayList<>();
private ListView listView;
private void showJSON(String response) {
listView = (ListView) findViewById(R.id.listview);
try {
String lnumber;
String violation;
String datetime;
DataBean dataBean = new DataBean();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
lnumber = jsonObject.getString("lnumber");
violation = jsonObject.getString("violation");
dataBean.setLnumber(lnumber);
dataBean.setViolation(violation);
beanList.add(dataBean);
}
MyAdapter myAdapter = new MyAdapter(beanList,MainActivity.this);
listView.setAdapter(myAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
so you want to fetch the json from the php script u have.
use AsyncDataClass to fetch json from your php script and as you are new to programming first read about AsyncDataClass and then try to print the json you fetched from the script using Log.d("","") then proceed to next step.

how to update Expandable Listview with new items?(notifyDataSetChanged()not works)

I have expandable Lisview and i load the data to listview from server.
And there are some rows with edittext. so whenever i pressed right button for edit,
edittext is focusable and edit that value and again pressed on that button value will goes to sever.
But from this it did not save it,Its again restore original value.
But when i am refreshing same activity value got changed.
How to load the Expandable listview with new editable values?
Here is my Code:-This is my activity
public class EditSwitch1Activity extends AppCompatActivity {
ExpandableListAdapter1 listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
SharedPreferences pref;
SharedPreferences.Editor editor;
private TextView edit_text;
HashMap<String, List<String>> listDataChild;
private TextView back;
private String roomId;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editswitch1);
pref = PreferenceManager.getDefaultSharedPreferences(EditSwitch1Activity.this);
editor = pref.edit();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
back = (TextView) findViewById(R.id.back);
expListView.setItemsCanFocus(true);
// preparing list data
Window window = EditSwitch1Activity.this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(EditSwitch1Activity.this.getResources().getColor(R.color.color_statusbar));
roomId = getIntent().getStringExtra("roomId");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + roomId;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new LongOperation1().execute(serverURL);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private class LongOperation1 extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
EditSwitch1Activity.this);
String data = "";
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Dialog.setMessage("Please wait..");
//Dialog.show();
// data += "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA";
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
// String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setDoOutput(true);
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
//conn.setRequestMethod("GET");
//byte[] encodedPassword = ( "Authorization" + ":" + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA" ).getBytes();
//BASE64Encoder encoder = new BASE64Encoder();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
// Map messageObjMap = new Gson().fromJson(Content, Map.class);
// String type = messageObjMap.get("messageType").toString();
// Song song = gson.fromJson(message, Song.class);
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
List<String> newlist = new ArrayList<String>();
for (int i = 0; i < response.getModule().length; i++) {
listDataHeader.add(response.getModule()[i].getModule_name());
newlist = new ArrayList<String>();
for (int j = 0; j < response.getModule()[i].getNo_of_switches(); j++) {
if (response.getModule()[i].getModuleId().getModuleid().equals(response.getModule()[i].getSwitches()[j].getModuleId().getModuleid())) {
newlist.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
listDataChild.put(response.getModule()[i].getModule_name(), newlist);
}
}
listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
// setting list adapter
expListView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
}
}
Also Attched the Expandable Listview Adapater:-
public class ExpandableListAdapter1 extends BaseExpandableListAdapter {
private String childText;
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private ArrayList<String> newlist;
private ArrayList<String> newlist1;
ArrayList<String>list1;
private SearchResponse response;
private Boolean onclick = true;
public ExpandableListAdapter1(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData, SearchResponse response) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.response = response;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
childText = (String) getChild(groupPosition, childPosition);
final ViewHolder holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtListChild.setText(childText); // Here whatever you will type in edittext will be overwritten by the value of 'childText.getTotal'. So after you are done writing in edit text make sore you change that in "_listDataChild" list.
newlist = new ArrayList<String>();
newlist1 = new ArrayList<String>();
list1=new ArrayList<>();
list1.add(childText);
final TextView txtListChild1 = (TextView) convertView
.findViewById(R.id.flash1);
txtListChild1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onclick) {
txtListChild1.setText("Save");
holder.txtListChild.setEnabled(true);
onclick = false;
} else {
// ArrayList<String> itemList=new ArrayList<String>();
//itemList.add();
onclick = true;
txtListChild1.setText("Edit");
holder.txtListChild.setEnabled(false);
newlist.add(response.getModule()[groupPosition].getSwitches()[childPosition].getSwitchId().getId());
newlist1.add(holder.txtListChild.getText().toString());
String url = "http://dashboard.droidhomes.in/api/switch";
RequestQueue requestQueue = Volley.newRequestQueue(_context);
JSONObject dataObj = new JSONObject();
try {
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for(int i=0;i<newlist.size();i++){
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("switch_id", newlist.get(i));
cartItemsObjedct.putOpt("switch_name",newlist1.get(i));
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("update_list", cartItemsArray);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.PUT, url, dataObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(_context, response.getString("status"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText(error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
notifyDataSetChanged();
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
class ViewHolder {
EditText txtListChild;
public ViewHolder(View v) {
txtListChild = (EditText) v.findViewById(R.id.lblListItem);
}
}
public HashMap<String,List<String>> gethashmap() {
return _listDataChild;
}
}
Here ,In this adapter i used gethashmap() method which call from activity so it load with fresh data but don't know how to do this.
Replace your code with following modified code :
public class EditSwitch1Activity extends AppCompatActivity {
ExpandableListAdapter1 listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
SharedPreferences pref;
SharedPreferences.Editor editor;
private TextView edit_text;
HashMap<String, List<String>> listDataChild;
private TextView back;
private String roomId;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editswitch1);
pref = PreferenceManager.getDefaultSharedPreferences(EditSwitch1Activity.this);
editor = pref.edit();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
back = (TextView) findViewById(R.id.back);
expListView.setItemsCanFocus(true);
// preparing list data
Window window = EditSwitch1Activity.this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(EditSwitch1Activity.this.getResources().getColor(R.color.color_statusbar));
roomId = getIntent().getStringExtra("roomId");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + roomId;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new LongOperation1().execute(serverURL);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
// setting list adapter
expListView.setAdapter(listAdapter);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private class LongOperation1 extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
EditSwitch1Activity.this);
String data = "";
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Dialog.setMessage("Please wait..");
//Dialog.show();
// data += "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA";
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
// String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setDoOutput(true);
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
//conn.setRequestMethod("GET");
//byte[] encodedPassword = ( "Authorization" + ":" + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA" ).getBytes();
//BASE64Encoder encoder = new BASE64Encoder();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
// Map messageObjMap = new Gson().fromJson(Content, Map.class);
// String type = messageObjMap.get("messageType").toString();
// Song song = gson.fromJson(message, Song.class);
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
List<String> newlist = new ArrayList<String>();
listDataHeader.clear() ;
listDataChild.clear();
for (int i = 0; i < response.getModule().length; i++) {
listDataHeader.add(response.getModule()[i].getModule_name());
newlist = new ArrayList<String>();
for (int j = 0; j < response.getModule()[i].getNo_of_switches(); j++) {
if (response.getModule()[i].getModuleId().getModuleid().equals(response.getModule()[i].getSwitches()[j].getModuleId().getModuleid())) {
newlist.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
listDataChild.put(response.getModule()[i].getModule_name(), newlist);
}
}
//listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
listAdapter.setListDataHeader(listDataHeader) ;
listAdapter.setListDataChild(listDataChild) ;
listAdapter.setSearchResponse(response) ;
listAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
}
Adapter class
public class ExpandableListAdapter1 extends BaseExpandableListAdapter {
private String childText;
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private ArrayList<String> newlist;
private ArrayList<String> newlist1;
ArrayList<String>list1;
private SearchResponse response;
private Boolean onclick = true;
public ExpandableListAdapter1(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData, SearchResponse response) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.response = response;
}
public void setListDataHeader(List<String> list){
this._listDataHeader = list;
}
public void setListDataChild(List<String> list){
this._listDataChild = list;
}
public void setSearchResponse(SearchResponse response){
this.response = response;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
childText = (String) getChild(groupPosition, childPosition);
final ViewHolder holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtListChild.setText(childText); // Here whatever you will type in edittext will be overwritten by the value of 'childText.getTotal'. So after you are done writing in edit text make sore you change that in "_listDataChild" list.
newlist = new ArrayList<String>();
newlist1 = new ArrayList<String>();
list1=new ArrayList<>();
list1.add(childText);
final TextView txtListChild1 = (TextView) convertView
.findViewById(R.id.flash1);
txtListChild1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onclick) {
txtListChild1.setText("Save");
holder.txtListChild.setEnabled(true);
onclick = false;
} else {
// ArrayList<String> itemList=new ArrayList<String>();
//itemList.add();
onclick = true;
txtListChild1.setText("Edit");
holder.txtListChild.setEnabled(false);
newlist.add(response.getModule()[groupPosition].getSwitches()[childPosition].getSwitchId().getId());
newlist1.add(holder.txtListChild.getText().toString());
String url = "http://dashboard.droidhomes.in/api/switch";
RequestQueue requestQueue = Volley.newRequestQueue(_context);
JSONObject dataObj = new JSONObject();
try {
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for(int i=0;i<newlist.size();i++){
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("switch_id", newlist.get(i));
cartItemsObjedct.putOpt("switch_name",newlist1.get(i));
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("update_list", cartItemsArray);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.PUT, url, dataObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(_context, response.getString("status"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText(error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
class ViewHolder {
EditText txtListChild;
public ViewHolder(View v) {
txtListChild = (EditText) v.findViewById(R.id.lblListItem);
}
}
public HashMap<String,List<String>> gethashmap() {
return _listDataChild;
}

Android - Same JSON parsing class for different web services

I have made a JSONParse class for parsing JSON response. I have to call 3 web services. But I want to use only that SINGLE class for parsing JSON response for all 3 web services. All 3 web services has different keys and values. What I have done is like below..
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
// Anything Else Goes Here
private ArrayList<ModelCourse> ArrayListModelCourses;
// Variables
private String url = "stream.php";
private String career_path = "";
// Widgets
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
initialisation();
find_view_by_id();
clickListners();
fetchData();
}
private void initialisation() {
ArrayListModelCourses = new ArrayList<>();
}
private void find_view_by_id() {
lv = (ListView) findViewById(R.id.list_view);
}
private void clickListners() {
lv.setOnItemClickListener(this);
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JsonParse jsonParse = new JsonParse(response);
ArrayListModelCourses = jsonParse.parseJson();
} else {
Toast.makeText(MainActivity.this, "Error msg from server!!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomAdapter ca = new CustomAdapter(getApplicationContext(), ArrayListModelCourses);
lv.setAdapter(ca);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "51");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String stream_name = ArrayListModelCourses.get(position).getmCourse_name();
String stream_id = ArrayListModelCourses.get(position).getmCourse_id();
career_path += stream_name + ", ";
fetchData();
}
}
JsonParse.java - The single class that I want to use for 3 web services.
public class JsonParse {
// Anything Else Goes Here
ArrayList<ModelCourse> modelCourses = new ArrayList<>();
// Variables
public static final String KEY_ARRAY = "stream_name";
public static final String KEY_ID = "stream_id";
public static final String KEY_NAME = "stream_name";
private String mJsonRes;
public JsonParse(String jsonRes) {
this.mJsonRes = jsonRes;
}
public ArrayList<ModelCourse> parseJson() throws JSONException {
JSONObject jo = new JSONObject(mJsonRes);
JSONArray ja = jo.getJSONArray(KEY_ARRAY);
for (int i = 0; i < ja.length(); i++) {
ModelCourse modelCourseObj = new ModelCourse();
JSONObject object = ja.getJSONObject(i);
modelCourseObj.mCourse_id = object.getString(KEY_ID);
modelCourseObj.mCourse_name = object.getString(KEY_NAME);
modelCourses.add(modelCourseObj);
}
return modelCourses;
}
}
Thanks in advance.
Use can use Gson for mapping json data to objects.
Create models classes for your json data. (use link http://www.jsonschema2pojo.org/)
Now in your MainActivity onResponse() method pass the string response to JsonParse class.
In JsonParse class parse your json data
Gson gson = new Gson();
gson.fromJson(jsonString, JsonModelRootClassName.class);
You can create one method to get "JsonModelRootClassName" based on your web services call.

How to add some parsed JSON objects into a custom listview?

Well, I don't know if the title is clear, so now I'll explain everything better.
I have parsed some JSON objects. After parsing, I need to show them into a custom listview.
The JSON objects are correctly parsed into string, because I have first show them into common textviews (just for a test).
Also the custom listview is working, because I have first added some values "manually" (again, just for testing it).
Here my problem:
Now I want to add the JSON objects (parsed into string) into my custom listview. I've tried every "tip and trick" I know, unsuccessfully. After two days of working, I've decided to ask you.
Before posting the code: the http request for parsing JSON objects is made with this library.
Here the code
Getprofiledata.java
public class Getprofiledata extends ActionBarActivity {
String num;
Boolean ok=true;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
String url = "URL FOR JSON OBJECTS";
ListView listadata = (ListView) findViewById(R.id.listadata);
final List<Data> datalist = new LinkedList <Data>();
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
/*********
* HERE WE CAN ADD VALUES TO MY CUSTOM LISTVIEW
* HOW CAN I PASS THE PREVIOUS STRING IN THIS STATEMENT?
*
* THIS IS THE METHOD:
* datalist.add(new Data(record1,record2,record3,record4,record5));
*********/
//HERE THE ADAPTER FOR MY CUSTOM LISTVIEW
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this, R.layout.data_riga, datalist);
listadata.setAdapter(adapter);
}
}
I hope I've been clear. Can you help me? I'm desperate! :(
Thanks in advance
Edit: here my Getprofiledata_customadapter.java
public class Getprofiledata_customadapter extends ArrayAdapter<Data>{
public Getprofiledata_customadapter(Context context, int textViewResourceId,
List <Data> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.data_riga, null);
TextView firstrecord = (TextView)convertView.findViewById(R.id.tv1);
TextView secondrecord = (TextView)convertView.findViewById(R.id.tv2);
TextView thirdrecord = (TextView)convertView.findViewById(R.id.tv3);
TextView forthrecord = (TextView)convertView.findViewById(R.id.tv4);
TextView fivethrecord = (TextView)convertView.findViewById(R.id.tv5);
Data c = getItem(position);
firstrecord.setText(c.getRecord1());
secondrecord.setText(c.getRecord2());
thirdrecord.setText(c.getRecord3());
forthrecord.setText(c.getRecord4());
fivethrecord.setText(c.getRecord5());
return convertView;
}
}
Basically you just pre-create the List first. Then with that data create an adapter and set it to your ListView.
At the moment you just loop through the data without saving it at all.
It would look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
mListView = (ListView) findViewById(R.id.listadata);
String url = "URL FOR JSON OBJECTS";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
// Save strings to your list
mData.add(new Data(record1,record2,record3,record4,record5));
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
// When the data loop is over create the adapter and set it to your ListView
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this,
R.layout.data_riga, mData);
mListView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
}

Categories

Resources