I have a gridview when this activity is loading it showing a white screen I checked a lot I don't know why it happening I am showing a gridview of image and those images are from sd card .
My oncreate code follows
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String pdfPath = Environment.getExternalStorageDirectory().toString() + "/ICA Faculty/";
Toast.makeText(getApplicationContext(),pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText(), Toast.LENGTH_SHORT).show();
try {
File file = new File(pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText());
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Sorry no PDF reader found.", Toast.LENGTH_SHORT).show();
}
}
});
File folder = new File(Environment.getExternalStorageDirectory() + "/ICA Faculty");
db.open();
c = db.getAllRecords();
//If data exist in local database AND "ICA Faculty" folder exist
//Getting the sd card file name from local database
if (c.moveToFirst() && folder.exists() && folder.listFiles() != null)
{
//This array list will help to create image
imgUrl = new ArrayList<String>();
pdfUrl = new ArrayList<String>();
do
{
imgUrl.add(c.getString(3));
pdfUrl.add(c.getString(2));
} while (c.moveToNext());
ImageAdapter adapter = new ImageAdapter(MainActivity.this);
gridview.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(), "You need to sync to create your library.", Toast.LENGTH_LONG).show();
}
db.close();
}
private class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public ImageAdapter(Context c) {
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return imgUrl.size();
//return c.getCount();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
boolean result = ( position == 0 ) ? c.moveToFirst() : c.moveToNext();
if (result)
{
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grid_row_view, null);
holder = new ViewHolder();
holder.ImgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
holder.Viewcover = (ImageView) convertView.findViewById(R.id.cover);
holder.PdfUrl = (TextView) convertView.findViewById(R.id.hiddenPdfUrl);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String imagePath = Environment.getExternalStorageDirectory().toString() + "/ICA Faculty/";
holder.ImgThumb.setImageDrawable(Drawable.createFromPath(imagePath + imgUrl.get(position)));
holder.Viewcover.setImageResource(R.drawable.book_cover);
holder.PdfUrl.setText(pdfUrl.get(position));
}
return convertView;
}
private class ViewHolder {
ImageView ImgThumb;
ImageView Viewcover;
TextView PdfUrl;
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//=======================================================================================================================================
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
String [] stringArrayPdfUrlForLocalDB;
String [] stringArrayBookId;
//-------------------------------------------------------------------------------------------
//Method for Sync
//-------------------------------------------------------------------------------------------
public void libSyc(View v)
{
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
db.deleteAllRecord();
}
else{}
new MyAsyncTask().execute("aa","dd");
}
//-------------------------------------------------------------------------------------------
//END Method for Sync
//-------------------------------------------------------------------------------------------
// Show Dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Making your library. \nPlease wait ...");
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
//Background Async Task to download file
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
for(int i=0 ; i < f_url.length ; i++){
try {
URL url = new URL(f_url[i]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String fpath = getFileName(f_url[i]);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/"+fpath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
//save File Name, Image Name, Book ID to laocal DataBase
try {
if(stringArrayPdfUrlForLocalDB.length>0)
{
for(int i=0 ; i < stringArrayPdfUrlForLocalDB.length ; i++)
{
//----------------------------------------------------------------
//Getting value from string array
//----------------------------------------------------------------
String fileName = getOnlyFileName(stringArrayPdfUrlForLocalDB[i]);
String imageName = getImageName(stringArrayPdfUrlForLocalDB[i]);
String BookId = stringArrayBookId[i];
//Toast.makeText(getApplicationContext(), "File Name: "+fileName+"\nBookId: "+BookId, Toast.LENGTH_LONG).show();
//----------------------------------------------------------------
//Inserting each File Name, Image Name, Book ID to laocal DataBase
//----------------------------------------------------------------
db.open();
long id = db.insertRecord(BookId, fileName + ".pdf", imageName);
db.close();
}
}
else
{
Toast.makeText(getApplicationContext(), "Not getting any book form server.", Toast.LENGTH_SHORT).show();
}
//populate grid view
// ImageAdapter adapter = new ImageAdapter(MainActivity.this);
// gridview.setAdapter(adapter);
// adapter.notifyDataSetChanged();
//Reloading activity
Intent intent = getIntent();
finish();
startActivity(intent);
} catch (Throwable e) {
Toast.makeText(getApplicationContext(), ""+e, Toast.LENGTH_SHORT).show();
}
}
public String getFileName(String wholePath)
{
String name=null;
int start,end;
start=wholePath.lastIndexOf('/');
end=wholePath.length(); //lastIndexOf('.');
name=wholePath.substring((start+1),end);
//Creating a folder named ICA Faculty
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"ICA Faculty");
directory.mkdirs();
name = "ICA Faculty/"+name;
System.out.println("Start:"+start+"\t\tEnd:"+end+"\t\tName:"+name);
return name;
}
public String getOnlyFileName(String wholePath)
{
String name=null;
int start,end;
start=wholePath.lastIndexOf('/');
end=wholePath.lastIndexOf('.');
name=wholePath.substring((start+1),end);
return name;
}
public String getImageName(String wholePath)
{
String name=null;
int start,end;
start=wholePath.lastIndexOf('/');
end=wholePath.length(); //lastIndexOf('.');
name=wholePath.substring((start+1),end);
//Creating a folder named ICA Faculty
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"ICA Faculty");
directory.mkdirs();
return name;
}
}
//===================================================================================================================================
//sending EmailAddress and Password to server
//===================================================================================================================================
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
String responseBody = null;
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(Double result){
//Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_SHORT).show();
if(responseBody!=null)
{
processResponce(responseBody);
}
else
{
Toast.makeText(getApplicationContext(), "Empty Responce.", Toast.LENGTH_LONG).show();
}
}
protected void onProgressUpdate(Integer... progress){
}
public void postData(String emailId,String passwrd) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new
HttpPost httppost = new HttpPost("http://bumba27.byethost16.com/Ica%20Test/book_lib.xml");
try {
// Data that I am sending
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("EmailId", emailId));
nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
Log.d("result", responseBody);
}
catch (Throwable t ) {
//Toast.makeText( getApplicationContext(),""+t,Toast.LENGTH_LONG).show();
Log.d("Error Time of Login",t+"");
}
}
}
//===================================================================================================================================
//END sending EmailAddress and Password to server
//===================================================================================================================================
//===================================================================================================================================
//processing the XML got from server
//===================================================================================================================================
private void processResponce(String responceFromServer)
{
try {
//saving the file as a xml
FileOutputStream fOut = openFileOutput("loginData.xml",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(responceFromServer);
osw.flush();
osw.close();
//reading the file as xml
FileInputStream fIn = openFileInput("loginData.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[responceFromServer.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
//getting the xml Value as per child node form the saved xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(readString.getBytes("UTF-8"));
Document doc = db.parse(is);
NodeList root=doc.getElementsByTagName("root");
String loginStatus = null;
for (int i=0;i<root.getLength();i++)
{
loginStatus = "" + ((Element)root.item(i)).getAttribute("status");
}
//If Email and Pass match with server
if(loginStatus.equalsIgnoreCase("T"))
{
NodeList book=doc.getElementsByTagName("book");
List<String> url = new ArrayList<String>();
List<String> fileName = new ArrayList<String>();
List<String> bkId = new ArrayList<String>();
for (int i=0;i<book.getLength();i++)
{
url.add(((Element)book.item(i)).getAttribute("bookImageUrl"));
url.add(((Element)book.item(i)).getAttribute("pdfUrl"));
//------------------------------------------------------------------------------------------------------------
//Creating two list and storing image url, Book Id
//Logic
//This 2 list will be accessed and file name, pdf name, book id will be extracted from this 2 value and saved to local DB
//------------------------------------------------------------------------------------------------------------
fileName.add(((Element)book.item(i)).getAttribute("bookImageUrl"));
bkId.add(((Element)book.item(i)).getAttribute("bookId"));
}
String [] stringArray = url.toArray(new String[url.size()]);
//Array list is converted to String array
stringArrayBookId = bkId.toArray(new String[bkId.size()]);
stringArrayPdfUrlForLocalDB = fileName.toArray(new String[fileName.size()]);
// Toast.makeText( getApplicationContext(),"List Value:\n"+stringArrayPdfUrlForLocalDB.length,Toast.LENGTH_LONG).show();
new DownloadFileFromURL().execute(stringArray);
}
else if(loginStatus.equalsIgnoreCase("F"))
{
Toast.makeText( getApplicationContext(),"No Match found for this user",Toast.LENGTH_SHORT).show();
}
}
catch (Throwable t)
{
Toast.makeText( getApplicationContext(),""+t,Toast.LENGTH_SHORT).show();
Log.d("Error On Saving and reading", t+"");
}
}
Main Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="38sp"
android:columnWidth="80dp"
android:gravity="center"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
android:listSelector="#00000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40sp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/background_title"
android:orientation="vertical" >
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/lib_logo1"
android:layout_width="40sp"
android:layout_height="wrap_content"
android:layout_marginLeft="4sp"
android:src="#drawable/book" />
<ImageView
android:id="#+id/lib_logo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/lib_logo1"
android:src="#drawable/lib_icon" />
<ImageView
android:id="#+id/sync_img"
android:layout_width="50sp"
android:layout_height="50sp"
android:src="#drawable/sync"
android:layout_alignParentRight="true"
android:onClick="libSyc"/>
</RelativeLayout>
</LinearLayout>
I guess the problem with ImageAdapter
public Object getItem(int position) {
return null;
}
You need to return corresponding object for a given position. Return approximate object. Then your GridView contains all objects are null, so thats why your getting empty (white screen).
You are trying to load the images directly in adapter using UI thread,try using Lazyloading concept in android that loads images in seperate thread,this will fix the issue.
Related
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.
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();
}
}
}
I have listview at which I am trying to implement an async task that loads the image into the view inside the getView method of my adapter. I have succeeded in creating this however my problem is that since in the listview and the adapter the view gets recycled, there is a short period of time when the user scrolls the listview that the imageView located in the layout shows the image of the view at a previous position. It then shows the correct image. I have tried setting the imageView bitmap to null inside the getView method before the async task is called but it still behaves the same. How do I load an image into a view using an async task without having the previous image shown before the image is finished loading?
hey follow few step to download image from server and show in your list view
Step 1. make this class in your project
OnImageDownloaded.java
public class OnImageDownloaded {
public OnImageDownloaded() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "your_Dir_name");
if (file.mkdirs()) {
}
} else {
Log.e("testing", "External Directory is not mounted");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void downloadTheImages(ArrayList<String> imageUrls) {
try {
new downloadingTheImages(imageUrls).execute();
} catch (Exception e) {
e.printStackTrace();
}
}
class downloadingTheImages extends AsyncTask<Void, Void, Void> {
ArrayList<String> imageUrls;
public downloadingTheImages(ArrayList<String> imageUrls) {
this.imageUrls = imageUrls;
}
#Override
protected Void doInBackground(Void... params) {
try {
for (int i = 0; i < imageUrls.size(); i++) {
if (imageUrls.get(i).equals("0")) {
} else
downloadTheImageIfRequired(imageUrls.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public void downloadTheImageIfRequired(String imageName) {
try {
String dirPath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator
+ "your_Dir_name"
+ File.separator;
String CompleteFilePath = dirPath + imageName;
File f = new File(CompleteFilePath);
if (f.exists()) {
} else {
URL url = new URL(
"http image URL ::"
+ imageName);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(CompleteFilePath);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 2.
Check out how you get that image
private class getImage extends AsyncTask<Void, Void, String> {
Dialog dialog;
String url;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
url = getResources().getString(R.string.baseurl) + "getNews";
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
try {
JSONObject jobject = new JSONObject(json);
Log.e("testing", "url: " + url + " " + json);
int success = jobject.getInt("success");
Log.e("testing", "json length" + jobject.length());
for (int i = 0; i < jobject.length() - 1; i++) {
JSONObject jobj = jobject
.getJSONObject(Integer.toString(i));
if (success == 1) {
HashMap<String, String> hm = new HashMap<String, String>();
ArrayList<String> tempAl1 = new ArrayList<String>();
tempAl1.add(jobj.getString("image"));
if (tempAl1.size() > 0) {
new OnImageDownloaded().downloadTheImages(tempAl1);
}
Log.e("test", "image" + jobj.getString("image"));
hm.put(image, jobj.getString("image"));
aldata.add(hm);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
if (dialog.isShowing())
dialog.dismiss();
Custom_Adapter adapter = new Custom_Adapter (
(Activity) context, aldata);
lv.setAdapter(adapter);
}
}
Step 3.
Show that image in your adapter like this
call these methods in your getview in adaper
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = null;
if (view == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.news_view, null);
final ViewHolder viewHolder = new ViewHolder();
initAll(view, viewHolder);
view.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) view.getTag();
fillAll(holder, position);
return view;
}
public void fillAll(final ViewHolder holder, final int position) {
String dirPath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator
+ "your_Dir_name"
+ File.separator;
String CompleteFilePath = dirPath + allData.get(position).get("image");
File f = new File(CompleteFilePath);
if (f.exists()) {
Log.e("testingTag", "if part");
holder.ivimage.setVisibility(View.VISIBLE);
catchOutOfMemory(holder.ivimage, CompleteFilePath);
} else {
Log.e("testingTag", "else part");
holder.ivimage.setVisibility(View.GONE);
}
Log.e("test", "image" + allData.get(position).get("image"));
}
void catchOutOfMemory(ImageView iv, String path) {
try {
iv.setImageURI(Uri.parse(path));
} catch (OutOfMemoryError e) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap = BitmapFactory.decodeFile(path, options);
iv.setImageBitmap(preview_bitmap);
}
}
thats all thanks
I had the same problem, then I started using Square's Picasso , it's very simple and handles imageview recycling perfectly!
In your adapter, you need to use a ViewHolder (to recycle views effectively) and set a tag (on the view) to bind the view to the correct image. You already know the position in the getView(...) callback.
I'm having a JSON file which is populated to a listview.
I wanna make the list view dynamic. That means, I only need one Activity for the click action on the list I have. And the source of the content (picture,title,description) which is populated to the Activity comes from a JSON file on the web.
For example, I have 13 projects on the list, whenever I click one of them it goes to ONE activity containing different picture,title,and description depends on the item I click.
I need somebody to improve the codes I provide below.
Projects.java
public class Projects {
public String title;
public String keyword;
public String description;
public String smallImageUrl;
public String bigImageUrl;
public int cost;
#Override
public String toString()
{
return "Title: "+title+ " Keyword: "+keyword+ " Image: "+smallImageUrl;
}
}
ProjectsAdapter.java
Public class ProjectsAdapter extends ArrayAdapter<Projects> {
int resource;
String response;
Context context;
//Initialize adapter
public ProjectsAdapter(Context context, int resource, List<Projects> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout projectView;
//Get the current alert object
Projects pro = getItem(position);
//Inflate the view
if(convertView==null)
{
projectView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, projectView, true);
}
else
{
projectView = (LinearLayout) convertView;
}
TextView Title =(TextView)projectView.findViewById(R.id.title);
try {
ImageView i = (ImageView)projectView.findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(pro.smallImageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Assign the appropriate data from our alert object above
//Image.setImageDrawable(pro.smallImageUrl);
Title.setText(pro.title);
return projectView;
}
}
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
//ListView that will hold our items references back to main.xml
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
ProjectsAdapter arrayAdapter;
//List that will host our items and allow us to modify that array adapter
ArrayList<Projects> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
//Initialize our ArrayList
prjcts = new ArrayList<Projects>();
//Initialize our array adapter notice how it references the listitems.xml layout
arrayAdapter = new ProjectsAdapter(Main.this, R.layout.listitems,prjcts);
//Set the above adapter as the adapter of choice for our list
lstTest.setAdapter(arrayAdapter);
//Instantiate the Web Service Class with he URL of the web service not that you must pass
WebService webService = new WebService("http://pre.spendino.de/test/android/projects.json");
//Pass the parameters if needed , if not then pass dummy one as follows
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
//Get JSON response from server the "" are where the method name would normally go if needed example
// webService.webGet("getMoreAllerts", params);
String response = webService.webGet("", params);
try
{
//Parse Response into our object
Type collectionType = new TypeToken<ArrayList<Projects>>(){}.getType();
//JSON expects an list so can't use our ArrayList from the lstart
List<Projects> lst= new Gson().fromJson(response, collectionType);
//Now that we have that list lets add it to the ArrayList which will hold our items.
for(Projects l : lst)
{
prjcts.add(l);
}
//Since we've modified the arrayList we now need to notify the adapter that
//its data has changed so that it updates the UI
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
Projects p = (Projects ) lstTest.getItemAtPosition(position);
//Do your logic and open up a new Activity.
Intent care = new Intent(Main.this, Organization.class);
startActivity(care);
}
});
}
}
WebService.java (I don't think we need to edit this one)
public class WebService{
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response1 = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
String webServiceUrl;
//The serviceName should be the name of the Service you are going to be using.
public WebService(String serviceName){
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
webServiceUrl = serviceName;
}
//Use this method to do a HttpPost\WebInvoke on a Web Service
public String webInvoke(String methodName, Map<String, Object> params) {
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, Object> param : params.entrySet()){
try {
jsonObject.put(param.getKey(), param.getValue());
}
catch (JSONException e) {
Log.e("Groshie", "JSONException : "+e);
}
}
return webInvoke(methodName, jsonObject.toString(), "application/json");
}
private String webInvoke(String methodName, String data, String contentType) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(webServiceUrl + methodName);
response1 = null;
StringEntity tmp = null;
//httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Groshie", "HttpUtils : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
Log.d("Groshie", webServiceUrl + "?" + data);
try {
response1 = httpClient.execute(httpPost,localContext);
if (response1 != null) {
ret = EntityUtils.toString(response1.getEntity());
}
} catch (Exception e) {
Log.e("Groshie", "HttpUtils: " + e);
}
return ret;
}
//Use this method to do a HttpGet/WebGet on the web service
public String webGet(String methodName, Map<String, String> params) {
String getUrl = webServiceUrl + methodName;
int i = 0;
for (Map.Entry<String, String> param : params.entrySet())
{
if(i == 0){
getUrl += "?";
}
else{
getUrl += "&";
}
try {
getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
httpGet = new HttpGet(getUrl);
Log.e("WebGetURL: ",getUrl);
try {
response1 = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Groshie:", e.getMessage());
}
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response1.getEntity());
} catch (IOException e) {
Log.e("Groshie:", e.getMessage());
}
return ret;
}
public static JSONObject Object(Object o){
try {
return new JSONObject(new Gson().toJson(o));
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
}
EDIT
What I wanna show in Organization.java is this .xml file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<ImageView
android:id="#+id/project_image"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Default Title"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#78b257"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginTop="15dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/btn_forward"
android:layout_marginLeft="5dp"
android:layout_gravity="left"
android:text="Weitersagen"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="15dp"/>
<Button
android:id="#+id/btn_sms_spend"
android:layout_marginTop="15dp"
android:layout_marginRight="5dp"
android:text="Per SMS spenden"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_white"
android:orientation="vertical">
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:gravity="left"
android:text="default description"
android:textSize="18sp"
android:textColor="#000000"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
and here's the JSON file:
[{
"title": "CARE Deutschland-Luxemburg e.V.",
"keyword": "CARE",
"description": "<p><b>Das CARE-Komplett-Paket für Menschen in Not</b",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1284113658.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1284113658.jpg",
"cost": "5"
},
{
"title": "Brot für die Welt",
"keyword": "BROT",
"description": "<p>„Brot für die Welt“ unterstützt unter der Maßgabe 'Helfen, wo die Not am größten ist' ausgewählte Projekte weltweit.",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1267454286.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1267454286.jpg",
"cost": "5"
},
{
"title": "Deutsche AIDS-Stiftung",
"keyword": "HIV",
"description": "<p>Die Deutsche AIDS-Stiftung unterstützt mit ihren finanziellen Mitteln seit mehr als 20 Jahren Betroffene, die an HIV und AIDS erkrankt sind.",
"smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1258365722.jpg",
"bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1258365722.jpg",
"cost": "5"
}]
Screenshot of the list view:
If these are the steps I gotta do, then I'm having trouble with number 4 & 5:
1. Have the JSON
2. construct a suitable data structure (an Array, ArrayList, whatever you like) to hold crucial data about your list view
3. Use this data structure as the source for your list view
4. when the user clicks on any row, try to find out the position of the row in the list view, and on that position in your source data structure, look for the data needed.
5. create any activity which handles these data generally
6. open that activity with the data of the row which user clicked in step 4
7. Consume this data in your new activity
ConstantData.java:
public class ConstantData extends ArrayList<Projects>{
private static final long serialVersionUID = 9100099012485622682L;
public static Object projectsList;
public ConstantData(){
}
public ConstantData(Parcel in){
}
#SuppressWarnings("unchecked")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator(){
public ConstantData createFromParcel (Parcel in){
return new ConstantData(in);
}
public Object[] newArray(int arg0){
return null;
}
};
private void readFromParcel(Parcel in){
this.clear();
int size = in.readInt();
for (int i = 0; i < size; i++){
Projects p = new Projects();
p.setTitle(in.readString());
p.setKeyword(in.readString());
p.setSmallImageUrl(in.readString());
p.setBigImageUrl(in.readString());
p.setCost(in.readInt());
}
}
public int describeContents() {
return 0;
}
public void writeToParcel (Parcel dest, int flags){
int size = this.size();
dest.writeInt(size);
for (int i = 0; i < size; i++){
Projects p = this.get(i);
dest.writeString(p.getTitle());
dest.writeString(p.getKeyword());
dest.writeString(p.getDescription());
dest.writeString(p.getSmallImageUrl());
dest.writeString(p.getBigImageUrl());
dest.writeInt(p.getCost());
}
}
}
If something is not clear, please let me know.
Thank you very much
For that you need A data structure that holds all your json nodes on index and it should be accessible for all the activities you need [Reco: Use something like GlobalVariables or ConstantData where you have all your project properties and make it public static].
Like : ConstantData.projectData which may be the arraylist or array that contains only Project objects
Now from list view onItemClick method you will get an index (position that denotes on which row its clicked), pass this on your single designed activity with help of bundles and extras.
2.Fetch the index in your desired activity. Fetch the project object on that index from ConstantData.projectData.
Populate the UI components from your project object.
By doing this you can inflate same view again and again only passing the index, only populating the list can be a heavy operation, but the rest will be quicker....
Edit: Let me provide you the snippets .
for 1. on Main.java you use these line in itemClick methods
Intent care = new Intent(Main.this, Organization.class);
startActivity(care);
Add this line between startActivity and Intent initialization.
care.putExtra("yourPackageStructure.Organization.position",position);
for 2. In Organization.java
2.1 create an integer member called mPosition[or the name you like]
2.2 in onCreate() method write mPosition = getIntent().getExtras().getInt("yourPackageStructure.Organization.position");
Project project = ConstantData.projectsData.get(mPosition);
As I don't know how what is there in Organization.java and I wanted to say an array list or something that holds your Projects objects.
Here is what you can have Organization.java 's onCreate method.
onCreate(){
position = getIntent().getExtras().getInt("yourPackageStructure.Organization.position");
//Below line will get you the projects object
Projects project = ConstantData.projectsList.itemAt(position);
ImageView projectImage = (ImageView)findViewById(R.id.project_image);
Bitmap image = getImageFromUrl(this,project.bigImageUrl);
projectImage.setBitmapDrawable(image);
TextView title = (TextView)findViewById(R.id.title);
title.setText(project.title);
TextView description = (TextView)findViewById(R.id.description);
description .setText(project.description);
}
This is what i use for getImageFromUrl method
public static Bitmap getImageFromUrl(Context context, String urlString) {
try {
if (haveInternet(context)) {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
Bitmap bmImg = BitmapFactory.decodeStream(is);
return bmImg;
} else {
return null;
}
} catch (MalformedURLException e) {
Log.e("Problem in image", e.toString(), e);
e.printStackTrace();
} catch (Exception e) {
Log.e("Problem in image", e.toString(), e);
}
return null;
}
This is the haveInternet Method
private static boolean haveInternet(Context context) {
NetworkInfo info = getNetworkInfo(context);
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Hoping it helps you properly...
Added ConstantData
ConstantData.java
public class ConstantData{
//All public static members will be here
public static final long guid = A LONG VAL;
public static String licenceText = A STRING VAL;
//etc... etc... above members are just the idea that what kind of members can be there in //ConstantData... I normally use all public static properties here
//Here is the variable you probably want
public static ArrayList<Projects> projectsList = new ArrayList<Projets>();
}
if you want to populate this array list you can do it from main.java check the lines
for(Projects l : lst)
{
prjcts.add(l);
}
You can add or replace this line. ConstantData.projectsList.add(l); I recommend you to add the line rather to display the line.....