In my application I have an activity named Hospitals that extends an AppCompatActivity and I'm using parse to store my data. In parse I have a table called "Hospitals" with column called "Name"....I'm trying to retrieve the hospital names and display it in a list view for the users....but my code is only retrieving the first row from the table.
This is my code
public class Hospital extends AppCompatActivity {
private static final String Hospitals = "Hospitals";
private static final String HospitalName = "Name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital);
ListView list1 = (ListView)findViewById(R.id.list1);
ParseQuery query = new ParseQuery(Hospitals);{
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
final String[] str = {test.get(x).getString(HospitalName)};
final ArrayAdapter A1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,str);
list1.setAdapter(A1);
}
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Replace code
Problem is you are doing everything inside loop
You can use HashMap<String, String> for multiple column.
List<String> listHospital = new ArrayList<String>();
HashMap<String, String> mapHospital = new HashMap<String, String>();
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
mapHospital.clear();
mapHospital.put("hospitalName", test.get(x).getString(HospitalName));
mapHospital.put("address", test.get(x).getString("addressColumnName"));
mapHospital.put("number", test.get(x).getString("addressColumnNumber"));
list1.add(mapHospital);
}
final ArrayAdapter A1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list1);
list1.setAdapter(A1);
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You must have custom Adapter. if you want key/value means multiple column data
Related
I'm attempting to set an array in the ImageAdapter (pics) equal to JSON contents in the arrayList called mComments. I cannot seem to accomplish this by using a toArray() method on the mComments and also typecasting didn't work. I'm trying to use the JSON content to set the images in the GridView instead of the hard-coded resources. See my ImageAdapter class below and also the relevant calling class. Full classes available upon request and here is the JSON URL if that helps: https://shipstudent.com/complaint_desk/androidImageFetch.php. Please let me know if you need more information.
ImageAdapter:
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context=c;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView iv;
if (convertView == null) { // if it's not recycled, initialize some attributes
iv = new ImageView(context);
iv.setLayoutParams(new GridView.LayoutParams(350,350));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setPadding(8, 8, 8, 8);
} else {
iv = (ImageView) convertView;
}
iv.setImageResource(pics[position]);
return iv;
}
public Integer[] pics={
R.drawable.menu ,R.drawable.dog,
R.drawable.favorites,R.drawable.pmlimage,
R.drawable.progress,R.drawable.hearsay,
// R.drawable.sample_6,R.drawable.sample_7
};
}
Calling Class:
private JSONArray mComments = null;
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
categoryList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
// when parsing JSON stuff, we should probably
// try to catch any exceptions:
try {
// I know I said we would check if "Posts were Avail." (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String comment = c.getString(TAG_COMMENT);
String filename = c.getString(TAG_FILENAME);
String IDUser = c.getString(TAG_IDUser);
System.out.print(comment);
System.out.print(filename);
System.out.print(IDUser);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COMMENT, comment);
map.put(TAG_FILENAME, filename);
map.put(TAG_IDUser, IDUser);
// adding HashList to ArrayList
categoryList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
// ListAdapter adapter = new SimpleAdapter(this.getActivity(), categoryList,
// R.layout.categories_list, new String[] { TAG_CATEGORY_NAME }, new int[] { R.id.title });
//
// // I shouldn't have to comment on this one:
// setListAdapter(adapter);
//imageAdapter.pics = (Integer[]) categoryList.clone();
System.out.print(categoryList.toString());
}
I am tring to onitemclicklistener is working but content is not displayed.
Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG_details = "details";
ListView mListView; String tv_country_details;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://http://192.168.0.200/android/count.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{ {
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null)
{
sb.append(line);
}
data = sb.toString();
br.close();
}
catch(Exception e)
{
Log.d("Exception while downloading url", e.toString());
}
finally
{
iStream.close();
}
return data;
}
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>implements OnItemClickListener
{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
String visibility = jObject.getString("visibility");
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.iv_flag,R.id.tv_country_details};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
String tv_country_details = getIntent().getStringExtra("details");
Intent intent = new Intent(MainActivity.this, SingleMenuItemActivity.class);
intent.putExtra("TAG_details", tv_country_details);
startActivity(intent);; }
});
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String im,gUrl;
gUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(gUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
## Json Parser Code ##
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject) {
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("countries");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries) {
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String flag="";
String currencyName = "";
try {
flag = jCountry.getString("flag");
currencyName = jCountry.getJSONObject("currency").getString("currencyname");
String details = currencyName ;
country.put("flag", R.drawable.blank);
country.put("flag_path", flag);
country.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return country; }
public static Object optJSONObject(int arg2) {
// TODO Auto-generated method stub
return null;
}
public static boolean isNull(int arg2) {
// TODO Auto-generated method stub
return false;
}
}
## SingleMenuitemActivity code ##
List item
public class SingleMenuItemActivity extends Activity {
// JSON node keys
String tv_country_details;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
Intent i = getIntent();
// Get the result of rank
tv_country_details = i.getStringExtra("tv_country_details");
// Locate the TextViews in singleitemview.xml
TextView txttv_country_details = (TextView) findViewById(R.id.tv_country_details);
// Set results to the TextViews
txttv_country_details.setText(tv_country_details);
}
}
I want to display a loading process when my application is loading data from the database.
This is my Java file.
Where do I have to put the function to display the loading process?
public class AksesServerActivity extends ListActivity {
private static String link_url = "http://plnskh.zz.mu/android/berita/cekdaftar.php";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, daftar_artikel,
R.layout.list_item,
new String[] { AR_JUDUL, AR_CONTENT, AR_ID}, new int[] {
R.id.judul, R.id.content, R.id.kode});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode = ((TextView) view.findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(AksesServerActivity.this, DetailAksesServer.class);
in.putExtra(AR_ID, kode);
startActivity(in);
}
});
}
}
public class LongOperation extends AsyncTask<String, String, String>
{
ProgressDialog pdialog;
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdialog.dismiss();
this.adapter_listview();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(NewsActivity.this);
pdialog.setMessage("Loading");
pdialog.show();
}
}
for more clarification about asynchronous task and its methods, check here
You must use AsyncTask class, override doInBackground method to perform your databse fetch, onPreExecute method to show your loading and onPostExecute to hide it. you can refer AsynTask process and AsynTask post for more information
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// 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_EMAIL, email);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL },
new int[] { R.id.name, R.id.email });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
startActivity(in);
}
});
}
}
Using this Class am able to print data after Parsing In Listview name and email .
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
Button next;
Button Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
Previous = (Button) findViewById(R.id.button1);
next = (Button) findViewById(R.id.button2);
Previous.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
// getting intent data
getdata();
}
public void getdata() {
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
lblName.setText(name);
}
}
I have apply # button On For Next and another for previous if click on Next it should display Next id name in SingleMenuItemActivity Class if click on Previous it should display Previous id Name in SingleMenuItemActivity . please tell me how i ll do this . i have tried and doing First time BUt not able to do i don't know how i will call all Ids and create function so that it should work
I have applied # button On For Next and another for previous if click
on Next it should display Next id name in SingleMenuItemActivity Class
if click on Previous it should display Previous id Name in
SingleMenuItemActivity . please tell me how I Will do this.
=> You can fetch previous/next records by doing ++/-- id field, once you have that particular record in terms of Cursor, you can fetch and display particular field value and display the same in particular view.
Or
Second solution is to get all the records at a time and fetch previous/next record by using below methods:
mCursor.moveToNext() // for next record from cursor
mCursor.moveToPrevious() // for previous record from cursor
By looking at above different solutions, I would say 1st method is easy when you have thousands of records because there way you won't have to manage thousand of records but a single record. Decision can be taken based on the number of records and your requirement.
Update:
After having talk with you in #AndroidDev chatroom, I came to know your doubt exactly, you should have mentioned earlier and it could have saved time.
Anyway, now as you want to implement prev/next in your SingleMenuItemActivity and as you are already having contactList which you have prepared in AndroidJSONParsingActivity, I would suggest you to pass ArrayList<HashMap<String, String>> from AndroidJSNOParsingActivity to SingleMenuItemActivity.
Now, as you are having complete list, you can fetch prev/next item.
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private LinkedList<String> mListItems;
//private PullToRefreshView mPullRefreshListView;
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// 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_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is My parsing COde i m able to get String value now i have Put JsonParser class in My project .
public class PullToRefreshListActivity extends Activity {
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private PullToRefreshView mPullRefreshListView;
private ArrayAdapter<String> mAdapter;
private static String url = "http://api.androidhive.info/contacts/";
/** Called when the activity is first created. */
private LinkedList<String> mListItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh_listview);
mPullRefreshListView = (PullToRefreshView) findViewById(R.id.pull_refresh_list);
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
mPullRefreshListView.setLastUpdatedLabel(DateUtils
.formatDateTime(getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL));
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
ListView actualListView = mPullRefreshListView.getRefreshableView();
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
// You can also just use setListAdapter(mAdapter)
actualListView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems
.addFirst("Added after refresh..New Version Coming soon J-elly Bean");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
private String[] mStrings = { "A-stro", "B-ender", "C-upcake", "E-clair",
"F-royo", "G-ingerbread", "H-oneycomb", "I-ce Cream Sandwich ",
"Android Versions From iamvijayakumar.blogspot.com" };
}
This is Dummy Example for PullToRefreshListview which i did. Now I want to Integrate so that i can display data in ListView with Pull To Refresh. Can u please help me how to integrate? Where i will place code for parsing and all?? Please help me .
In the Dummy Example, You given simply replace Adapter creation by using the below which is used to set data using Hashmap list. TAG_ID etc are used to be columns. Create an xml with name row and put 4 textview in the row layout and give them names as below which I have used in int array. Then set this adapter to listview.
mAdapter= new SimpleAdapter(this, mylist, R.layout.row,
new String[] {TAG_ID, TAG_NAME, TAG_EMAIL,TAG_PHONE_MOBILE}, new int[]
{R.id.tvtagid, R.id.tvtagname, R.id.tvtagemail,R.id.tvtagphone});
In the above adapter mylist is an Arraylist of your HashMap objects.