Dynamically adding Groups and Headers to an Expandable List View - java

I have data coming in as a JSON Array and I am parsing it. Here is an example:
[{"Tag":"Amusement Parks","Category":"Attractions"},{"Tag":"Restaurant","Category":"Food"}, etc]
What I want to do is to make every "Category" a Header in the ListView and every "Tag" a child of that Header. Right now I am hard coding the Header's and adding the Tags like this:
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
...
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (json.getString("Category").equals("Attractions")) {
tempAttractions.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Food")) {
tempFood.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Lodging")) {
tempLodging.add(json.getString("Tag"));
}
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
But instead of hard coding the categories, I want to dynamically add categories from the JSON data.
So basically, something like this...
//obviously pseudo code...
if (json.getString("Category") exists as a header already) {
add json.getString("Tag") as a child under that group
//or if it doesn't exist
} else {
add a header header and add json.getString("Tag") as a child under that group
}
I think this is more of a conceptual problem, I can't seem to grasp a way to get this done. Any ideas? Thanks!
Full Code
public class CategorySelect extends BaseActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
List<String> listAttractions;
List<String> listFood;
List<String> listLodging;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_select);
// initialize Nav Drawer
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
progress = new ProgressDialog(this);
progress.setMessage("Loading...Please Wait");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
listAttractions = new ArrayList<String>();
listFood = new ArrayList<String>();
listLodging = new ArrayList<String>();
new FillCategories().execute();
}
private class FillCategories extends
AsyncTask<Integer, Void, Void> {
List<String> tempAttractions = new ArrayList<String>();
List<String> tempFood = new ArrayList<String>();
List<String> tempLodging = new ArrayList<String>();
#Override
protected ArrayList<Location> doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String action = "nav";
nameValuePairs.add(new BasicNameValuePair("action", action));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = 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(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
//Log.d("Text", json.getString("Txt"));
if (json.getString("Cat").equals("Attractions")) {
tempAttractions.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempAttractionsTags.add(json.getString("Txt"));
} else {
tempAttractionsTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Food")) {
tempFood.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempFoodTags.add(json.getString("Txt"));
} else {
tempFoodTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Lodging")) {
tempLodging.add(json.getString("Txt"));
if (json.getString("Tag").equals("")) {
tempLodgingTags.add(json.getString("Txt"));
Log.d("Tag", "Is Null");
} else {
tempLodgingTags.add(json.getString("Tag"));
Log.d("Tag Not Null", json.getString("Tag"));
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
}
}
}

You can do something like this
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (listDataChild.get(json.getString("Category")) == null) {
tempList = new ArrayList<String>();
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}else{
tempList = listDataChild.get(json.getString("Category"));
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}

You can use this library : library, it is very simple and very efficient

Related

How to parse this Json Array in android

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");
}

JSON respone in list view display based on the particular condition in android

I need to display the items on particular condition .I done that one.I have three tabs are present.In the first tab A ,i display the list of items,in that only one item is present.But when you move to tab B and again come to tab A,we can see two items.I need to avoid that repeating item displaying, how to do that one, please help me if you have an idea,Thank you in advance
Here is my code:
List View list;
ListViewAdapter adapter;
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> title_array1 = new ArrayList<String>();
ArrayList<String> title_array2 = new ArrayList<String>();
ArrayList<String> title_array3 = new ArrayList<String>();
ArrayList<String> title_array4 = new ArrayList<String>();
ArrayList<String> title_array5 = new ArrayList<String>();
ArrayList<String> title_array6 = new ArrayList<String>();
String response_value;
JSONObject result;
JSONArray tokenList;
JSONObject oj5;
String appid;
JSONObject oj;
String fileid;
HttpEntity entity;
String status ,borrowername,coborrowername,loannumber,addrs1,city;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_frame, container, false);
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
new AsyncTaskParseJson().execute();
return rootView;
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "******");
object.put("Password", "******");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("*********");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
entity = response.getEntity();
response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value);
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
}
} catch (Exception e) {
e.printStackTrace();
}
return response_value;
}
#Override
protected void onPostExecute(String response_value) {
super.onPostExecute(response_value);
// dismiss the dialog after getting all products
try
{
if (entity != null) {
result = new JSONObject(response_value);
tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
oj = tokenList.getJSONObject(i);
String oj1 = oj.getString("FileID");
JSONObject oj12= (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
fileid = oj.getString("FileID");
borrowername = oj12.getString("FirstName");
coborrowername = oj2.getString("FirstName");
loannumber = oj3.getString("LoanNumber");
addrs1 = oj4.getString("Address1");
city = oj4.getString("City");
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
appid = oj5.getString("ApplicationOrderId");
String duedate = oj5.getString("DueDate");
status = oj5.getString("Status");
// Log.e(TAG, appid +"/"+ appid1);
Log.e(TAG, appid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber + fileid );
if(status.equals("1")){
title_array3.add("New");
title_array1.add(addrs1 + " ,"+ city);
title_array.add(borrowername +" , "+coborrowername);
title_array2.add("Duedate");
// title_array3.add(status);
title_array4.add(appid);
title_array5.add(loannumber);
title_array6.add(fileid);
list.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent first = new Intent(getActivity(),DetailView.class);
first.putExtra("fileid", fileid);
startActivity(first);
} });
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), title_array,title_array1,title_array2,title_array3,title_array4,title_array5,title_array6);
list.setAdapter(adapter);
}
}
}

