Android: How do I parse an HTML page? - android

I new to android programming. I would like to know how to parse a webpage and extract specific content into a ListView. What is the easiest and best way to do it? Can someone show me an example using what's given below?
URL = "Something.com".
I want to extract the names of the cities and href link for each one.
ann arbor
battle creek
central michigan
detroit metro
flint
grand rapids
Thank you guys and sorry for asking this basic question.

look the code below and let me know if you have any doubts and see this link it may help you
http://wptrafficanalyzer.in/blog/android-lazy-loading-images-and-text-in-listview-from-http-json-data/
public class MainActivity extends Activity {
ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "ur url/countries";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "country"
// Ids of views in listview_layout
int[] to = { R.id.tv_country};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
}
}
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Use something like http://jsoup.org/ to get the html content.
Then use something like
http://jsoup.org/cookbook/extracting-data/selector-syntax
extract the urls.
then
:matches(regex): find elements whose text matches the specified regular expression; e.g. div:matches((?i)login)
do a regular expression for the url you are looking for.
I'm not sure if this is what you want.

I remember I did this once and luckily I found that code.
You would just have to give a call to this Intentservice from your activity
and you would need to specify the website name at the top ( in url variable )
public class parser extends IntentService {
public String url="http://www.mywebsite.com";
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// shutdown();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
private Timer t = new Timer();
byte[] buffer;
public timeCell() {
super("name");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
t.schedule(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
BufferedReader reader=null;
try {
reader = new BufferedReader(
new InputStreamReader(
new URL(url).openStream()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("line was ", line); // printing is done here ;)
}
}

Related

OnItemClickListner is not working in json parser android

I am using listview in android with JSON Parser the listview sucessful working, here is my problem, onitemclicklistner is not working in listview?
Here this my code
Main Activity code
public class MainActivity extends Activity {
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://192.168.0.200/android/count.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.iv_flag,R.id.tv_country_details};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String im,gUrl;
gUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(gUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Activity view = null;
// TODO Auto-generated method stub
// getting values from selected ListItem
String type = ((TextView) view.findViewById(R.id.tv_country_details)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(type, type);
startActivity(in);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
SingleMenuItemActivity code
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_details = "details";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String cost = in.getStringExtra(TAG_details);
// Displaying all values on the screen
TextView lblCost = (TextView) findViewById(R.id.tv_country_details);
lblCost.setText(cost);
}
}
Json Parser Code
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("countries");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String flag="";
String currencyName = "";
try {
flag = jCountry.getString("flag");
currencyName = jCountry.getJSONObject("currency").getString("currencyname");
String details = currencyName ;
country.put("flag", R.drawable.blank);
country.put("flag_path", flag);
country.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
public static Object optJSONObject(int arg2) {
// TODO Auto-generated method stub
return null;
}
public static boolean isNull(int arg2) {
// TODO Auto-generated method stub
return false;
}
}
Add these code into your dewnloadurl method.
String jsonString = null;
HttpURLConnection linkConnection = null;
try{
URL linkur1 = new URL(url);
linkConnection = (HttpURLConnection) linkur1.openConnection();
int responseCode = linkConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream linkingStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkingStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(linkConnection != null){
linkConnection.disconnect();
}
}
return jsonString;
Than Use it to get single item
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
View item = arg0.getChildAt(position);
}

JSON listview OnItemClickListener url (webview)

I got all the data ... But I am not able to use webview url(UrlWeb) , i mean when i click on list item then it will open in web view. when i click any list it should pass corresponding url to the WebView activity.So how to achieve this, how to store corresponding url?? please someone help me..
My MainActivity :
public class MainActivity extends Activity {
ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://www.mulnivasisangh.com/aman/listweb.json";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "country","flag","details", "URL"};
// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details,R.id.tv_URL};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
String URL = ((TextView) view.findViewById(R.id.tv_URL)).getText().toString();//this will take the value of the invincible textView
Intent i = new Intent(MainActivity.this, WebViewActivity.class);
i.putExtra("URL", URL);
startActivity(i);
}
});
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My CountryJSONParser :
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("webs");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag="";
String language = "";
String capital = "";
String web ="";
try {
countryName = jCountry.getString("Nom");
flag = jCountry.getString("UrlImatge");
language = jCountry.getString("Descripcio");
capital = jCountry.getString("Id");
web = jCountry.getString("UrlWeb");
String details = "Descripcio : " + language + "\n" +
"Id : " + capital + "\n" + "URL: " + web + "\n";
country.put("country", countryName);
country.put("UrlImatge", R.drawable.blank);
country.put("flag_path", flag);
country.put("details", details);
country.put("URL", web);
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
Thanks in advance..
I use this trick when I want to pass data from listview to another activity.
1- I add a textView to my item-list.xml which is R.layout.lv_layout in your case and make its visibility gone. android:visibility="gone"
2- add the URL String to this textView, it wont be shown in the listview, because it has no visibility.
String[] from = { "country","flag","details", "URL"};
// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details, R.id.tv_country_URL};//the forth one is the textView you set it as gone.
3- in OnItemClick function just add the following:
String URL = ((TextView) view.findViewById(R.id.tv_country_URL)).getText().toString();//this will take the value of the invincible textView
Intent i = new Intent(MainActivity.this, WebView.class);
i.putExtra("URL", URL);
startActivity(i);
4- use getIntent in your webView Activity to get the URL and load it.
if it is still vague please inform me. hope you got the idea.
Edit
you dont need getURL function anymore, I thought getCountries doesnt return a hashMap for URL.
so all you have to do is create a invisible textView in your lv_layout and put each URL in it.
follow the 4 steps above.
for step 3 in Post:
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
String URL = ((TextView) view.findViewById(R.id.tv_URL)).getText().toString();//this will take the value of the invincible textView
Intent i = new Intent(MainActivity.this, WebView.class);
i.putExtra("URL", URL);
startActivity(i);
}
Edit
for webViewActivity you need to get extra from the previous activity as the following:
public class WebViewActivity extends Activity{
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
String url = getIntent().getExtras().getString("URL")
if (null != url) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

i am using gridview in which i am parsing data from json in android,but some time my application runs and some time gives rejected execution eception

public class TopMovie extends Activity
{
GridView lv;
Vibrator vibrator;
private Object params;
public static String movie_Id;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("Category", MainActivity.movie_Category);
setContentView(R.layout.new_movie);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=other";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(TopMovie.this, MovieDescription.class));
}
});
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
countries, R.layout.grid_view_content, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
adapter.notifyDataSetChanged();
}
}
}
My application is debugging but not running.RejectedExecutionException: Task android.os.AsyncTas rejected from java.util.concurrent.
Submitting tasks to a thread-pool gives RejectedExecutionException
how to resolve threadpool exception in gridview android
You can change the executor the asynctask uses if you extend the asynctask class.
Check this example from docs where they download multiple images and use a custom asynctask to control the concurrency.
I had the same problem you are having and used that project to fix it.

