how to pass id with url while requesting? - android

loginpage.java this is my activity for login page.
i am using this json for it {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
here i am getting one unique filed (user_login_id) when user log in successfully.it works fine.
after log in i am using Navigationdrawer which is Activity class and it has different types fragment behavior,one of them is HomeFragment which extended with Fragment.
in that HomeFragment class I want to get some json data in List view.for that I have another json file.which has following link like http://sdfkjksd.com/apps/matching?version=apps&user_login_id=2650
public class HomeFragment extends Fragment {
NavDrawerListAdapter adapters;
private ProgressDialog pDialog;
//JSON parser class
JSONParsing jsonParser = new JSONParsing();
String result = "";
List<HashMap<String,String>> aList;
private static final String TAG_USERID="user_login_id";
private static final String MATCH_URL = "http://sdfa.com/apps/matching?version=apps&user_login_id="+TAG_USERID;
JSONArray matching=null;
private static final String TAG_SUCCESS = "status";
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
ArrayAdapter<String> adapter;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//String strtext = getArguments().getString("user_login_id");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
/* Bundle bundle = this.getArguments();
if(bundle != null){
String i = bundle.getString("user_login_id", TAG_USERID);
}*/
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("version", "apps"));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(MATCH_URL, "POST",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
JSONObject Jasonobject = new JSONObject(result);
JSONArray Jarray = Jasonobject.getJSONArray("matching");
if (Jarray != null) {
// looping through All data
for (int i = 0; i < Jarray.length(); i++) {
JSONObject c = Jarray.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age);
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(
getActivity().getBaseContext(), aList,
R.layout.list_item_matchs, new String[] { TAG_NAME,TAG_PROFILE,TAG_IMAGE,TAG_CAST,TAG_AGE,TAG_LOCATION
}, new int[] {
R.id.txtproname,R.id.txtprofileage,R.id.propic,R.id.txtprofilecast,R.id.txtprofileplace});
// updating listview
listview.setAdapter(adapter);
}
});
}
private void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}
}
}
so the problem is , in that link i am using user_login_id field of login json,,so i want to send or pass that field during requesting with URL..

I just suggest you to use SharedPreference for this. When you get Login response, just parse the JSON and then get log_in_id field value and save it in SharedPreferences, then whenever you want to use this value you can use throughout your application.

you already used the same method in your doInBackground :
here is a suggested edit to prepare it for the next:
add "user_login_id" to params list
change POST to GET if it is so.
protected String doInBackground(String... args) {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("version", "apps"));
// add the user_login_id to params.
params.add(new BasicNameValuePair("user_login_id ", "265"));
// getting JSON string from URL
// I think you are using GET bcz the url shows the parameters.
String json = jsonParser.makeHttpRequest(MATCH_URL, "GET",
params);

Related

'for' statement does not loop (contact application)

I am trying to send the numbers of my contacts to the server to check if these numbers are contained in my database. All numbers contained in database and in the address list of the phone finally should be displayed in a listview.
While using the for each loop ('for (String phoneNumberString : aa)') I get this warning: 'for' statement does not loop...
How can I solve this problem?
public class AllUserActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_user = "http://.../.../.../get_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USER = "user";
private static final String TAG_PHONE = "phone";
private static final String TAG_UID = "uid";
private static final String TAG_USERNAME = "username";
String phoneNumber;
ArrayList<String> aa= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_user);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllUsers().execute();
getNumber(this.getContentResolver());
}
// get all numbers of contacts
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
// use the cursor to access the contacts
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneNumberString = phoneNumber.replaceAll("\\D+","");
// get phone number
System.out.println(".................."+phoneNumberString);
aa.add(phoneNumberString);
}
phones.close();// close cursor
}
class LoadAllUsers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUserActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (String phoneNumberString : aa){
params.add(new BasicNameValuePair("phone[]", phoneNumberString));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", params);
// Check your log cat for JSON response
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray users = json.getJSONArray(TAG_USER);
// looping through all contacts
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String uid = c.getString(TAG_UID);
String phone = c.getString(TAG_PHONE);
String username = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, uid);
map.put(TAG_PHONE, phone);
map.put(TAG_USERNAME, username);
// adding HashList to ArrayList
usersList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
AllUserActivity.this, usersList,
R.layout.list_users, new String[] { TAG_PHONE,
TAG_USERNAME},
new int[] { R.id.phone, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}}
}
You have a return statement at the end of your for loop, meaning it will go through the first element and return from your doInBackground() call.