changing interface in an asynctask (the right way)

I'm trying to change the process data retrieved into a list view. The data is recieved properly. but i'm failing to make up the list view the right way.
Here is my asynctask class
class GetFriendsInfo extends AsyncTask<String, String, String>{
String id = "";
String fullName = "";
String birthday = "";
protected void onPreExecute() {
super.onPreExecute();
pd_GetData = new ProgressDialog(MainActivity.this);
pd_GetData.setMessage("Getting friend data");
pd_GetData.setIndeterminate(false);
pd_GetData.setCancelable(true);
pd_GetData.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray friendArray;
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_id", id));
param.add(new BasicNameValuePair("user_id", fullName));
param.add(new BasicNameValuePair("user_id", birthday));
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
try{
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1){
Log.d("PHP Server [GET]", "Retrieved user data");
String jsonString = jsonObject.getString("message");
friendArray = new JSONArray(jsonString);
String[] names = new String[friendArray.length()];
String[] birthdays = new String[friendArray.length()];
String[] ids = new String[friendArray.length()];
for(int i=0; i<friendArray.length(); i++) {
JSONObject friend = friendArray.getJSONObject(i);
String friend_id = friend.getString("id");
ids[i] = friend_id;
String friend_name = friend.getString("fullName");
names[i] = friend_name;
String friend_birthday = friend.getString("birthday");
birthdays[i] = friend_birthday;
}
Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));
List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>();
for (int i=0;i<names.length;i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("names", names[i]);
hm.put("ids", ids[i]);
hm.put("birthdays", birthdays[i]);
birthday.add(hm);
}
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}else{
Log.d("PHP Server [GET]", "Failed retrieve user data");
}
}catch (JSONException e){
e.printStackTrace();
}catch (RuntimeException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pd_GetData.dismiss();
}
}
I know that i shouldn't create the listview in the doInBackground. But i don't have a clue how i should do it.
This should give you the idea. Read the inline comments:
class GetFriendsInfo extends AsyncTask<Void, Void, JSONObject> {
private String url;
public GetFriendsInfo(String url_get_birthdays) {
this.url = url_get_birthdays;
}
#Override
protected JSONObject doInBackground(Void... params) {
// Make your network call and get your JSONObject
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
// Here you get your jsonObject on the main thread. You can parse it and update your UI
// Convert your jsonObject to what you want and then show the dialog
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}
}
set your adapter in onPostExecute() method.
class GetFriendsInfo extends AsyncTask<String, String, String>{
String id = "";
String fullName = "";
String birthday = "";
List<HashMap<String, String>> birthday;
protected void onPreExecute() {
super.onPreExecute();
pd_GetData = new ProgressDialog(MainActivity.this);
pd_GetData.setMessage("Getting friend data");
pd_GetData.setIndeterminate(false);
pd_GetData.setCancelable(true);
pd_GetData.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray friendArray;
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_id", id));
param.add(new BasicNameValuePair("user_id", fullName));
param.add(new BasicNameValuePair("user_id", birthday));
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
try{
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1){
Log.d("PHP Server [GET]", "Retrieved user data");
String jsonString = jsonObject.getString("message");
friendArray = new JSONArray(jsonString);
String[] names = new String[friendArray.length()];
String[] birthdays = new String[friendArray.length()];
String[] ids = new String[friendArray.length()];
for(int i=0; i<friendArray.length(); i++) {
JSONObject friend = friendArray.getJSONObject(i);
String friend_id = friend.getString("id");
ids[i] = friend_id;
String friend_name = friend.getString("fullName");
names[i] = friend_name;
String friend_birthday = friend.getString("birthday");
birthdays[i] = friend_birthday;
}
Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));
birthday = new ArrayList<HashMap<String, String>>();
for (int i=0;i<names.length;i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("names", names[i]);
hm.put("ids", ids[i]);
hm.put("birthdays", birthdays[i]);
birthday.add(hm);
}
}else{
Log.d("PHP Server [GET]", "Failed retrieve user data");
}
}catch (JSONException e){
e.printStackTrace();
}catch (RuntimeException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
pd_GetData.dismiss();
}
}
As UI operation can not be done in doinbackground. So first make birthday list global in asyntask.
List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>(); // make it Global.
move the below part from doinbackground to
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pd_GetData.dismiss();
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}
If you have still nay query please let me know.

