How to fill ListView with Adapters - java

I'm aware that this is very simple question but I'm a newbie in Android development so please go easy on me.
Problem that I have is in one of the fragments (AsyncTask specifically) that lays in my main activity.
AsyncTask sends out data to php script which then returns according data in json format. This is then processed and saved to jsonlist array. Up until post execute everything works fine data is downloaded, processed etc. However when program reaches post execute problems start to pop out. And basically i'm unable to list out all the data from jsonlist to listview
//setting up an array
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
//creating list view variable
ListView listview;
//Define work in progress dialog
private ProgressDialog mProgressDialog;
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait");
// Set progressdialog message
mProgressDialog.setMessage("Fetching data...");
mProgressDialog.setIndeterminate(false);
}
#Override
protected Boolean doInBackground(String... params) {
//To do in the background
//Define variable of JSON parser type
JSONParser jParser = new JSONParser();
//Pass url to json parser class to fetch and save it into array variable
JSONArray json = jParser.getJSONFromUrl(url);
//loop from 0 to length of an array by increasing by 1
for (int i = 0; i < json.length(); i++) {
//Try and catch routine to prevent any crashes
try {
//Get an object defined in { ... } in original json file
JSONObject c = json.getJSONObject(i);
//Separate object by obtaining values for each of the sections
String vtitle = c.getString(title);
String vcontent = c.getString(content);
String vuser = c.getString(user);
HashMap<String, String> map = new HashMap<String, String>();
//Fill up an array with data extracted
map.put(title, vtitle);
map.put(content, vcontent);
map.put(user, vuser);
//Add values into jsonlist
jsonlist.add(map);
} catch (JSONException e)
{
//In case of any error Stack trace will be returned
e.printStackTrace();
}
}
//Once everything has been done return null value
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
//listview = (ListView) findViewById(R.id.list);
// Set the adapter to the ListView
//listview.setAdapter(adapter);
//Get rid off dialog when operation of fetching data has been done
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
As you can see i have tried the commented code but listview = (ListView) findViewById(R.id.list); returns following error:
Cannot resolve method findViewById(int)
which prevents me from executing program. This is very upsetting because I literally have all the data i need in an array but only one line of code stops me from displaying it.
I have also tried:
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
setListAdapter(adapter);
lv = getListView();
But as in previous case error of unresolved method is returned. Which is due to the fact that fragment is extended by fragment and adding anything to it crashes it
public class Fragment2 extends Fragment, ListActivity {...}

Add this to your code in Fragment2 class.
private ListView listview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);
listview = (ListView) v.findViewById(R.id.R.id.list);
return v;
}

Since you are in a Fragment you have to call getView() before findViewById, like this
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
listview = (ListView) getView().findViewById(R.id.list);

Related

Unable to update my user interface in Android as I update my Mysql database