how can i resolve my rejected execution execption in android gridview?

public class TopMovie extends Activity
{
GridView lv;
Vibrator vibrator;
Dialog dialog;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.i("Category", MainActivity.movie_Category);`enter code here`
setContentView(R.layout.new_movie);
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminateVisibility(false);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=other";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(TopMovie.this, MovieDescription.class));
}
});
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
// linlaHeaderProgress.setVisibility(View.VISIBLE);
//super.onPreExecute();
dialog=dialog=ProgressDialog.show(TopMovie.this,"", "Loading...", true);
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
countries, R.layout.grid_view_content, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
// Setting adapter for the listview
if(dialog!=null)
dialog.dismiss();
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
adapter.notifyDataSetChanged();
}
}
}}
i have a gridview in which items coming from json..,sometime my applications runs but sometime gives REJECTED EXECUTION EXECPTION at " imageLoaderTask.execute(hm);",i am unable to understand how to resolve this problem.i have tried all examples and condiotions.i have used asynchtask ,custom adapetr in my code ,but no solution and answer is ocured in my code.,how can i resolve my error.please help me...:(
First you have to understand what RejectedExecutionException means. Then decide how do you want to handle it.
AsyncTask runs its tasks in an Executor. This executor uses a queue where the tasks are stored until the executor is free to pay attention to them. The default executor with a default task can handle 10 tasks at the same time and store 10 additional tasks to perform once the running ones complete. Once the spot for all these 20 tasks (10+10) it can't take any more tasks, and it lets you know by raising a RejectedExecutionException.
How can you deal with this? Depends on what you need. You can catch that exception and try again later to see if the queue has room later, or you could use a differently configured executor that (a) can perform more tasks at the same time or (b) that has a queue with more space for tasks. Some already existing executor classes can be configured with parameters more appropriate for your needs (see the documentation for Executor) or you can write your own. One such executor is ThreadPoolExecutor that you can tell what kind of queue to use (this is the executor that is used in some of the Android versions, you don't specify which version you're working with). In the documentation there's discussion about what kinds of queues there are.
Again, the decision on how to configure the executor and queue is up to you and your needs. Such as if you want to allow for unbounded creation of threads, or have a limit. Want to have a long queue of tasks or short, or even unbound.
Try this..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
imageLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, hm);
else
imageLoaderTask.execute(hm);
For all AsyncTask

Android: Json parse in listview

