How to use Array-list in String array? - java

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)

Related

Json parsing errors at android

I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.

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

Android parsing Json error

I having an error while parsing json array in my android application.
My json object is in the following form:
{"post":[
[{"0":"all the best to every one...!!","post":"all the best to every one...!!"},
{"0":"hello every one...","post":"hello every one..."}]
]}
My java file in android is as follows:
public class Newsactivity extends ListActivity {
private static final String TAG_SUCCESS = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> postsList;
private static String url_all_products = "myurl";
private static final String TAG_POST = "post";
JSONArray posts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allposts);
postsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Newsactivity.this);
pDialog.setMessage("Loading posts. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("All Posts: ", json.toString());
try {
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Newsactivity.this, postsList,
R.layout.singlepost, new String[] { TAG_POST},
new int[] { R.id.pid});
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_newsactivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am getting a fatal exception starting this activity. This code is modified code of an online tutorial on json parsing. As I am new to android I am unable to find where the id is. So, please help me. Thank you.
I am afraid that your json format is "a little bit strange" (or i may say it is in a different format with what your code is trying to do) according to your code.
As you can see, there are two "[" after the first "post", which means the array of elements is actually inside another array.
{"post":[ // first '['
[ // second '['
{"0":"all the best to every one...!!","post":"all the best to every one...!!"},
{"0":"hello every one...","post":"hello every one..."}
]
]}
so to make it correct, do following
try {
posts = json.getJSONArray(TAG_POST);
posts = posts.getJSONArray(0) // to get the first array
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
as your json responce having nested array you need to code like this...
JSONObject json; = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("All Posts: ", json.toString());
try {
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.length(); i++) {
subposts = posts.getJSONArray(i);
for (int j = 0; j < subposts.length(); j++) {
JSONObject c = subposts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_POST, post);
postsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.getJSONArray(0).length(); i++) {
JSONObject c = posts.getJSONArray(0).getJSONObject(i);
String post = c.getString("0");
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}

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.

Parse Json Object in android?

I am developing one application in that i have to receive data from server ,I am successfully read data . here i have problem i receive data from server code wrote in AsyncTask,and send data from AsyncTask to My activity,here i send only one data out of three,my json object have 3 objects.i can get 3 objects in AsyncTask but not getting in Activity
my AsyncTask
public class ReceivingLatLongAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
Context mContext;
JSONArray jsonArryDetails=null;
public static final String DETAILS = "locations";
public static final String LAT = "lat";
public static final String LNG = "lng";
public static final String ADDRESS = "address";
public static final String CTIME = "ctime";
private String lat1;
private String lng1;
private String address1;
private String time1;
public ReceivingLatLongAsync(Context context){
this.mContext = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler serviceHandler= new ServiceHandler();
String jSonString = `serviceHandler.makeServiceCall
(TrafficConstants.RECIEVE_LATLON_POL_URL, ServiceHandler.POST);`
Log.e("Response: ", "> " + jSonString);
if(jSonString != null){
try {
JSONObject jsonObject = new JSONObject(jSonString);
jsonArryDetails = jsonObject.getJSONArray(DETAILS);
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
Log.e("ADDRESS1", address1);
Log.e("TIME2",time1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
Intent intent = new Intent(mContext,GetLatLongForTPActivity.class);
intent.putExtra("LAT", lat1);
intent.putExtra("LNG", lng1);
intent.putExtra("ADDRESS", address1);
intent.putExtra("time",time1);
mContext.startActivity(intent);
}
}
my activty
public class GetLatLongForTPActivity extends FragmentActivity
implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
Log.e(" NEW LATLONG",anotherLAT);
}
Becouse it is an jsonArray and now you send only the last object not the entier array
Change this
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
to
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
You have to add something like
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for(int i = 0;i<jsonArryDetails.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
map.put(LAT, lat1);
map.put(LNG, lg1);
map.put(ADDRESS, address1 );
map.put(CTIME, time1 );
mylist.add(map);
}
In for loop change the index :
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =jsonArryDetails.getJSONObject(i);
//etc ^ //change here
You need to create a class that stores the four fields you are using (lat,long,address,time), make that object parable, you could use this example: http://aryo.lecture.ub.ac.id/android-passing-arraylist-of-object-within-an-intent/ ;
And after that you can attach the array to the intent using:
intent.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
This would be the correct way to handle this, even if it's a little more complicated then you originally would have hoped.

Categories

Resources