hi please answer my question
i have this code in eclipse for Android Developing.
i am using mysql and php for database and get data with JSON . But i dont know how can i use JSONparse data in listview . please edit my codes.
public class ViewAllPersons extends Activity {
String url = "http://192.168.1.206/androhp/view_all_persons.php";
ArrayList<String> result;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_person);
result = new ArrayList<String>();
LoadAllPersons lap = new LoadAllPersons();
lap.execute(url);
}
class LoadAllPersons extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
InputStream jsonStream = getStreamFromURL(args[0], "GET");
String jsonString = streamToString(jsonStream);
parseJSON(jsonString);
return null;
}
void parseJSON(String JSONString) {
try {
JSONObject jo = new JSONObject(JSONString);
JSONArray allpersons = jo.getJSONArray("allpersons");
for (int i = 0; i < allpersons.length(); i++) {
JSONObject object = allpersons.getJSONObject(i);
String objString = "";
objString = object.getString("name") + " , "
+ object.getString("name2") + " : "
+ object.getInt("iconlink");
result.add(objString);
}
} catch (JSONException e) {
}
}
protected void onPostExecute(String file_url) {
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
CustomList adapter = new
CustomList(ViewAllPersons.this, web, imageUrl);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
How can I use parseJSON data instead of web listview :
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
You have got both data as well as list, now you need to combine them.
first you have to convert your json result into list, where values are your json values.
final ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listdata .add(values[i]);
}
then you have to assign adapter to your list. You can use following code.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.yourlistlayout, listdata );
list.setAdapter(adapter);
More details
http://www.vogella.com/tutorials/AndroidListView/article.html
Related
I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
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);
}
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);
}
}
}
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);
}
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.