How to create a listview to get text from web and image from folder

I make list that show text from database but the image near items. I need images that get from drawable folder in Android. It means in listview text from database and image from Android.
Code is:
public class Category extends Activity {
// progress dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> categoryList;
private static String url_books = "http://10.0.2.2/project/category.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_CATEGORY_NAME = "category_name";
private static final String TAG_MESSAGE = "massage";
// category JSONArray
JSONArray category = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
new LoadCategory().execute();
ListView imagelist=(ListView) findViewById(R.id.list_image);
imagelist.setAdapter(new imageview(this));
}
/**
* Background Async Task to Load category by making HTTP Request
* */
class LoadCategory extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Category.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);
// Check your log cat for JSON reponse
Log.d("category: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Getting Array of category
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
// Storing each json item in variable
String category_id = c.getString(TAG_CATEGORY_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CATEGORY_ID,category_id);
map.put(TAG_CATEGORY_NAME, category_name);
// adding HashList to ArrayList
categoryList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
System.out.println("no category found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListView lv=(ListView)findViewById(R.id.list_view);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Category.this,categoryList,
R.layout.category_item, new String[] { TAG_CATEGORY_NAME},
new int[] { R.id.category_name });
// updating listview
// setListAdapter(adapter);
lv.setAdapter(adapter);
}
});
}
}
In my code, i have text but no image. Any help?
Create a pojo for your needs in list items,You can set pojos values from web or local, then use custom listadapter override getView method according to ur needs. A good explanation here!

setListAdapter not working with Sherlock Fragment in Android

