JSONObject cannot be converted to JSONArray in android - java

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

Related

Asynctask: pass values from doInBackground to onPostExecute

I´m new in Java programming and have a question. I found this post and tried to use this method to pass my values from doInBackground method to onPostExecute method. But Android Studio 2.3 does not allow it.
Android Studio underline my #Override at onPostExecute:
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create adapter for ListView (Universal Image Loader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
and my QueryResult in doInBackground:
#Override
protected QueryResult doInBackground(String... params){
try
{
Here is all the code:
public class MultiplyTask extends AsyncTask<String,Void,ArrayList<Artikel>>{
private class QueryResult {
ArrayList<Artikel> dataList;
public QueryResult(ArrayList<Artikel> dataList) {
this.dataList = dataList ;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create Adapter for ListView (UniversalImageLoader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
String data ="";
#Override
protected QueryResult doInBackground(String... params){
try
{
URL url = new URL("https://myjson.com");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][5];
//Fill Array with response
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("Artikelnummer"));
matrix[i][1] = String.valueOf(obj.getDouble("Preis"));
matrix[i][2] = obj.getString("Von");
matrix[i][3] = obj.getString("Bis");
matrix[i][4] = obj.getString("art_link");
}
//new Arrays
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
//Array sort
for (int i = 0; i < matrix.length; i++) {
all_art_nr[i] = matrix[i][0];
all_preis[i] = matrix[i][1];
all_von[i] = matrix[i][2];
all_bis[i] = matrix[i][3];
all_link[i] = matrix[i][4];
}
//Fill Arraylist
ArrayList<Artikel> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
Artikel angebote = new Artikel(all_art_nr[i], all_preis[i], all_von[i], all_bis[i], all_link[i]);
dataList.add(angebote);
}
return new QueryResult(dataList);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Android Studio want to change QueryResult into Arraylist and the #Override does not override method from his superclass, if i take QueryResult in doINBackground out, he can override the superclass method. Thanks in advance.
When you extends the Asynctask check the parameter:
extends Asynctask<Params, Progress, Result>
So if you want to pass a String to your doInBackround which will return a QueryResult to your onPostExecute you should extends like this:
extends Asynctask<String, Void, QueryResult>

Parsing multiple JsonObject and JsonArray

I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}

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.

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

Categories

Resources