changing interface in an asynctask (the right way) - java

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.

Related

JSONObject cannot be converted to JSONArray in android

I am new in android developing. I faced a error like:- JSON Object cannot be convert in jsonArray:-
My ProductInner.java:
public class ProductInner extends AppCompatActivity {
TextView textView;
ImageView imageView;
LinearLayout linearLayout;
String s,s1;
List<String> mainImage = new ArrayList<>();
List<String> outerlist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_inner);
textView = (TextView)findViewById(R.id.product_inner_page_product_name);
imageView = (ImageView)findViewById(R.id.product_inner_page_product_main_image);
linearLayout = (LinearLayout)findViewById(R.id.sub_images_show_section);
new ProductInnerDisplay().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/product&id=80&key=test123$");
}
public class ProductInnerDisplay extends AsyncTask<String,Void,Void>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ProductInner.this);
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("rproducts");
JSONArray jsonArray1 = jsonObject.getJSONArray("productdata");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
List<String> list = new ArrayList<>();
list.add(jsonObject1.getString("product_id"));
list.add(jsonObject1.getString("thumb"));
list.add(jsonObject1.getString("name"));
list.add(jsonObject1.getString("price"));
list.add(jsonObject1.getString("rating"));
list.add(jsonObject1.getString("reviews"));
list.add(jsonObject1.getString("href"));
Log.d("json parse","");
}
for(int i=0;i<jsonArray1.length();i++){
Log.d("length of",jsonArray1.length()+"");
JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
List<String> list = new ArrayList<>();
list.add(jsonObject1.getString("id"));
// list.add(jsonObject1.getString("name"));
s=jsonObject1.getString("name");
list.add(jsonObject1.getString("model"));
list.add(jsonObject1.getString("reward"));
list.add(jsonObject1.getString("points"));
// list.add(jsonObject1.getString("image"));
outerlist.add(jsonObject1.getString("image"));
JSONArray jsonArray2 = jsonObject1.getJSONArray("images");
for(int j=0;j<jsonArray2.length();j++){
List<String> list1 = new ArrayList<>();
Log.d("i am here","");
mainImage.add(jsonArray2.getString(j));
Log.d("i am here next", "");
// list1.add(jsonArray2.getString(j));
}
list.add(jsonObject1.getString("price"));
Log.d("i am here 1", "");
JSONArray jsonArray3 = jsonObject1.getJSONArray("options");
for(int j=0;j<jsonArray3.length();j++){
JSONObject jsonObject2 = jsonArray3.getJSONObject(j);
List<String> list1 = new ArrayList<>();
list1.add(jsonObject2.getString("product_option_id"));
list1.add(jsonObject2.getString("option_id"));
list1.add(jsonObject2.getString("name"));
list1.add(jsonObject2.getString("type"));
JSONArray jsonArray4 = jsonObject2.getJSONArray("option_value");
for(int k=0;k<jsonArray4.length();k++){
JSONObject jsonObject3 = jsonArray4.getJSONObject(k);
List<String> list2 = new ArrayList<>();
list2.add(jsonObject3.getString("product_option_value_id"));
list2.add(jsonObject3.getString("option_value_id"));
list2.add(jsonObject3.getString("name"));
list2.add(jsonObject3.getString("image"));
list2.add(jsonObject3.getString("price"));
list2.add(jsonObject3.getString("price_prefix"));
}
list1.add(jsonObject2.getString("required"));
}
list.add(jsonObject1.getString("minimum"));
list.add(jsonObject1.getString("newprice"));
list.add(jsonObject1.getString("qty"));
list.add(jsonObject1.getString("rating"));
list.add(jsonObject1.getString("description"));
JSONArray jsonArray4 = jsonObject1.getJSONArray("attribute_groups");
for(int j=0;j<jsonArray4.length();j++){
JSONObject jsonObject2 = jsonArray4.getJSONObject(j);
List<String> list1 = new ArrayList<>();
list1.add(jsonObject2.getString("attribute_group_id"));
list1.add(jsonObject2.getString("name"));
JSONArray jsonArray5 = jsonObject2.getJSONArray("attribute");
for(int k=0;k<jsonArray5.length();k++){
JSONObject jsonObject3 = jsonArray5.getJSONObject(k);
List<String> list2 = new ArrayList<>();
list2.add(jsonObject3.getString("attribute_id"));
list2.add(jsonObject3.getString("name"));
list2.add(jsonObject3.getString("text"));
}
}
}
}
}catch (IOException |JSONException e){
Log.e("Error",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
dialog.dismiss();
// super.onPostExecute(aVoid);
// new SetImageView(image).execute(thumbDiscount.get(j));
textView.setText(s);
new SetImage(imageView).execute(s1);
for(int i=0;i<mainImage.size();i++){
ImageView imageView = new ImageView(ProductInner.this);
new SetImage(imageView).execute(mainImage.get(i));
linearLayout.addView(imageView, i);
}
}
}
public class SetImage extends AsyncTask<String,Void,Bitmap>{
ImageView bitmap;
public SetImage(ImageView bitmap){
this.bitmap = bitmap;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
String urldisplay = params[0];
Bitmap bitmap = null;
try{
InputStream in = new java.net.URL(urldisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
}catch (IOException e ) {
e.getMessage();
// Log.e("Error :",e.getMessage());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
bitmap.setImageBitmap(result);
//super.onPostExecute(bitmap);
}
}
}
My Json Array Link is here
My Logcat show this error:-
E/Error: Value {"id":"80","name":"Bag_80","model":"
","reward":"0","points":"0","image":"http://opencart.codeniques.com/shopping/image/cache/data/product/bag_81_1-1000x1000.JPG","images":["http://opencart.codeniques.com/shopping/image/cache/data/product/bag_80_2-80x80.JPG"],"price":1175,"minimum":"1","newprice":1163.25,"qty":4,"rating":0,"description":""}
at productdata of type org.json.JSONObject cannot be converted to
JSONArray`
productdata is not a JSONArray but a JSONObject, so you have to change
JSONArray jsonArray1 = jsonObject.getJSONArray("productdata");
to
JSONObject jsonObject1 = jsonObject.getJSONObjct("productdata");
As in log :
productdata of type org.json.JSONObject cannot be converted to JSONArray
means productdata key is used for JSONObject in response json of server instead of JSONArray .
So get productdata key value as JSONObject instead of JSONArray :
JSONObject jsonObject1 = jsonObject.getJSONObject("productdata");
You are getting productData as a JSONArray while it's a JsonObject which contains a JsonArray of images as I can see in the json link that you provided
JSONArray jsonArray1 = jsonObject.getJSONArray("productdata");
that line of code should be a JsonObject

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

My Simple Adapter Wont Populate my listview

I am creating an android application and my code will loop through the json data and if finds a match to the string that i have placed in ( in this case "Guil Hernandez") , then it will add that name to an array list of hashmaps. I then populate my listview with a simple adapter. Everything is working properly, but my listview will not appear. Am i doing this sorting "algorithm" wrong? Also if you know of a better way to do the sorting to find a match..PLEASE LET ME KNOW. i am still new to this. Thank you in advance!
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
full code here :
public class MyActivity extends ListActivity {
private JSONObject mNameDataJson;
private final String TAG = MyActivity.class.getSimpleName();
private final String KEY_NAME = "author";
private final String KEY_TITLE = "title";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
GetNameData getNameData = new GetNameData();
getNameData.execute();
}
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetNameData extends AsyncTask<Object, Void, JSONObject> {
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... objects) {
String nameUrl = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(nameUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
String responseString = response.body().string();
Log.v(TAG , responseString);
try {
jsonResponse = new JSONObject(responseString);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
mNameDataJson = jsonObject;
handleResponse();
}
}
}
If you want to compare strings use equals(). Like this:
if (name.equals("Guil Hernandez")) {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
}

Dynamically adding Groups and Headers to an Expandable List View

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

How to use Array-list in String array?

I am creating an image-view from JSON URL where I am pushing the URL in a array-list. Here is the code.
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(AnotherActivity.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);
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for (int i = 0; i < android.length(); i++)
{
map = new ArrayList<HashMap<String, String>>();
JSONObject c = android.getJSONObject(i);
// Storing each json item in variable
String flag = c.getString("flag");
HashMap<String, String> map = new HashMap<String, String>();
map.put("url",flag);
arraylist.add(i,"\"" + map.toString().substring(5).replace("}", "\""));
}
final String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
Log.v("url", "Creating view..." + imageUrl);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Now I want to use this array-list in a string array.
String[] IMAGES = new String[]{
};
How can I do that?? When I tried something like this
String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
I got the the log as
Creating view...[Ljava.lang.String;#41450ea0
Use Arrays.toString(array[]) method to print array as here you are getting [Ljava.lang.String;#41450ea0 Which isObject reference for array.
String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
Log.v("url", "Creating view..." + Arrays.toString(imageUrl));
Which will print array like this
[element1,element2...]
You can remove [ ] by the use of indexOf
String s= Arrays.toString(imageUrl);
s = s.substring(1, s.length()-1)

Categories

Resources