Im trying to parse some items in a listview and when I scroll down I want to get more products and add them to the list.
But my code doesnt do that it either refreshes it or crashes.
Any help?
Also adding a footer doesnt work either i get an classcastexception
JSONParser:
package com.lars.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lars.R.drawable;
import android.R;
import android.util.Log;
/** A class to parse json data */
public class JSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jProducts = null;
try {
// Retrieves all the elements in the 'countries' array
jProducts = jObject.getJSONArray("products");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getProducts(jProducts);
}
private List<HashMap<String, Object>> getProducts(JSONArray jProducts){
int productsCount = jProducts.length();
List<HashMap<String, Object>> productList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> product = null;
// Taking each country, parses and adds to list object
for(int i=0; i<productsCount;i++){
try {
// Call getCountry with country JSON object to parse the country
product = getJSON((JSONObject)jProducts.get(i));
productList.add(product);
} catch (JSONException e) {
e.printStackTrace();
}
}
return productList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getJSON(JSONObject f){
HashMap<String, Object> country = new HashMap<String, Object>();
String id = "";
String naam = "";
String status = "";
String prijs = "";
String productnum = "";
try {
String priceone = f.getString("prijsex");
id = f.getString("id");
naam = f.getString("naam");
status = f.getString("status");
prijs = "€" + priceone;
productnum = f.getString("productnum");
country.put("id", id);
country.put("naam", naam);
country.put("img", com.lars.R.drawable.tlogotrans);
country.put("prijs", prijs);
country.put("img_path", "http://www.lars.com/images/" + productnum + ".jpg");
if(Integer.parseInt(status) > 0){
country.put("status", com.lars.R.drawable.stock);
}else{
country.put("status", com.lars.R.drawable.nostock);
}
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
Download tasks and Listview loaders:
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
Log.i("Result", result);
if(result.equals(" ")){
Log.i("No img", "No Img");
}else{
listViewLoaderTask.execute(result);
}
// Start parsing xml data
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
private List<HashMap<String, Object>> products;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
JSONParser jsonpars = new JSONParser();
jsonpars.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
JSONParser jsonpars = new JSONParser();
// A list object to store the parsed countries list
try{
// Getting the parsed data as a List construct
if(set == 0){
products = jsonpars.parse(jObject);
}else{
products.addAll(jsonpars.parse(jObject));
}
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "img","naam","status","prijs"};
// Ids of views in listview_layout
int[] to = { R.id.imPThumb,R.id.tvPRName,R.id.imstock,R.id.tvPRPrijs};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), products, R.layout.productlijstrow, from, to);
return adapter;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
publishProgress();
Log.i("ListView Loader Task", "Update");
super.onProgressUpdate(values);
}
/** Invoked by the Android on "doInBackground" is executed */
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// View v = getLayoutInflater().inflate(R.layout.footerview, null);
//list.addFooterView(v);
// Setting adapter for the listview
list.setAdapter(adapter);
if(set == 0){
list.setOnScrollListener(onAnswersScrolled);
set++;
}
list.setOnItemClickListener(onAnswerClicked);
list.setTextFilterEnabled(true);
/* list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Bundle extra = new Bundle();
Intent i = new Intent("com.lars.productdescription");
extra.putString("id", o.get("id"));
i.putExtras(extra);
startActivity(i);
}
});*/
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("img_path");
Log.i("imgurlonPost", imgUrl);
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hmDownload.put("img_path",imgUrl);
hmDownload.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hmDownload);
adapter.notifyDataSetChanged();
}
/* list.setOnScrollListener(new OnScrollListener(){
});*/
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("img_path");
int position = (Integer) hm[0].get("position");
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.i("imgUrl", imgUrl);
// Connecting to url
urlConnection.connect();
// Log.i("Response", urlConnection.getResponseMessage());
// Reading data from url
if(urlConnection.getResponseMessage().contains("OK")){
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
cacheDirectory.delete();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
// Storing the path to the temporary image file
hmBitmap.put("img",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}else{
Log.i("nope", "nb");
String uriStr = "android.resource://" + "com.lars" + "/" + R.drawable.ic_launcher;
hmBitmap.put("img", uriStr);
hmBitmap.put("position",position);
return hmBitmap;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("img");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
adapter = (SimpleAdapter ) list.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("img",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
publishProgress();
adapter.notifyDataSetChanged();
Log.i("Image Task", "Update");
super.onProgressUpdate(values);
}
}
private OnItemClickListener onAnswerClicked = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) parent.getItemAtPosition(position);
Bundle extra = new Bundle();
Intent i = new Intent("com.lars.productdescription");
extra.putString("id", o.get("id"));
i.putExtras(extra);
startActivity(i);
}
};
private OnScrollListener onAnswersScrolled = new OnScrollListener() {
public void onScroll(AbsListView view, int first, int visibleitems, int totalitemcount) {
// TODO Auto-generated method stub
int lastInScreen = first + visibleitems;
if(lastInScreen == totalitemcount){
if(kf == 0){
Log.i("onScroll", "" + c);
Log.i("kf", "0");
String filfinal = keuze.replace(" ", "thisisaspace");
String strUrl = "http://www.lars.nl/getName.php?name=" + filfinal + "&page=" + c ;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
c = c + o;
Log.i("After Scroll", "" + c);
}else{
Log.i("onScroll", "" + c);
Log.i("kf", "1");
String strUrl = "http://www.lars.nl/get.php?id=" + filter + "&page=" + c ;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
c = c + o;
Log.i("After Scroll", "" + c);
}
}
}
public void onScrollStateChanged(AbsListView view, int scrollstate) {
// TODO Auto-generated method stub
}
};
}
I'd like to introduce you to CWAC-ENDLESS by non other than the brilliant mark murphy (commonsware). Not only is it a fine example of the power of putting an adapter inside another adapter, it handles all the background tasks for you as well as scrolling so that your data list may be added to very easily by following the demo
I sincerely hope this helps you as much as its helped me.

Categories

Resources