I tried to make a simple application that will take the API from the internet, rearrange them and show as list.
In the emulator it works. The phone shows a white screen. The phone has Android 2.3.7. But when I tried it on the tablet, the app stopped working. The tablet has Android 4.1.
MainActivity
public class MainActivity extends ListActivity implements OnItemClickListener{
private ProgressDialog pDialog;
private String url = "http://www.cscpro.org/secura/market/"; //food-29-5.json;
private String res;
private String ql;
JSONArray market;
final static String RESOURCES = "res";
final static String QUALITY = "q";
private static final String TAG_OFFER = "offer";
private static final String TAG_PRICE = "price";
private static final String TAG_SALLER = "seller";
private static final String TAG_SALLER_NAME = "name";
ArrayList<HashMap<String, String>> listSaller;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listSaller = new ArrayList<HashMap<String, String>>();
Intent in = getIntent();
res = in.getStringExtra(RESOURCES);
ql = in.getStringExtra(QUALITY);
ListView lv = getListView();
lv.setOnItemClickListener(this);
// Calling async task to get json
new GetContacts().execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String rate = ((TextView) view.findViewById(R.id.rate)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_PRICE, rate);
in.putExtra(TAG_SALLER_NAME, name);
startActivity(in);
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String myURL = url+res+"-29-"+ql+".json";
String jsonStr = sh.makeServiceCall(myURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
market = jsonObj.getJSONArray(TAG_OFFER);
// looping through All Contacts
for (int i = 0; i < market.length(); i++) {
JSONObject c = market.getJSONObject(i);
String rate = c.getString(TAG_PRICE);
// Phone node is JSON Object
JSONObject saller = c.getJSONObject(TAG_SALLER);
String name = saller.getString(TAG_SALLER_NAME);
// tmp hashmap for single contact
HashMap<String, String> sallers = new HashMap<String, String>();
// adding each child node to HashMap key => value
sallers.put(TAG_PRICE, rate);
sallers.put(TAG_SALLER_NAME, name);
// adding contact to contact list
listSaller.add(sallers);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, listSaller,
R.layout.list_item, new String[] { TAG_PRICE, TAG_SALLER_NAME}, new int[] { R.id.rate,
R.id.name});
setListAdapter(adapter);
}
}
}
SingleContactActivity
public class SingleContactActivity extends Activity {
// JSON node keys
private static final String TAG_PRICE = "price";
private static final String TAG_SALLER_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String rate = in.getStringExtra(TAG_PRICE);
String name = in.getStringExtra(TAG_SALLER_NAME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblRate = (TextView) findViewById(R.id.rate_label);
lblName.setText(name);
lblRate.setText(rate);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_single_contact.xml is a simple LinearLayout with two TextViews.
Related
I have list of cities in listview and now i want to add searchview in listview to search the item by specific letter like when i enter D in search view then all the cities should show with D in listview can anyone help me how can i do this i am new to android plaese help me.
this is my code in in this code only is showing in listview now i want to add searchview item please help
public class CityNameActivity extends ListActivity {
ListView list;
EditText inputSearch;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
inputSearch = (EditText) findViewById(R.id.inputSearch);
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String cityId= citylist.get(position).get(TAG_ID);
Intent in = new Intent(getApplicationContext(),
HospitalList_Activity.class);
in.putExtra("city_id",cityId);
startActivity(in);}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_ID, id);
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}}
cityname_activity_main.xml
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
city_list_item.xml
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"
android:textStyle="bold" />
I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.
i used a list view in my app.i used scroll bar for update the details. i got complete updated list again.which added all the data in ny list. i wants to avoid it so plz suggest me how i retrict the duplicate values in list after updation.... my code snippet is here.....
public class MainActivity extends ListActivity implements SwipeRefreshLayout.OnRefreshListener {
private ProgressDialog pDialog;
ListView mListView;
SwipeRefreshLayout swipeLayout;
Adapter mAdapter;
// URL to get contacts JSON
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";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
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 single contact activity
Intent in = new Intent(getApplicationContext(),
ak.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
//Dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
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 node is 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);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/* if (pDialog.isShowing())
pDialog.dismiss();*/
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.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);
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new GetContacts().execute();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
The only thing you have to do is set adapter like this way and it won't replicate data. It just add new data below older one.
adapter = null;
if (adapter == null) {
adapter = new CustomAdapter(this, arrayList);
listvie.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
Hope it will work.
Thanks. :)
Solution is very simple.
Create ListAdapter before executing AsyncTask with empty Collection
Set adapter for ListView with created adapter
In AsyncTask create local field ArrayList<HashMap<String, String>> localList
Parsed contacts put to localList, not to contactList
After download items, clear Collection by calling contactList.clear();
Add download contacts contactList.addAll(localList);
Call adapter.notifyDataSetChanged();
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
I have created a listview with headers but I am unable to group items that fall under the same header.
Can someone advise me on what I should do?
Below are the codes to display the items into the listview:
public class OrganizationList extends Activity implements OnClickListener {
ListView lv;
SimpleAdapter simpleAdapter;
ArrayList<HashMap<String, String>> videosList;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONArray videos = null;
// url to get all videos
private static String url_video = "http://10.0.2.2/android_connect/get_organization.php";
//JSON Nodes
private static final String TAG_POSITION = "position";
private static final String TAG_URL = "URL";
private static final String TAG_MEMBER = "name";
private static final String TAG_SUCCESS = "success";
private static final String TAG_NAME = "members";
protected static final int GET_INTENT_CODE = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video);
Button refresh = (Button)findViewById(R.id.btn_refresh);
refresh.setOnClickListener(this);
TextView header = (TextView)findViewById(R.id.text_header);
header.setText("Videos (视频)");
ImageButton home = (ImageButton)findViewById(R.id.btn_home);
home.setOnClickListener(this);
// Hashmap for ListView
videosList = new ArrayList<HashMap<String, String>>();
//Get adapter
simpleAdapter = new SimpleAdapter(OrganizationList.this, videosList, R.layout.list_date_item, new String[] {TAG_POSITION, TAG_MEMBER},
new int[] { R.id.text_header, R.id.name});
//Get Listview
lv = (ListView) findViewById(R.id.lst_name);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String videoName = ((TextView) view.findViewById(R.id.name)).getText()
.toString();
Log.d("row click:", videoName);
}
});
// Loading videos in Background Thread
new LoadAllVideos().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllVideos extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OrganizationList.this);
pDialog.setMessage("Loading" + "\n" + "Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All videos 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_video, "GET", params);
// Check your log cat for JSON reponse
Log.d("All videos: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// videos found
// Getting Array of videos
videos = json.getJSONArray(TAG_NAME);
// looping through All videos
for (int i = 0; i < videos.length(); i++) {
JSONObject c = videos.getJSONObject(i);
// Storing each json item in variable
String post = c.getString(TAG_POSITION);
String name = c.getString(TAG_MEMBER);
//videosList.add(c.getString(TAG_COMPANY));
//Log.d("item Name:", name);
//Log.d("companyNAme", videosList.get(0));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_POSITION, post);
map.put(TAG_MEMBER, name);
// adding HashList to ArrayList
videosList.add(map);
//System.out.println(map);
}
}
else {
}
} 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 videos
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// ListView Adapter
lv = (ListView) findViewById(R.id.lst_name);
lv.setAdapter(simpleAdapter);
}
});
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btn_refresh)
{
videosList.clear();
new LoadAllVideos().execute();
}
else if(v.getId() == R.id.btn_home)
{
Intent intent = new Intent();
intent.setClassName("com.scba", "com.scba.Menu");
finish();
}
}
}
Screenshot:
just change your itemxml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/grayimage"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="president"
android:id="#+id/headerText"
/>
</FrameLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Prof. Dr. Khanuka"
android:id="#+id/DiscriptionText"
/>
</LinearLayout>
And then create Your Custem List from Here custom list
and edit your code according to you
Thanks