Json String to Image - android

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

Related

When we click on item in listview then how we get id of that item

I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this
can anyone tell me how can i do this please
public class CityNameActivity extends ListActivity{
ListView list;
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 = "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();
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) {
Intent in = new Intent(getApplicationContext(),
Specialities_Activity.class);
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_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);
}
}
Code of Service Handlerclass:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city
public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list_);
ListView listView=getListView();
hospitallist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
startActivity(in);
}
});
new GetHospitals().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetHospitals extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HospitalList_Activity.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
Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);
// looping through All Cities
for (int i = 0; i < Hospitals.length(); i++) {
JSONObject c = Hospitals.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Hospitals = new HashMap<String, String>();
Hospitals.put(TAG_NAME, name);
// adding contact to Cities list
hospitallist.add(Hospitals);
}
} 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(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
public class CityNameActivity extends ListActivity {
ListView list;
Map <String, String> cityListWithId = new HashMap<String, String>();
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;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
Map<String, String> tempHashmap = (Map<String, String>) parent.getItemAtPosition(position);
String tagName = tempHashmap.get(TAG_NAME);
System.out.println("tagname" + tagName);
String tagId = (String)cityListWithId.get(tagName);
System.out.println("tagId" + tagId);
Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();
}
});
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);
cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
HashMap<String, String> Cities = new HashMap<String, String>();
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);
}
}
}
On ItemClick() method you can add this to get the id of the product.
HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .
please find below code . i am just refactor few thing so please let me if there some thing wrong
public class CityNameActivity extends ListActivity
{
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 = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetCities().execute();
ListView listView=getListView();
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) {
if(citylist!=null && !citylist.isEmpty())
{
Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
}
}
});
new GetCities().execute();
}
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_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);
}
}
}

How to Show JSON DATA in LISTVIEW

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.

ListView works in emulator, but not in phone

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.

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
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
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} 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(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

How to parse a json rss feed into an android widget

please i need help, am a rookie, how can i create a widget that get its feed from from a Json in android. Is there a helpful tutorial that can help with this or a source code i can look at. I have checked online for a suitable tutorail but i found none that can help directly. this is the json url feed i want to pass into my android widget:url
public class MinistryNews extends SherlockListActivity {
private ActionBarMenu abm;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://";
// JSON Node names
private static final String TAG_QUERY = "query";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
// private static final String TAG_CAT_CODE = "cat_code";
// private static final String TAG_STATUS = "status";
// private static final String TAG_CREATED_TIME = "created_time";
private static final String TAG_UPDATE_TIME = "update_time";
// private static final String TAG_AUTHOR_ID = "author_id";
// contacts JSONArray
JSONArray query = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> queryList;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ministry_news);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
abm = new ActionBarMenu(MinistryNews.this);
if (com.cepfmobileapp.org.service.InternetStatus.getInstance(this)
.isOnline(this)) {
// Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
// Toast.makeText(getBaseContext(),"You are online",Toast.LENGTH_SHORT).show();
// Calling async task to get json
new GetQuery().execute();
} else {
// Toast.makeText(getBaseContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
// Toast t =
// Toast.makeText(this,"You are not online!!!!",8000).show();
// Log.v("Home",
// "############################You are not online!!!!");
AlertDialog NetAlert = new AlertDialog.Builder(MinistryNews.this)
.create();
NetAlert.setMessage("No Internet Connection Found! Please check your connection and try again!");
NetAlert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
// finish();
}
});
NetAlert.show();
}
queryList = 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.title))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.time))
.getText().toString();
String description = ((TextView) view
.findViewById(R.id.content)).getText().toString();
// String plain = Html.fromHtml(description).toString();
// description.replace(/<\/?[^>]+>/gi, '');
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, name);
in.putExtra(TAG_UPDATE_TIME, cost);
in.putExtra(TAG_CONTENT, description);
startActivity(in);
}
});
// Calling async task to get json
// new GetQuery().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetQuery extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MinistryNews.this);
pDialog.setMessage("Please wait..Loading news");
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
query = jsonObj.getJSONArray(TAG_QUERY);
// looping through All Contacts
for (int i = 0; i < query.length(); i++) {
JSONObject c = query.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String update_time = c.getString(TAG_UPDATE_TIME);
// 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_TITLE, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_UPDATE_TIME, update_time);
// contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
queryList.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(MinistryNews.this,
queryList, R.layout.list_item, new String[] { TAG_TITLE,
TAG_UPDATE_TIME, TAG_CONTENT }, new int[] {
R.id.title, R.id.time, R.id.content });
setListAdapter(adapter);
}
}
here is a nice tutorial for you to import json data http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944
if its hard for you still.i can suggest you one thing ,you can import your rss to any website and customize it there as you want it to be and post them as json data it will be easier to do i guess.
its a raugh test for geting json data only the method i think its a bit easier and detail u can return the values instead of showing them in a text from the textvw
public void getdata()
{
String result=null;
InputStream inputstream=null;
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.hadid.aero/news_and_json");
HttpResponse response=httpclient.execute(httppost);
HttpEntity httpentity=response.getEntity();
inputstream= httpentity.getContent();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 1st exception");
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!= null)
{
sb.append(line +"\n");
}
inputstream.close();
result=sb.toString();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 2nd exception");
}
try{
String s="test :";
JSONArray jarray=new JSONArray(result);
for(int i=0; i<jarray.length();i++)
{
JSONObject json=jarray.getJSONObject(i);
s= s +"+json.getString("lastname")+"\n"+
"newsid&title : "+json.getString("id_news")+" "+json.getString("title")+"\n"+
"date :"+json.getString("date")+"\n"+
"description : "+json.getString("description");
}
resultview.setText(s);
}
catch(Exception ex)
{
this.resultview.setText(ex.getMessage()+"at 3rd exception");
}
Check out GSON library which will create Java object with JSON content and use this in Your widget

Categories

Resources