I am pretty new to Android.I am trying to parse a JSON url. But I am getting following error "Json parsing error: No value for unofficial-summary".
Here is the response that I am getting.
Response from url: {"success":true,"data":{"summary":{"total":15616130,"confirmedCasesIndian":15616082,"confirmedCasesForeign":48,"discharged":13276039,"deaths":182553,"confirmedButLocationUnidentified":0},"unofficial-summary":[{"source":"covid19india.org","total":7945975,"recovered":7198877,"deaths":119538,"active":626192}],"regional":[{"loc":"Andaman and Nicobar Islands","confirmedCasesIndian":5466,"confirmedCasesForeign":0,"discharged":5243,"deaths":64,"totalConfirmed":5466},{"loc":"Andhra Pradesh","confirmedCasesIndian":976987,"confirmedCasesForeign":0,"discharged":915626,"deaths":7472,"totalConfirmed":976987},{"loc":"Arunachal Pradesh","confirmedCasesIndian":17113,"confirmedCasesForeign":0,"discharged":16835,"deaths":56,"totalConfirmed":17113},{"loc":"Assam","confirmedCasesIndian":227473,"confirmedCasesForeign":0,"discharged":217296,"deaths":1145,"totalConfirmed":227473},{"loc":"Bihar","confirmedCasesIndian":342059,"confirmedCasesForeign":0,"discharged":283863,"deaths":1841,"totalConfirmed":342059},{"loc":"Chandigarh","confirmedCasesIndian":35148,"confirmedCasesForeign":0,"discharged":30768,"deaths":421,"totalConfirmed":35148},{"loc":"Chhattisgarh","confirmedCasesIndian":574299,"confirmedCasesForeign":0,"discharged":442337,"deaths":6274,"totalConfirmed":574299},{"loc":"Dadra and Nagar Haveli and Daman and Diu","confirmedCasesIndian":5422,"confirmedCasesForeign":0,"discharged":4047,"deaths":4,"totalConfirmed":5422},{"loc":"Delhi","confirmedCasesIndian":905540,"confirmedCasesForeign":1,"discharged":807328,"deaths":12638,"totalConfirmed":905541},{"loc":"Goa","confirmedCasesIndian":69311,"confirmedCasesForeign":1,"discharged":60145,"deaths":926,"totalConfirmed":69312},{"loc":"Gujarat","confirmedCasesIndian":428177,"confirmedCasesForeign":1,"discharged":346063,"deaths":5615,"totalConfirmed":428178},{"loc":"Haryana","confirmedCasesIndian":371610,"confirmedCasesForeign":14,"discharged":318369,"deaths":3483,"totalConfirmed":371624},{"loc":"Himachal Pradesh","confirmedCasesIndian":79410,"confirmedCasesForeign":0,"discharged":68164,"deaths":1219,"totalConfirmed":79410},{"loc":"Jammu and Kashmir","confirmedCasesIndian":150238,"confirmedCasesForeign":0,"discharged":134697,"deaths":2071,"totalConfirmed":150238},{"loc":"Jharkhand","confirmedCasesIndian":172315,"confirmedCasesForeign":0,"discharged":137590,"deaths":1547,"totalConfirmed":172315},{"loc":"Karnataka","confirmedCasesIndian":1198644,"confirmedCasesForeign":0,"discharged":1025821,"deaths":13646,"totalConfirmed":1198644},{"loc":"Kerala","confirmedCasesIndian":1272637,"confirmedCasesForeign":8,"discharged":1148671,"deaths":4978,"totalConfirmed":1272645},{"loc":"Ladakh","confirmedCasesIndian":12556,"confirmedCasesForeign":0,"discharged":10610,"deaths":134,"totalConfirmed":12556},{"loc":"Lakshadweep","confirmedCasesIndian":1335,"confirmedCasesForeign":0,"discharged":817,"deaths":1,"totalConfirmed":1335},{"loc":"Madhya Pradesh","confirmedCasesIndian":433704,"confirmedCasesForeign":0,"discharged":350720,"deaths":4713,"totalConfirmed":433704},{"loc":"Maharashtra","confirmedCasesIndian":3960356,"confirmedCasesForeign":3,"discharged":3213464,"deaths":61343,"totalConfirmed":3960359},{"loc":"Manipur","confirmedCasesIndian":29869,"confirmedCasesForeign":0,"discharged":29106,"deaths":378,"totalConfirmed":29869},{"loc":"Meghalaya","confirmedCasesIndian":15116,"confirmedCasesForeign":0,"discharged":14105,"deaths":154,"totalConfirmed":15116},{"loc":"Mizoram","confirmedCasesIndian":5085,"confirmedCasesForeign":0,"discharged":4569,"deaths":12,"totalConfirmed":5085},{"loc":"Nagaland","confirmedCasesIndian":12650,"confirmedCasesForeign":0,"discharged":12299,"deaths":94,"totalConfirmed":12650},{"loc":"Odisha","confirmedCasesIndian":377464,"confirmedCasesForeign":0,"discharged":349377,"deaths":1953,"totalConfirmed":377464},{"loc":"Puducherry","confirmedCasesIndian":48974,"confirmedCasesForeign":0,"discharged":43184,"deaths":717,"totalConfirmed":48974},{"loc":"Punjab","confirmedCasesIndian":309316,"confirmedCasesForeign":0,"discharged":264562,"deaths":8045,"t
What am I doing wrong?
package com.sudarshan.jsonparse2;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.rootnet.in/covid19-in/stats/latest";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONObject c = jsonObj.getJSONArray("unofficial-summary").getJSONObject(0);
String source = c.getString("source");
int total = c.getInt("total");
int recovered = c.getInt("recovered");
int deaths = c.getInt("deaths");
int active = c.getInt("active");
// tmp hash map for single contact
HashMap<String, String> summary = new HashMap<>();
// adding each child node to HashMap key => value
summary.put("source", "source: "+source);
summary.put("total", "total:" +String.valueOf(total));
summary.put("recovered", "recovered" +String.valueOf(recovered));
summary.put("deaths", "deaths" + String.valueOf(deaths));
summary.put("active", "active" + String.valueOf(active));
// adding contact to contact list
contactList.add(summary);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "source","total","recovered","deaths","active"},
new int[]{R.id.source, R.id.total,R.id.recovered,R.id.deaths,R.id.active});
lv.setAdapter(adapter);
}
}
}
Json is like
{
"success": true,
"data": {
"summary": {
//...
},
"unofficial-summary": [
{
//...
}]
}
}
Shoud get data first:
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.rootnet.in/covid19-in/stats/latest";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
// Add: 2021/4/26 add get data first
JSONObject jsonObj = new JSONObject(jsonStr);
String data = jsonObj.getString("data");
Log.w(TAG, "doInBackground: " + data);
// Getting JSON Array node
JSONObject c = new JSONObject(data).getJSONArray("unofficial-summary").getJSONObject(0);
String source = c.getString("source");
int total = c.getInt("total");
int recovered = c.getInt("recovered");
int deaths = c.getInt("deaths");
int active = c.getInt("active");
// tmp hash map for single contact
HashMap<String, String> summary = new HashMap<>();
// adding each child node to HashMap key => value
summary.put("source", "source: " + source);
summary.put("total", "total:" + String.valueOf(total));
summary.put("recovered", "recovered" + String.valueOf(recovered));
summary.put("deaths", "deaths" + String.valueOf(deaths));
summary.put("active", "active" + String.valueOf(active));
// adding contact to contact list
contactList.add(summary);
} catch (final JSONException e) {
//...
}
} else {
//...
}
return null;
}
I want to Delete a record from the database when i click on the Buttton.
The Button i set in the listView.
I want to perfrom this on ListView Here i tried following way but its not working..
Here My API
<?php
include("connection.php");
$tbl = "abc";
$idToDelete = $_GET["id"];
$delete_row = mysql_query("DELETE FROM $tbl WHERE o_id=".$idToDelete);
$response["delete"] = array();
$response["success"]=1;
// push single product into final response array
echo json_encode($response);
?>
ListviewAdapter.java
package com.example.sachin.alertbox;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button add;
Spinner spinner;
ListView listview;
LinearLayout linearlayout;
JSONObject jsonobject;
private static String url_addevent = "http ://10.0.2.2/portal/order_product.php";
public static String url_visitor= "http://10.0.2.2/portal/fetchorder_of_user.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
ListViewAdapterorder listadapter;
EditText qty;
LinearLayout layout;
ActionMenuView.LayoutParams params;
LinearLayout mainLayout;
PopupWindow popUp;
final Context context = this;
ArrayAdapter<String> adapter;
Button Delete;
ArrayList<String> listItems = new ArrayList<>();
String stringqty,stringspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.clickme);
popUp = new PopupWindow(this);
layout = new LinearLayout(this);
mainLayout = new LinearLayout(this);
listview = (ListView)findViewById(R.id.listview);
Delete=(Button)findViewById(R.id.delete);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);
qty=(EditText)promptsView.findViewById(R.id.qty);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();
Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
private void addvisitor() {
service(stringqty,stringspinner);
}
private void service(String qty,String sp) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
//#Override
protected void onPreExecute() {
// Create a progressdialog
super.onPreExecute();
//loading = ProgressDialog.show(getApplicationContext(), "Please Wait...!!!", null, true, true);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("quantity", params[0]);
param.put("model", params[1]);
String result = ruc.sendPostRequest(url_addevent, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getApplicationContext(), "Service Added Successfully...!!!", Toast.LENGTH_LONG).show();
/* Intent i1 = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i1);*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(qty,sp);
}
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/spinner.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
list.add("Please Select Model");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("m_model"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
listItems.addAll(list);
}
}
}
Here MainActivity.java ListView class
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
I tried this way but the delete is not happening.. please suggest me some coede for this.
Try this.
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datlist.remove(position);
o_aid.remove(position);
o_aproduct.remove(position);
o_aqty.remove(position);
o_atotal.remove(position);
Snackbar.make(view, "Record Delete Succesfully", Snackbar.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
Call me:85110 51548 if any issue
There is issue in your connection.php pls check I have checked but not issue from php queries but if connection.php has issue you will not find because if record is deleted it returns 1 if any problem it returns 0 in your code return 0 it means record is not deleted successfully.
Write The Following Code in Your php and change it into connection.php
/*connection.php */
$host="your host";
$username="your user name";
$password="your password";
$dbname="your database name";
$con = new mysqli($host, $username, $password,$dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
/*code.php */
include('connection.php');
$tbl = "abc";
$idToDelete = $_GET["id"];
$sql="DELETE FROM $tbl WHERE o_id=".$idToDelete;
$delete_row = $con->query($sql);
$response["delete"] = array();
$response["success"]=1;
/// push single product into final response array
echo json_encode($response);
** In short there is a problem in connection file thats why not deleted that record **
I am fetching JSON data from a URL and then displaying it in a ListView in the MainActivity.
I have made proper connection to the JSON file URL and I am able to fetch the data from the URL into a string but now I am trying to display it in a ListView using ListAdapter but it's not displaying any data in it.
My JSON data is like:
{
"result": 1,
"data": [{
"id": 1,
"name": "Aconitum",
"url": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/7\/7e\/Aconitum_degenii.jpg"
},
{
"id": 2,
"name": "African lily",
"url": "http:\/\/i1.wp.com\/cottagegardenflowershop.co.uk\/wp-content\/uploads\/2014\/09\/1040668-90x90.jpg?ssl=1"
},
{
"id": 3,
"name": "Alpine thistle",
"url": "http:\/\/i1.wp.com\/cottagegardenflowershop.co.uk\/wp-content\/uploads\/2014\/09\/1040668-90x90.jpg?ssl=1"
},
I am storing the data in the form of hashmap in the arrayList of this format.
ArrayList> contactList;
My main activity.java is:
package com.example.hsports.flowers;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
public static String url="http://development.easystartup.org/NO/Backend/flower.php";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listview);
new GetContacts().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String url=contactList.get(position).get("url");
System.out.println("hello");
}
});
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < 28; i++) {
JSONObject c = contacts.getJSONObject(i);
if(c==null)
{
continue;
}
String id = c.getString("id");
String name = c.getString("name");
String urlInjson = c.getString("url");
//String address = c.getString("address");
//String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("url", urlInjson);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.support_simple_spinner_dropdown_item, new String[]{"name"}, new int[]{R.id.flowerName});
lv.setAdapter(adapter);
}
}
}
how can I populate just the "name" from the Arraylist inside that ListView?
There should be a change in this statement:
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.support_simple_spinner_dropdown_item, new String[]{"name"}, new int[]{R.id.flowerName});
Where R.layout.list_view should be given where this is the view which defines the ListView layout.
I want to add a searchview to filter results. Please help me with this. I have tried all the methods available online but all are for custom adapter and none seems to be working for my project.
My MainActivity.class
package info.androidhive.jsonparsing;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
My HttpHandler.class
package info.androidhive.jsonparsing;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by Ravi Tamada on 01/09/16.
* www.androidhive.info
*/
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
U can use latest recylerview to achieve this (robust and better performance)
Or Easy way: try this MaterialSearchViewlibrary
I have a Listview in android that can be read by TTS when you click the items it reads it, but my problem is how to make the TTS to read all the items by clicking any of the items in the listview only once?
here's the codes
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
ListView list;
TextView html;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=New%20York,NY&sensor=false"; //url is just a sample
//JSON Node Names
private static final String TAG_OS = "routes";
private static final String TAG_HTM = "html_instructions";
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
JSONArray android = null;
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
html = (TextView) findViewById(R.id.html_instruction);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for (int x = 0; x < android.length(); x++) {
JSONArray legs = android.getJSONObject(x).getJSONArray("legs");
JSONObject distance = legs.getJSONObject(0).getJSONObject("distance");
JSONObject duration = legs.getJSONObject(0).getJSONObject("duration");
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
for (int j = 0; j < steps.length(); j++) {
String html_instructions = steps.getJSONObject(j).getString("html_instructions");
String s = html_instructions.replaceAll("<(\"[^\"]*\"|'[^']*'|[^'\">])*>", " ");
//for(int i = 0; i < android.length(); i++){
//JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
//String ver = c.getString(TAG_VER);
//String name = c.getString(TAG_NAME);
//String api = c.getString(TAG_API);
//String htm = c.getString("html_instructions");
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_HTM, s);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] {TAG_HTM}, new int [] {R.id.html_instruction});
list.setAdapter(adapter);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("html"), Toast.LENGTH_SHORT).show();
parent.getAdapter();
//adapter.getItem(position).toString();
String words = adapter.getItem(position).toString();
// String words = html.getText().toString();
speakWords(words);
}
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}} catch (JSONException e) {
e.printStackTrace();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this,(OnInitListener) this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
}