I am working on an e-commerce app.
I am using mysql database from siteground and retrieving data using Volley class. The problem is as I am filling any new data in my table, it should also reflect in my fragment as I re-open my fragment, but it is not happening.
I have to uninstall my app and then re-run the android code and then I can see the data updated in my recycler view. I am using String request class in to retrieve data. I don't know what is the problem; is it something that I am not able to close the fragment properly and it is loading the previous data until I don't uninstall it?
This is my fragment.
public class Fragment_Women_Apparels extends Fragment {
private View v;
private RecyclerView recyclerView;
ArrayList<String> id1,name,brand,gender,discount,desc,sellprice,markprice,rating,type,size,category,length,
image1,image2,image3,image4,image5,shop,color,stock,material;
//5cbytcuv57x4
ProgressBar progressBar;
Animation animation;
public Fragment_Women_Apparels() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_women__apparels_, container, false);
progressBar=v.findViewById(R.id.progress);
animation= AnimationUtils.loadAnimation(getActivity(),R.anim.rotate);
progressBar.startAnimation(animation);
id1=new ArrayList<>();
name=new ArrayList<>();
brand=new ArrayList<>();
gender=new ArrayList<>();
discount=new ArrayList<>();
desc=new ArrayList<>();
sellprice=new ArrayList<>();
markprice=new ArrayList<>();
rating=new ArrayList<>();
type=new ArrayList<>();
size=new ArrayList<>();
category=new ArrayList<>();
length=new ArrayList<>();
image1=new ArrayList<>();
image2=new ArrayList<>();
image3=new ArrayList<>();
image4=new ArrayList<>();
image5=new ArrayList<>();
shop=new ArrayList<>();
color=new ArrayList<>();
stock=new ArrayList<>();
material=new ArrayList<>();
recyclerView=v.findViewById(R.id.recycler);
// recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2,RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
RequestQueue rq = Volley.newRequestQueue(getActivity());
String url = "-------------------MY-----API-----------------------";
StringRequest sr= new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("result");
for(int i =0;i<ja.length();i++)
{
JSONObject jo1 = ja.getJSONObject(i);
String ID=jo1.getString("ID");
String NAME=jo1.getString("NAME");
String BRAND=jo1.getString("BRAND");
String GENDER=jo1.getString("GENDER");
String DISCOUNT=jo1.getString("DISCOUNT");
String DESC=jo1.getString("DESCRIPTION");
String SELLPRICE=jo1.getString("SELLPRICE");
String MARKPRICE=jo1.getString("MARKPRICE");
String RATING=jo1.getString("RATING");
String TYPE=jo1.getString("TYPE");
String SIZE=jo1.getString("SIZE");
String CATEGORY=jo1.getString("CATEGORY");
String LENGTH=jo1.getString("LENGTH");
String IMAGE1=jo1.getString("IMAGE1");
String IMAGE2=jo1.getString("IMAGE2");
String IMAGE3=jo1.getString("IMAGE3");
String IMAGE4=jo1.getString("IMAGE4");
String IMAGE5=jo1.getString("IMAGE5");
String SHOP=jo1.getString("SHOP");
String COLOR=jo1.getString("COLOR");
String STOCK=jo1.getString("STOCK");
String MATERIAL=jo1.getString("MATERIAL");
id1.add(ID);
name.add(NAME);
brand.add(BRAND);
gender.add(GENDER);
discount.add(DISCOUNT);
desc.add(DESC);
sellprice.add(SELLPRICE);
markprice.add(MARKPRICE);
rating.add(RATING);
type.add(TYPE);
size.add(SIZE);
category.add(CATEGORY);
length.add(LENGTH);
image1.add(IMAGE1);
image2.add(IMAGE2);
image3.add(IMAGE3);
image4.add(IMAGE4);
image5.add(IMAGE5);
shop.add(SHOP);
color.add(COLOR);
stock.add(STOCK);
material.add(MATERIAL);
}
Log.d("abcde",id1.get(0));
progressBar.clearAnimation();
progressBar.setVisibility(View.INVISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(new RecyclerAdapter(getActivity(),id1,name,brand,gender,discount,desc,sellprice,markprice,
rating,type,size,category,length,image1,image2,image3,image4,image5,shop,color,stock,material));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.clearAnimation();
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(getActivity(),"Please check your internet connection...",Toast.LENGTH_LONG).show();
}
});
rq.add(sr);
return v;
}
}
I am receiving each element of JSONArray in an ArrayList and then passing the ArrayList in recyclerView.
The question is if I reload this fragment this should show the updated data in database but it is not happening
Finally I got the solution... The problem was that i was using Volley library which has a feature of caching enable by default.... So whenever I updated my database things were not reflected on the UI because of the cache that was saved for that particular API... So every time i had to clear the app cache to see the changes from database...
The solution is before adding the StringRequest to RequestQueue disable the caching feature by using the function of StringRequest class
sr.setShouldCache(false) ;
rq.add(sr) ;
where sr and rq are the objects of StringRequest and RequestQueue classes...

