JSONArray to Android ListView - android

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.

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

Passing Array list as parameter and showing it as a list

I'm trying to pass an ArrayList to a function which will then display it on a list format but it seems my parameters are wrong for Arrayadapter.
#Override
public void handleResult(final Result result) {
final RequestQueue mQueue = Volley.newRequestQueue(this);
String url = "https://fg3qzgb2va.execute-api.ap-southeast-1.amazonaws.com/sample";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length() ; i++) {
JSONObject jsonArray = response.getJSONObject(i);
String first = jsonArray.getString("Name");
String price = jsonArray.getString("Price");
int priceResult = Integer.parseInt(price);
String id = jsonArray.getString("id");
if(id.equals(result.getText())){
addItem.setName(first);
addItem.setPrice(priceResult);
MainActivity.resultTextView.setText("Name: " + addItem.getName() + "\n"+"Price: " + addItem.getPrice());
itemList = new ArrayList<>();
itemList.add(addItem.getName());
addItem.setName("");
addToList.addList(itemList);
}
//Storing into the list
}
} catch (JSONException e) {
e.printStackTrace();
}
public class AddToList extends AppCompatActivity {
ArrayAdapter<String> adapter;
public void addList(ArrayList<String> arrayList ){
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,arrayList);
adapter.notifyDataSetChanged();
MainActivity.list.setAdapter(adapter);
}
}
Try this
Remove line:
MainActivity.list.setAdapter(adapter);
Add:
ListView mList = MainActivity.list;
mList.setAdapter(adapter);
try to change public void addList(ArrayList<String> arrayList ) to public void addList(List<String> arrayList )

Android application crashes if JSON is empty

I am developing an Application of JSON object Which Returns data into ListView.
if json have data then show data in listview..if dont have date then application is crashes.my application is crashes when json is empty.how to resolve this problem..thanx in advancce
here is android code..
public class EmployeePaymentHistory extends Fragment {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
ListView CategoryListView;
ProgressBar progressBar;
List<String> IdList = new ArrayList<>();
private String TAG = EmployeePaymentHistory.class.getSimpleName();
// Http Url For Filter Student Data from Id Sent from previous activity.
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
String TempItem;
ProgressDialog progressDialog2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_employee_payment, container, false);
CategoryListView = (ListView)view.findViewById(R.id.listview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getActivity().getIntent().getExtras().getString("ListViewValue1");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
// Add Click listener on Delete button.
return view;
}
// Method to Delete Student Record
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new EmployeePaymentHistory.GetHttpResponse(getActivity()).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("CustomerID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, api.EmployeePayment);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
List<Customer> CategoryList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Customer category;
CategoryList = new ArrayList<Customer>();
for(int i=0; i<jsonArray.length(); i++)
{
category = new Customer();
jsonObject = jsonArray.getJSONObject(i);
category.CustomerName = jsonObject.getString("date").toString();
category.Customertotal = jsonObject.getString("account").toString();
category.CustomerPaid = jsonObject.getString("total").toString();
category.CustomerUnPaid = jsonObject.getString("status").toString();
CategoryList.add(category);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "abcc", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
CategoryListView.setVisibility(View.VISIBLE);
CustomerListAdapterClass adapter = new CustomerListAdapterClass(CategoryList, context);
CategoryListView.setAdapter(adapter);
}
}
}
here is php Api code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$CustomerID= $_POST['CustomerID'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "sELECT b.payerid,a.account as account,b.date as date,b.status as status,b.type as type,sum(b.amount) as total FROM crm_employees a left JOIN sys_transactions b ON a.id = b.payerid where payerid= '$CustomerID' group by b.date ORDER BY a.id desc" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
You need to give the response output same as you are parsing in android side. If you are trying to find a Json object of key name which is not in response then it will crash.
In this scenario you need to handle manually, the values you think it will be null or empty then handle using normal if statements.
Suppose jsonObject.getString("date") object is not fount then using if statements you can handle.
if(jsonObject.getString("date") != null){
//code here
}

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.

Updating ListView JsonParsing by using Volley

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.

Categories

Resources