Here is ,my code for selecting images and texts from mysql database through php.And it is displaying in a linearlayout in a scrollview.All i want to do is change my layout to listview like this example.
I tried listview and other many ways but its not working properly.I'm new in android,so im trying for a long time.Please help me by editing my code for my requirement.Please.
JAVA
#SuppressLint("NewApi")
public class News_and_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_and_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.activity_news_and_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
// Toast.makeText(getActivity(),image, Toast.LENGTH_LONG).show();
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
// img.buildDrawingCache();
// final Bitmap bmap = img.getDrawingCache();
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
XML
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"[![enter image description here][1]][1]
(source: codelearn.org)
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
>
<LinearLayout
android:id="#+id/newslayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffff"
>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
You cannot call display() from within AsyncTask to display results in listview.
You should follow the following steps
Inside on create, Call AsyncTask to fetch the data from server and populate this into an Array List. While async task is running, make sure you display a progress dialogue so that user cannot do anything in the UI thread.
Inside on create, do initialize your listview.
inside on Post execute of AsyncTask, after you have populated all the elements in the arraylist, call the adapter to populate the listview.
Define an adapter which extends BaseAdapter using which you can populate the listview from the array list.
You may want to check out this link for a similar working example.
Related
I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
I got image path from json webservice in log. I used hashmap for displaying images in listview using json. But can't display any images in listview. Below is my source code.
public class New_PDF_List extends Activity {
ListView mListView;
// Default url
private static String strUrl = "http://thetilesofindia.com/webservice.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove Titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove Notificationbar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.pdf_list);
// 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.listView1);
}
/** 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]);
TileJSONParser tilesjsonparser = new TileJSONParser();
tilesjsonparser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
TileJSONParser tilesjsonparser = new TileJSONParser();
// 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 = tilesjsonparser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "name","imagepath"};
// Ids of views in listview_layout
int[] to = { R.id.mtextview_title,R.id.mImageview_pdf};
// 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.list_item, from, to);
return adapter;
}
private void loadNetworkThumNail(final Context context,
ImageView imageview, String Url) {
// TODO Auto-generated method stub
Picasso.with(context).load(Url.trim()).resize(98, 98).placeholder(R.drawable.ic_launcher).into(imageview);
}
/** 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("image_flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("image_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;
String imgUrl = (String) hm[0].get("image_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() + "/the_tiles_of_india_"+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("imagepath",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("imagepath");
// 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
#SuppressWarnings("unchecked")
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("imagepath",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
Below is layout file which have Listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/tiles_logo" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_marginBottom="16dp"
android:layout_marginLeft="87dp"
android:layout_toRightOf="#+id/imageView1"
android:background="#drawable/info_btn" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="21dp"
android:layout_toRightOf="#+id/button1"
android:background="#drawable/delete_btn" />
<Button
android:id="#+id/button3"
android:layout_width="55dp"
android:layout_height="43dp"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignParentRight="true"
android:background="#drawable/refresh_btn" />
<Button
android:id="#+id/mPdf_list_btn_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/imageView1"
android:layout_below="#+id/button3"
android:background="#drawable/more_button" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/mPdf_list_btn_more" >
</ListView>
</RelativeLayout>
Below is another layout file which is used in simpleAdapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/mImageview_pdf"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/mtextview_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/mImageview_pdf"
android:layout_marginBottom="14dp"
android:layout_marginLeft="57dp"
android:layout_toRightOf="#+id/mImageview_pdf"
android:textColor="#ea0b1e"
android:text="TextView" />
<TextView
android:id="#+id/mtextview_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mtextview_title"
android:layout_below="#+id/mtextview_title"
android:text="Free" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mtextview_type"
android:layout_below="#+id/mtextview_type"
android:layout_marginTop="21dp"
android:background="#drawable/btn_download" />
</RelativeLayout>
After doing lots of R&D i got my answer for my question.
public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private ProgressDialog mProgressDialog;
Button mButtonHelp,mButtonDelete,mButtonRefresh;
ArrayList<HashMap<String, Object>> MyArrList;
public static final String TAG_DOCUMENT = "docs";
public static final String TAG_TITLE = "name";
public static final String TAG_PDF_PATH = "path";
public static final String TAG_IMAGEPATH = "imagepath";
JSONArray document = null;
ListView lstView1;
// Default url
private static String url = "your url";
Button mPdf_list_btn_more;
ProgressDialog pDialog;
// flag for Internet connection status
Boolean isInternetPresent = false;
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove Titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove Notificationbar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.pdf_list);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lstView1 = (ListView)findViewById(R.id.listView1);
mPdf_list_btn_more = (Button)findViewById(R.id.mPdf_list_btn_more);
mPdf_list_btn_more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(PDF_List_New.this,Info_Screen.class);
startActivity(i);
}
});
mButtonHelp = (Button)findViewById(R.id.mButtonHelp);
mButtonHelp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Help", 2).show();
}
});
mButtonDelete = (Button)findViewById(R.id.mButtonDelete);
mButtonDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Delete", 2).show();
}
});
mButtonRefresh = (Button)findViewById(R.id.mButtonRefresh);
mButtonRefresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DownloadJSONFileAsync().execute();
}
});
// Download JSON File
new DownloadJSONFileAsync().execute();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_JSON_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Please Wait.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
// Show All Content
public void ShowAllContent()
{
// listView1
lstView1 = (ListView)findViewById(R.id.listView1);
lstView1.setAdapter(new ImageAdapter(PDF_List_New.this, MyArrList));
}
// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
ImageAdapter imgadapter=new ImageAdapter(PDF_List_New.this, MyArrList);
imgadapter.notifyDataSetChanged();
lstView1.invalidate();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
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);
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
// Getting JSON Array node
document = jsonObj.getJSONArray(TAG_DOCUMENT);
// looping through All Contacts
for (int i = 0; i < document.length(); i++) {
JSONObject c = document.getJSONObject(i);
String name = c.getString(TAG_TITLE);
String image_path = c.getString(TAG_IMAGEPATH);
String pdf_path = c.getString(TAG_PDF_PATH);
Log.i("Name:--->", name);
Log.i("Image_Path--->",image_path);
Log.i("PDF Download Path", pdf_path);
// tmp hashmap for single contact
map = new HashMap<String, Object>();
map.put("name", (String)c.getString("name"));
map.put("imagepath", (Bitmap)loadBitmap(c.getString("imagepath")));
MyArrList.add(map);
}
}
catch(JSONException e){
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
public class ImageAdapter extends BaseAdapter {
private Context context;
TextView txtPicName;
private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList)
{
// TODO Auto-generated method stub
context = c;
MyArr = myArrList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
}
// ColImage
ImageView imageView = (ImageView) convertView.findViewById(R.id.mImageview_pdf);
try
{
imageView.setImageBitmap((Bitmap)MyArr.get(position).get("imagepath"));
} catch (Exception e) {
// When Error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
// ColImgName
txtPicName = (TextView) convertView.findViewById(R.id.mtextview_title);
txtPicName.setText(MyArr.get(position).get("name").toString());
Button button1 = (Button) convertView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Clicked", 2).show();
// downloadPdfContent("http://thetilesofindia.com/magazines/SPECIAL INTERNATIONAL ISSUE - APR-MAY 2013.pdf");
}
});
return convertView;
}
public void downloadPdfContent(String urlToDownload){
try {
String fileName="xyz";
String fileExtension=".pdf";
// download pdf file.
URL url = new URL(urlToDownload);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Making Image auto slider, i have written code to parse JSON but still using drawable images
Actually i am concern, How to use online images in slideshow instead of drawables
Please clear to me because if same kind of problem occurs in future so i will be able to make changes.
check my code below:
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
public int currentimageindex = 0;
ImageView slidingimage;
// using drawable images
// in place of these static images, how can i use my arraylist
// along with DownloadImageTask class, i have written posted below
private int[] IMAGE_IDS = {
R.drawable.splash0,
R.drawable.splash1,
R.drawable.splash2,
R.drawable.splash3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
// execute AsyncTask
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// handler to set duration and to upate animation
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 0000;
int period = 4000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
// AsyncTask to get data from server
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setImage(object.getString("image"));
Log.d("image: ", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
// method to show slide show
private void AnimateandSlideShow() {
slidingimage = (ImageView)findViewById(R.id.ImageView3_Left);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
}
// method to dowload online images
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/ImageView3_Left"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
Logcat:
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/jolie.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/tom.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/will.jpg
Here is my code. I use View Flipper
public class MainActivity extends Activity {
ArrayList<String> actorsList;
ViewFlipper viewFlipper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
actorsList = new ArrayList<String>();
// execute AsyncTask
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// handler to set duration and to upate animation
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 500;
int period = 4000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
// AsyncTask to get data from server
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Actors actor = new Actors();
actorsList.add(object.getString("image"));
// actor.setImage(object.getString("image"));
Log.d("image: ", object.getString("image"));
// actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
setFlipperImage( actorsList);
}
}
}
private void setFlipperImage(ArrayList<String> actorsList) {
for(int i=0;i<actorsList.size();i++){
Log.i("Set Filpper Called", actorsList.get(i).toString()+"");
ImageView image = new ImageView(getApplicationContext());
// image.setBackgroundResource(res);
Picasso.with(MainActivity.this)
.load(actorsList.get(i).toString())
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.into(image);
viewFlipper.addView(image);
}
}
// method to show slide show
private void AnimateandSlideShow() {
viewFlipper.showNext();
}}
And i use Picasso to load the images....
Everything was fine until I used doInBackground(Object... arg0) inorder to show ProgressDialog until it is loaded then dismisses it on onPostExecute(Object result) method. No error message in a LogCat, just crashes. Please help?
Vacancy.java
package com.apps.vacancy;
//all the necessary imports are imported
public class Vacancy extends Activity {
public static String urlPageNumHolder;
public ProgressDialog dialog;
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchJob();
}
});
}
public void searchJob() {
new LoadContentFromServer().execute();
dialog = ProgressDialog.show(this, "Vacancy", "Loading...", true, false);
}
public String getJSONUrl(String url, List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... arg0) {
String url = "http://10.0.2.2/android/smartaddis/mobile/vacancy/getVacancy.php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", inputText.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url, params));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("title_en", c.getString("title_en"));
map.put("description_en", c.getString("description_en"));
map.put("posteddate", c.getString("posteddate"));
map.put("expiredate", c.getString("expiredate"));
MyArrList.add(map);
}
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView,
int position, long mylng) {
urlPageNumHolder = MyArrList.get(position).get("id").toString();
Intent subActivity = new Intent(Vacancy.this,
VacancyWebber.class);
Bundle translateBundle = ActivityOptions
.makeCustomAnimation(Vacancy.this,
R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
startActivity(subActivity, translateBundle);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return MyArrList;
}
#Override
protected void onPostExecute (ArrayList<HashMap<String, String>> result) {
if (dialog != null)
dialog.dismiss();
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
}
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
You are updating ui from doInbackground which you should not do. Return the result in doInbackground and update ui in onPostExecute.
In doInbackground return MyArrList. The result of background computation is a passed to onPostExecute.
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... params) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
... // rest of the code
return MyArrList;
}
In onPostExecute initialize adapter and set the adapter to listview.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// dimiss dialog
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
... // rest of the code
}
For more info
http://developer.android.com/reference/android/os/AsyncTask.html
You also need to move the below inside onCreate after setContentView coz findViewById looks for a view in the current inflated layout.
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);
I am making an app that loads images via internet to a ListView. It is built on sdk 15 with an minimum of 8. Everything works fine if i run it on an emulator with version 8, but if i run it on anything with an sdk of 11 and up the app fails to set the images in the ListView and it then only displays an empty list. Logcat doesn't give anything on this.
I haven't had any succes finding an article addressing this issue, but i think it most be something with the HTTP that is suppose to get the images from the internet, but i don't understand why they don't work on the newer versions of android.
My code looks like this.
EDIT UPDATED CODE:
public class MainActivity extends Activity {
static ArrayList<Tumblr> tumblrs;
ListView listView;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
View v;
String responseBody;
HttpResponse r;
HttpEntity e;
String searchUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
setContentView(R.layout.main);
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout,
null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
new GetChicks().execute();
footer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
} else {
setContentView(R.layout.nonet);
}
}
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
public UserItemAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId, tumblrs);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(GetImage_usingURl(urls[position]));
}
}
return v;
}
}
String[] urls = new String[] { "url1", "url2", "url2" };
public Bitmap GetImage_usingURl(String BitmapUrl) {
try {
Log.d("Image Download State", " Open Stream For : " + BitmapUrl);
InputStream in = new java.net.URL(BitmapUrl).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", "" + e.getMessage());
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
return tumblrs;
}
private class GetChicks extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("More chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
// increment current page
offset += 2;
// Next page request
tumblrs.clear();
String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset="
+ offset;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.aboutUs:
Intent i = new Intent("com.example.example.ABOUT");
startActivity(i);
break;
case R.id.refresh:
Intent f = new Intent(MainActivity.this, MainActivity.class);
startActivity(f);
finish();
break;
case R.id.exit:
finish();
break;
}
return false;
}
}
LOG
10-09 13:21:57.923: D/Image Download State(888): Open Stream For : url1
10-09 13:21:57.923: E/Error(888): Protocol not found: url1
10-09 13:21:58.013: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.033: E/Error(888): Protocol not found: url2
10-09 13:21:58.113: D/Image Download State(888): Open Stream For : url1
10-09 13:21:58.123: E/Error(888): Protocol not found: url1
10-09 13:21:58.153: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.153: E/Error(888): Protocol not found: url2
For Images From internet Try this Could Help you:
if you want to download when you create adapter .
String[] urls=new String[]{"url1","url2","url2"}
public Bitmap GetImage_usingURl(String url){
try {
Log.d("Image Download State", " Open Stream For : "
+ url);
InputStream in = new java.net.URL(url).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
return null;
e.printStackTrace();
}
}
And When You Create Adapet Just Use :
image.setImageBitmap(GetImage_usingURl(urls[position]);
Important Thing For Your Project You Have To Get Policy When You using HTTP its Only For API 9 or higher so i check VERSION.SDK_INT First .
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if you don't set StrictMode you program maybe crash.
Set This Code Before Everything .
Your Errors Its :
In getView You Try To Check img!=null but you forget its create now and its already null
so compiler never get in and set your images , This is first thing .