Android : Convert List Array to String Array show nothing

I am trying to get the data from URL and convert it into String Array, but when I try to show it on TextView its show nothing. The link and itemId that I use is already right.
There's no Error warning on logcat.
I can't figure it out why.
Is there anyone can't help me?
Here's my json data
[{"image":"http://cdn-data.apps.com/category_item/05d92b217f916c9b9d87ab9121662d87.jpg"},
{"image":"http://cdn-data.apps.com/category_item/0424ef5a980255ff989fe5b20eaa5dcd.jpg"},
{"image":"http://cdn-data.apps.com/category_item/02b5bce4a9ca8fa3e53ceea2c7e273ff.jpg"},
{"image":"http://cdn-data.apps.com/category_item/dd15419113c091c93eafb3695eb65153.jpg"},
{"image":"http://cdn-data.apps.com/category_item/1ddfd2d7a489678e3c66e7f012ceb951.jpg"}]
Here's my Java code
if(in.getStringExtra("TAG_IMAGE_COUNT").equals("0")) {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.GONE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.GONE);
}
else {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.VISIBLE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.VISIBLE);
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String json = reader.readLine();
//JSONObject jsonObject = new JSONObject(json);
JSONArray arr = new JSONArray(httpResponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
String[] stringArr = list.toArray(new String[list.size()]);
TextView array = (TextView)findViewById(R.id.testarray);
array.setText(Arrays.toString(stringArr));
Log.d("", json);
//Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I try to show it on testarray but its show nothing.
First of all your have to parse a String not Httpresponse:
here you do:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
JSONArray arr = new JSONArray(httpResponse);
Change a little like:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
And finally set the list data as you want in your textView out of the background thread.
you should not use any UI thread views (e.g button, textview, edittext ..) in background thread.
EDIT:
private class GetImages extends AsyncTask<String, Integer, ArrayList<String>>{
ArrayList<String> list = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(String... params) {
try {
HttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//use this result and put in your textView
}
}

Android: Remove null values from an array:

How can I remove any null values from an array.
public class RecipeMethodActivity extends ListActivity {
Intent myIntent;
String value;
TextView editvalue;
TextView buttonPressed;
Intent intent;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result2 = null;
final Recipe[] mRecipesArray = { new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
if(!recipes[i].name.equals(value)){
recipes[i].steps = null;
Recipe[] tmp = new Recipe[recipes.length - 1];
//int j = 0;
//for (int k = 0; k < recipes.length; k++) {
// if (j != 1) {
// tmp[j++] = recipes[i];
// }
//}
recipes = tmp;
} else {
ret.add(recipes[i].name);
}
}
return ret;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = getIntent().getStringExtra("searchValue");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_name=json_data.getString("recipename");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, MethodActivity.class);
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
it returns a list view which when clicked should take you to the matching recipe but if i ask for Earth Destruction I get the portal cake recipe methods.
Thanks
This line of code is a problem
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
Instead of using mRecipesArray[position] use ret.get(position).steps
and declare ArrayList<Recipe> ret = new ArrayList<Recipe>(); outside of the FetchRecipesRawArray() method so that it can be accessed inside onListItemClick() method.
also modify your code in FetchRecipesRawArray()
else {
ret.add(recipes[i]);
}
Hope this will help you..

Categories

Resources