Android: Checking If Arraylist is Empty JSON

Im using https://github.com/thest1/LazyList as my listview
i wonder how will i check if the listview is Empty or when null?
this is the sample codes from the post Execute
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
Please help !
I tried this code from what i've searched
if(!arraylist.isEmpty()){
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
//o_total.setText("aaa");
// Close the progressdialog
mProgressDialog.dismiss();
}else{ String msg = "No records found in Database!";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
Intent home_in = new Intent ( OrderSum.this,
Home.class );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
but i still got the error
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"
To check if a listView is null:
listView != null;
To check if a listView dont have elements:
listView.getAdapter().getCount()<=0;

How to filter database output? (android PHP)

I am building an mobile app in where a user logs in and it outputs the contents of my database table which is named "announcements".
What I'm trying to do is to filter out these output based on the "department" column from the "accounts" table in which the users are stored.
The "announcements" table has the column named "receiver".
The contents will only show if the "department" column of the user logged in has the same value as the "receiver column" of the "announcements" column or if the value of the receiver is "all".
How do I do this?
My PHP script
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="sunshinedb"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from announcement";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['services'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Java class
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog;
JSONParser jsonParser = new JSONParser();
String email;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/services.php";
String user_id;
// ALL JSON node names
private static final String TAG_TRANS_ID = "announcement_id";
private static final String TAG_DATE = "date";
private static final String TAG_SERVICES = "title";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
// get listview
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
Single_List.class);
String transaction_id = ((TextView) view
.findViewById(R.id.transac_id)).getText().toString();
i.putExtra("announcement_id", transaction_id);
startActivity(i);
}
});
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(VideosActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading Services");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(url);
// Check your log cat for JSON reponse
Log.d("Service history ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Locate the array name
jsonarray = json.getJSONArray("services");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
String transac_id = json.getString(TAG_TRANS_ID);
String date = json.getString(TAG_DATE);
String service = json.getString(TAG_SERVICES);
// Retrive JSON Objects
map.put(TAG_SERVICES, service);
map.put(TAG_DATE, date);
map.put(TAG_TRANS_ID, transac_id);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
VideosActivity.this, arraylist,
R.layout.listview_services, new String[] {
TAG_TRANS_ID, TAG_SERVICES, TAG_DATE },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
You are not making any filtering anywhere in your code...
The steps to do it should be these ones (in this order) :
Android side : Calling your webservice (PHP code) with the user's department (in GET or POST parameter)
WS side : Requesting your database with something like SELECT * FROM announcement WHERE receiver = '<department'> OR receiver = 'ALL' where department is the user's department
WS side : Construct the JSON response
Android side : Process the JSON response to display results
The advantages of making it like this :
Limit the number of data transfered (limit network consumption on the Android device and you limit the load on your PHP server)
Limit the number of data processed Android side (limit the load of the Android app : it's not a desktop app ! Never forgive it !)
PS : reading your post and your comment, I really think you should look into these points before starting to make your app : SQL request, PHP MySQL access (as pointed out by #Jay Blanchard), Web services and HTTP protocol, Android AsyncTask

USING collections in Android

I was looking at this code while surfing through Stackoverflow
CODE::
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
static String PRICE= "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("--------------URL----------");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("ARRAY");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("collegeNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("collegeTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("collegeIMAGE"));
map.put(MainActivity.DISTANCE, jsonobject.getString("collegeDISTANCE"));
map.put(MainActivity.RATING, jsonobject.getString("collegeRATING"));
map.put(MainActivity.PRICE, jsonobject.getString("collegePrice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
My Question is Why we use collection in android ?
What is the use ?
Why a hashmap is added to ArrayList in the above code ?
Can't we directly set views in android without collection,( I tried
it dosent work when dealing with group of key,value pairs)
.
~ I am a newbie so please go easy on with answers to my questions
I'm not sure how to answer your first 2 questions about collections... but I'll give it a shot.
1, 2) Collections are good for keeping groups of information lumped together and accessible through 1 variable. They also make it very easy to iterate over them, which makes them ideal for things like ListView adapters since that is also a list (or a collection).
Consider the following if you dont have an array
String var1 = "hi1";
String var2 = "hi2";
String var3 = "hi3";
String var4 = "hi4";
String var5 = "hi5";
String var6 = "hi6";
String var7 = "hi7";
String var8 = "hi8";
String var9 = "hi9";
// do something with the variables
Toast.makeText(this, var1, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var3, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var4, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var5, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var6, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var7, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var8, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var9, Toast.LENGTH_SHORT).show();
Now consider this, if you have arrays:
ArrayList<String> vars = new ArrayList<String(9);
for (int i = 1; i <= 9; i++)
{
vars.add("hi" + i);
Toast.makeText(this, vars.get(i), Toast.LENGTH_SHORT).show();
}
Much, much easier to work with.
3) The Hashmap is added to the array because the author wanted to keep a collection of separate name/value pairs. You can't have multiple keys with the same value in a Hashmap, so if you want that then you have to make a new Hashmap. The adding them to an array was to keep it neat, and then allowed the author to pass the array to a ListView adapter for displaying the values to the user using Android's built-in mechanism.
Basically the author created this Hierarchy:
item1
name
type
flag
distance
rating
price
item2
name
type
flag
distance
rating
price
item3
name
type
flag
distance
rating
price
...etc...
So when the ListView iterated over the array, each separate collection of hashmap values will be available to a new listview item for displaying.
4) You can set values directly, but working with adapters in ListViews makes it much less of a chore. You create an array, pass the array to the listview, and bada-bing-bada-boom, there's your list. Otherwise you will be creating ListView items and setting the display text all yourself for each item. In a similar way to why collections are useful when you have many variables of the same type, passing that collection to a ListView makes it much, much easier to code, maintain, and troubleshoot, not to mention that it just works!
I hope this helps! We are all beginners once :)
This piece of code will go populate an ListView, there are several ways to do that. I believe in this case, the coder is SimpleAdapter http://developer.android.com/reference/android/widget/SimpleAdapter.html.
Some think like:
// In This case the value os NAME is shown on android.R.id.text1 (TextView)
// and PRICE is shown on android.R.id.text2 (TextView)
String[] from = new String[]{MainActivity.NAME, MainActivity.PRICE}; // Map keys
int[] to = new int[]{android.R.id.text1, android.R.id.text2}; // List Layout item views
SimpleAdapter adapter = new SimpleAdapter(context, arraylist, android.R.layout.simple_list_item_2, String[] from, int[] to);
listview.setAdapter(adapter);

Fatal exception caused by android.os.NetworkOnMainThreadException

As I am a beginner to Android programming, I was trying to run some tutorials, but upon running the programs( the source code is available here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ) I got an error.
The program is supposed to read in data from a website and process it, but I think there is something wrong with the networking part.
I am fully aware there have been similar questions here on SO, yet I had no clue how to solve it, perhaps anyone could give solutions which I also can understand.
Strange NetworkOnMainThreadException in Android app?
This is a questions which was asked earlier and is identical to my problem, but I had no clue what they are trying to say there, i.e. "To fix you just need to move any thing that is touching the network to its own thread." makes no sense to me whatsoever..
Can anyone please shed some light on this?
Use an AsyncTask to move your network operation off of the main/ui thread and onto a background/worker thread.
Expanding on the example from the tutorial, wrap the JSON stuff inside of an anonymous AsyncTask:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Void, Void, JSONObject>() {
protected JSONObject doInBackground(Void... args) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
return jParser.getJSONFromUrl(url);
}
protected void onPostExecute(JSONObject json) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
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();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
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();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}.execute((Void) null);
}

Categories

Resources