I have a jsonArray which I want to parse in my android app.
The array:-
[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},
{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]
My android Code:-
Asynctask:-
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");
for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
JsonFunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The error I get:-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The json is hosted here
I was following this tutorial for learning json parsing, but this tutorial uses jsonObject and I am not able to parse the json array.
Not a duplicate to this :-Sending and Parsing JSON Objects or this How to parse this JSON Array in android?
Let me offer an alternate solution (of sorts). A much simpler version of your existing code would be:
Updated code:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);
for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);
HashMap<String, String> map = new HashMap<>();
if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {
if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}
if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}
if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}
if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}
/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
private class TestListAdapter extends BaseAdapter {
Activity activity;
// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;
// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;
public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {
this.activity = activity;
// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;
// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrItem.size();
}
#Override
public Object getItem(int position) {
return arrItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// A VIEWHOLDER INSTANCE
ViewHolder holder;
// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;
// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);
// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();
/***** CAST THE LAYOUT ELEMENTS *****/
/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);
// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}
if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}
if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}
return vi;
}
private class ViewHolder {
/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}
For the sake of completeness, I am also including the code for the adapter. It is a simple implementation. Do clean it up / optimize it / customize as per your requirement.
This piece of code has been tested prior to being posted (see screenshot of Logs at the bottom)
This uses the OkHttp library. Add this compile statement to the dependencies section of the module's gradle file: compile 'com.squareup.okhttp:okhttp:2.5.0'. Check the link for an updated version.
The example code uses if statements considering that not every record has the same set of nodes.
You BufferReader is not working as expected in your class JSONfunctions , do some changes in your class and it should looks like
JSONfunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
StringBuffer sb = new StringBuffer("");
try {
URL urls = new URL(url);
URLConnection urlConnection;
urlConnection = urls.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
result=sb.toString();
} catch (IOException e) {}
catch (Exception e) {}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
and to avoid Exception check if JSONArray is not null then only it goes to run for loop like this :
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android? service=airtel&circle=assam");
if(ja2!=null)
for (int i = 0; i < ja2.length(); i++) {}
jsonResponse="";
for(int i = 0; i<response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String category = person.getString("category");
}
Related
public class FindPlaces extends AppCompatActivity {
private static final String MAP_API_URL = "https://api.foursquare.com/v2/venues/categories?client_id=AW31XQWUOLJWFZCFNZZ04I4IQFUFYIFAFDEHEYITEBBDHIVB&client_secret=R10S3ACA5VFOTGVG2LW1N4YONU30LQ3IE0DKIG1JNHN2QNWE&v=20170811&m=foursquare";
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> categoriesList;
ArrayList<Categories> categories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_places);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the Categories Class
categories = new ArrayList<Categories>();
// Create an array to populate the spinner
categoriesList = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("https://api.foursquare.com/v2/venues/categories?client_id=CONSUMER_KEY&client_secret=CONSUMER_SECRET&v=20170811&m=foursquare");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("categories");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Categories cat = new Categories();
cat.setName(jsonobject.optString("name"));
categories.add(cat);
// Populate spinner with country names
categoriesList.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinnerCategories);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(FindPlaces.this,
android.R.layout.simple_spinner_dropdown_item,
categoriesList));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtname = (TextView) findViewById(R.id.tvName);
txtname.setText(categories.get(position).getName());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
This is my class to inflate the spinner.
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
This is where i handle with the http request
{ "response": {
"categories": [
{
"id": "4d4b7104d754a06370d81259",
"name": "Arts & Entertainment",
"pluralName": "Arts & Entertainment",
"shortName": "Arts & Entertainment",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
},
"categories": [
{
"id": "56aa371be4b08b9a8d5734db",
"name": "Amphitheater",
"pluralName": "Amphitheaters",
"shortName": "Amphitheater",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
}
and this is the json.
How can i change to get request instead a post request?
and how can i populate my spinner?
Thanks in advance.
I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = null;
#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();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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 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);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
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);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.
I am working on an application related with news, I have successfully parsed a json response and displayed the data in listview.
But the listview is not loading data at first time and remains empty.
On second time it displayed parsed data in listview.
What might be the problem ? Below is my code
// This is my java file:
public class FunHallListActivity extends AppCompatActivity {
FunHallDBHandler funhallhandler;
SQLiteDatabase db;
InputStream is=null;
String resultFunHall = null;
String line=null;
int code;
String URL = "";
private Context context;
private ListView fhListview;
private FunHallAdapter adapterfunhall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_hall_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
fhListview=(ListView)findViewById(R.id.funhall_lv);
context=this;
new FunHallFetcherTask().execute();
funhallhandler=new FunHallDBHandler(context);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
//Json parsing code with to fech and add into Sqlite Database
class FunHallFetcherTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
//Json Parsing code end
return null;
}
}
}
// and this is my adapter
public class FunHallAdapter extends BaseAdapter {
private List<FunHall> funHallList;
private Context context;
private LayoutInflater layoutInflater;
public FunHallAdapter(Context context, List<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return funHallList.size();
}
#Override
public FunHall getItem(int position) {
return funHallList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvfunHallName,tvfunHalladdress,tvfunHallcontact;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Holder holder;
if (convertView == null)
{
holder = new Holder();
convertView = layoutInflater.inflate(R.layout.funhall_list_item,null);
holder.tvfunHallName=(TextView)convertView.findViewById(R.id.funhallname_tv);
holder.tvfunHalladdress=(TextView)convertView.findViewById(R.id.funhalladdress_tv);
holder.tvfunHallcontact=(TextView)convertView.findViewById(R.id.hunhallcantact_tv);
convertView.setTag(holder);
}else
{
holder = (Holder) convertView.getTag();
}
holder.tvfunHallName.setText(funHallList.get(position).getFHallName());
holder.tvfunHalladdress.setText(funHallList.get(position).getFHalladdress());
holder.tvfunHallcontact.setText(funHallList.get(position).getFHallContact());
return convertView;
}
}
i think you must declare setAdapter was onPostExecute. don't declare before onPreExecute or doInBackground. i think it was issue..
Issue is that you are not notifying the adapter when data is changed.
Follow the steps
1. Modify your constructor
ArrayList<FunHall> funHallList;
public FunHallAdapter(Context context, ArrayList<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Step 2.
In your FunHallAdapter add this method
public void swapData(ArrayList<FunHall> funHallList){
this.funHallList = funHallList;
notifyDataSetChanged();
}
In your FunHallListActivity
class FunHallFetcherTask extends AsyncTask<Void,Void,String> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
return resultFunHall ;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!TextUtils.isEmpty(s)) {
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
adapterfunhall.swapData(funhallhandler.getAllFunHall());
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
}
i found what mistake i did, and i solved it as follow,
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.
This question already has answers here:
Error parsing data org.json.JSONException: Value String cannot be converted to JSONArray
(2 answers)
Closed 8 years ago.
Here is list activity
ListActivity:
public class ListDataActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_listview);
url = "http://xxx.xx.x.xxx/index.php";
Bundle c = getIntent().getExtras();
blo = c.getString("blood");
new ProgressTask(ListDataActivity.this).execute();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(ListDataActivity.this,
MainActivity.class));
}
}
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, Category },
new int[] { R.id.vehicleType, R.id.vehicleColor }) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_listitem,
null);
}
// TODO Auto-generated method stub
if (position % 2 == 1)
convertView.setBackgroundColor(Color.rgb(120, 151, 66));
else
convertView.setBackgroundColor(Color.rgb(86, 107, 129));
return super.getView(position, convertView, parent);
}
};
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
protected Boolean doInBackground(final String... args) {
url = url + "?blo_name=" + blo;
Log.d("", url);
baseAdapter jParser = new baseAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vfuel = c.getString(Category);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(Category, vfuel);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
Base Adapter class:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed ");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
PHP:
if (isset($_POST['blo_name'])) {
$str = $_POST['blo_name'];
$sql = "SELECT * FROM blood_group where Category IN ($str)";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
I am trying to parse bol string, it have value like bol="'B-','O-'"; while I parse this type of value it didn't show results and gives the logcat
logcat:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
I need to get result against query SELECT * FROM blood_group where Category IN ($str) but I cannot get. When I give hard core value in php like $str = "'A+','B+'"; it give me result while parsing from android it does not give result while in logcat I can see value http://xxx.xx.x.xxx/heart.php?blo_name='A','B' but error as well.
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
Notice <br - the web service is returning HTML and not a plain JSON string. Basically you need to fix your PHP response so it doesn't return HTML.