I made a list view to show parsed JSON data from an url! The same code is working fine without fragment but with fragment the setListAdapter is not working! I also tried getActivity().setListAdapter! Please check my code!
public class Uploads extends SherlockFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> uploadsList;
// products JSONArray
JSONArray uploads = null;
// Inbox JSON url
private static final String UPLOADS_URL = "http://my_url";
// ALL JSON node names
private static final String TAG_UPLOADS = "uploads";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DATE = "date";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container,
false);
// Hashmap for ListView
uploadsList = new ArrayList<HashMap<String, String>>();
// Loading INBOX in Background Thread
new LoadInbox().execute();
return rootView;
}
/**
* Background Async Task to Load all INBOX messages by making HTTP Request
* */
class LoadInbox extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Content...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Inbox JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(UPLOADS_URL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Inbox JSON: ", json.toString());
try {
uploads = json.getJSONArray(TAG_UPLOADS);
for (int i = 0; i < uploads.length(); i++) {
JSONObject c = uploads.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_DATE, "Date: " + date);
// adding HashList to ArrayList
uploadsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
Toast.makeText(getActivity(), "Content Loaded!", Toast.LENGTH_LONG)
.show();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(),
uploadsList, R.layout.list_items, new String[] {
TAG_NAME, TAG_DATE }, new int[] {
R.id.tvUploadTitle, R.id.tvUploadDate });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You need to change
public class Uploads extends SherlockFragment
To
public class Uploads extends SherlockListFragment
Or you need to have a listview in R.layout.fragmenttab2 initialize it and then set the adapter to listview.

JSONArray cannot be converted to JSONObject Android

I am trying to consume json data from a server in android app. the format of data which is from a cakePHP web app looks like this;
[{"Chapter":{"id":"1","chapter":"4","chaptertitle":"The Bill of Rights"}}]
and below is the java code am using to achieve my goal;
public class Sheria extends SherlockListFragment {
// Progress Dialog
// private ProgressDialog pDialog;
// private View view;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> chapterList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_projects/sanisani/today_getall.php";
private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CHAPTERS = "Chapter";
private static final String TAG_CHAP = "chapter";
private static final String TAG_CHAP_TITLE = "chaptertitle";
JSONArray chaps = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sheria, container, false);
new FetchDetails().execute();
return super.onCreateView(inflater, container, savedInstanceState);
}
class FetchDetails extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getSherlockActivity());
pDialog.setMessage("Fetching Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
chapterList = new ArrayList<HashMap<String, String>>();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url_chapters);
// Check your log cat for JSON reponse
Log.d("Chapters: ", json.toString());
try {
// Checking for SUCCESS TAG
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
// products found
// Getting Array of Products
chaps = json.getJSONArray(TAG_CHAPTERS);
System.out.println(chaps);
// looping through All Products
for (int i = 0; i < chaps.length(); i++) {
JSONObject c = chaps.getJSONObject(i);
// Storing each json item in variable
String chapter = c.getString(TAG_CHAP);
String chapter_title = c.getString(TAG_CHAP_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CHAP, chapter);
map.put(TAG_CHAP_TITLE, chapter_title);
// adding HashList to ArrayList
chapterList.add(map);
// getSherlockActivity().finish();
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Keys used in Hashmap
String[] from = { TAG_CHAP, TAG_CHAP_TITLE };
// Ids of views in listview_layout
int[] to = { R.id.chapter, R.id.chaptertitle };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity()
.getBaseContext(), chapterList, R.layout.sheriainfo, from,
to);
// Setting the adapter to the listView
setListAdapter(adapter);
}
}
}
When i run the code i get the error JSONArray cannot be converted to JSONObject.
Please help
Because you are getting a JSONArray not a JSONObject, try this:
JSONArray json = jParser.getJSONFromUrl(url_chapters);
and return JSONArray from getJSONFromUrl(String)
and also remove chaps = json.getJSONArray(TAG_CHAPTERS); because your TAG_CHAPTER is not an array.
And in the for loop do
JSONObject c = json.getJSONObject(i);
in place of
JSONObject c = chaps.getJSONObject(i);
Edit
public class Sheria extends SherlockListFragment {
// Progress Dialog
// private ProgressDialog pDialog;
// private View view;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> chapterList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_projects/sanisani/today_getall.php";
private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CHAPTERS = "Chapter";
private static final String TAG_CHAP = "chapter";
private static final String TAG_CHAP_TITLE = "chaptertitle";
JSONArray chaps = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sheria, container, false);
new FetchDetails().execute();
return super.onCreateView(inflater, container, savedInstanceState);
}
class FetchDetails extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getSherlockActivity());
pDialog.setMessage("Fetching Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
chapterList = new ArrayList<HashMap<String, String>>();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
/*
HERE in the method getJSONFromUrl() convert the String u get from server into
JSONArray not JSONObject
*/
JSONArray json = jParser.getJSONFromUrl(url_chapters);
// Check your log cat for JSON reponse
Log.d("Chapters: ", json.toString());
try {
// Checking for SUCCESS TAG
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
// products found
// Getting Array of Products
// chaps = json.getJSONArray(TAG_CHAPTERS);
// System.out.println(chaps);
// looping through All Products
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
JSONObject jObj = c.getJSONObject("TAG_CHAPTERS ");
// Storing each json item in variable
String chapter = jObj.getString(TAG_CHAP);
String chapter_title = jObj.getString(TAG_CHAP_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CHAP, chapter);
map.put(TAG_CHAP_TITLE, chapter_title);
// adding HashList to ArrayList
chapterList.add(map);
// getSherlockActivity().finish();
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Keys used in Hashmap
String[] from = { TAG_CHAP, TAG_CHAP_TITLE };
// Ids of views in listview_layout
int[] to = { R.id.chapter, R.id.chaptertitle };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity()
.getBaseContext(), chapterList, R.layout.sheriainfo, from,
to);
// Setting the adapter to the listView
setListAdapter(adapter);
}
}
}

Parsed JSON Data not displaying on android

I have a JSON string which is generated by a php file. The problem is that the JSON string is not appearing on the textview of android. can anyone explain why?
public class AllUsersActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UID = "UserID";
private static final String TAG_FIRSTNAME = "FirstName";
// users JSONArray
JSONArray users = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_users);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllusers().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String uid = ((TextView) view.findViewById(R.id.uid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
UserDetailsActivity.class);
// sending uid to next activity
in.putExtra(TAG_UID, uid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllusers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUsersActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All users from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
// Check your log cat for JSON reponse
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
// looping through All users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_FIRSTNAME, name);
// adding HashList to ArrayList
usersList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUsersActivity.this, usersList,
R.layout.list_item, new String[] { TAG_UID,
TAG_FIRSTNAME},
new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
this is the JSON string from the PHP file
{"Users":[{"0":[],"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"0":[],"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null,"1":[]},{"0":[],"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null,"1":[],"2":[]},{"0":[],"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null,"1":[],"2":[],"3":[]}],"success":1}
I've found the error.
It is caused by case sensitiveness.
users --> Users
Mistake on my part. Sorry.
Thanks for trying to help me!

Categories

Resources