How to get and display thumbnail images from JSON webservice using Hashmap? - android

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();
}
}
}

Related

org.json.JSONException: Value [....] of type org.json.JSONArray cannot be converted to JSONObject

Got stuck to this error..:(
Here is my code..
json exception cannot be converted to jsonobject..
this is my Furniture.java file. this is the main file that is executed first
i want to show the layout as listview which shows logo, furniture name and its price.
public class Furniture extends Activity
{
TextView login;
ListView list;
Button b,search;
String s,s1="error";
int value;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.furniture);
String strUrl = "http://realroom.byethost24.com/realroom/furniture.php"
Log.d("c1 :", s1);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
list = (ListView) findViewById(R.id.flist);
}
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowup = getMenuInflater();
blowup.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generated method stub
Intent i;
switch(item.getItemId())
{
case R.id.checkout:
i = new Intent(Furniture.this, Payment.class);
startActivity(i);
break;
case R.id.aboutUs:
i = new Intent(Furniture.this,AboutUs.class);
startActivity(i);
break;
case R.id.profile:
i = new Intent(Furniture.this,Profile.class);
startActivity(i);
break;
case R.id.help:
i = new Intent(Furniture.this,Help.class);
startActivity(i);
break;
}
return false;
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream istream = null;
try
{
Log.d("c2",s1);
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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.e("c3",s1);
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]);
Log.d("c26",s1);
System.out.print(data);
}
catch(Exception e)
{
Log.d("Background Task",e.toString());
Log.e("c6",s1);
}
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
{
Log.d("c4",s1);
jObject = new JSONObject(strJson[0]);
Log.d("c44",s1);
FurnitureJsonParser furnitureJsonParser = new FurnitureJsonParser();
Log.d("c84",s1);
furnitureJsonParser.parse(jObject);
Log.d("c94",s1);
}
catch(Exception e)
{
Log.d("JSON Exception1",e.toString());
Log.e("c5",s1);
}
// Instantiating json parser class
FurnitureJsonParser furnitureJsonParser = new FurnitureJsonParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> furnitures = null;
try
{
// Getting the parsed data as a List construct
furnitures = furnitureJsonParser.parse(jObject);
}
catch(Exception e)
{
Log.d("Exception",e.toString());
Log.e("c7",s1);
}
// Keys used in Hashmap
String[] from = { "furniture","flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.tv_fur,R.id.iv_icon,R.id.tv_fur_details};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), furnitures, R.layout.f_item, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
list.setAdapter(adapter);
Log.d("c8",s);
for(int i=0;i<adapter.getCount();i++)
{
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
Log.d("c9",s1);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
Log.d("c10",s1);
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
Log.d("c11",s1);
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();
Log.d("c12",s1);
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".jpeg");
Log.d("c13",s1);
// 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.JPEG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}
catch (Exception e)
{
e.printStackTrace();
Log.e("c14",s1);
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result)
{
Log.d("c15",s1);
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) list.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
FurnitureJsonParser.java file
this file is used to parse the data via JSON
class FurnitureJsonParser
{
String s="error";
public List<HashMap<String,Object>> parse(JSONObject jObject)
{
JSONArray jFurnitures = null;
try
{
jFurnitures = jObject.getJSONArray("furnitures");
}
catch(JSONException e)
{
e.printStackTrace();
}
return getFurnitures(jFurnitures);
}
private List<HashMap<String, Object>> getFurnitures(JSONArray jFurnitures)
{
int furnitureCount = jFurnitures.length();
List<HashMap<String, Object>> furnitureList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> furniture = null;
for(int i=0; i<furnitureCount;i++)
{
try
{
furniture = getFurniture((JSONObject)jFurnitures.get(i));
furnitureList.add(furniture);
Log.d("c18",s);
}
catch (JSONException e)
{
e.printStackTrace();
Log.e("c19",s);
}
}
return furnitureList;
}
private HashMap<String, Object> getFurniture(JSONObject jFurniture)
{
HashMap<String, Object> furniture = new HashMap<String, Object>();
String furnitureName = "";
String flag="";
String language = "";
try
{
furnitureName = jFurniture.getString("furniture_name");
flag = jFurniture.getString("furniture_image");
language = jFurniture.getString("furniture_cost");
String details = "Language : " + language + "\n"
furniture.put("furniture", furnitureName);
furniture.put("flag", R.drawable.blank);
furniture.put("flag_path", flag);
furniture.put("details", details);
Log.d("c20",s);
} catch (JSONException e)
{
e.printStackTrace();
Log.e("c21",s);
}
return furniture;
}
}
furniture.php file
the php file that fetch the info from the database and send to android
<?php
include('config.php');
date_default_timezone_set("Asia/Calcutta");
$result1 = mysqli_query($con,"SELECT furniture_name, furniture_image, furniture_cost FROM tbl_furniture");
while($row=mysqli_fetch_array($result1))
{
//$row['store_name'];
//echo"<br>";
$back_android[]=$row;
}
print(json_encode($back_android));
?>
furniture.xml file
the layout of the furniture file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
tools:context=".MainActivity"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/search"
android:layout_gravity="center"
android:text="Search for Furniture"
android:textSize="10dp"
android:textColor="#AAAAAA"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sf"
android:layout_gravity="center"
android:text="Select Furniture"
android:textSize="20dp"
android:textColor="#FFFFFF"
/>
<ListView
android:id="#+id/flist"
android:layout_width="fill_parent"
android:layout_height="402dp"
android:layout_marginTop="10dp"
android:layout_weight="0.18" >
</ListView>
</LinearLayout>
</ScrollView>
f_item.xml file
Layout of the listview in the furniture.xml file
<?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" >
<TextView
android:id="#+id/tv_fur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_fur"
android:layout_centerVertical="true"
android:padding="5dp"
android:contentDescription="#string/str_iv_flag" />
<TextView
android:id="#+id/tv_fur_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iv_icon"
android:layout_below="#id/tv_fur" />
</RelativeLayout>
The following code will return a list of furnitures based on this JSON
private List<Furniture> getThemFurnitures(String json){
List<Furniture> furnitures = new ArrayList<Furniture>();
try {
JSONObject jsonRoot = new JSONObject(json);
JSONArray jsonArray = jsonRoot.getJSONArray("furnitures");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject furnitureObject = jsonArray.getJSONObject(i);
String storeID = furnitureObject.getString("store_id");
String name = furnitureObject.getString("furniture_name");
String cost = furnitureObject.getString("furniture_cost");
String image = furnitureObject.getString("furniture_image");
furnitures.add(new Furniture(storeID, name, cost, image));
}
} catch (JSONException e) {
e.printStackTrace();
}
return furnitures;
}

OnItemClickListner is not working in json parser android

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

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

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

i want grid view with loading by scroll i have image fetch from sever but i want only 10 images view other can load when scrolling grid view

public class NewMovie extends Activity {
GridView lv;
Vibrator vibrator;
SimpleAdapter adapter;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("Category", MainActivity.movie_Category);
setContentView(R.layout.new_movie);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=new";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download processt
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(NewMovie.this, MovieDescription.class));
}
});
}
/** 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]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
adapter = new SimpleAdapter(getBaseContext(), countries,
R.layout.grid_view_content, from, to);
return adapter;
// lv.setAdapter(new ListAdapter(getApplicationContext()));
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
// }
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask
extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its
// position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path
// and position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
// lv.invalidateViews();
adapter.notifyDataSetChanged();
}
}
}
---------*********************-------------------------------------------
PLZ help i found this ans from loag time i want loading more image from server when scrolling like facebook app style. above my code plz help me.
Benji helped me here.
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new LoadGigsTask().execute(currentPage + 1);
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
Check this out

Gridview showing white screen while loading images from sd card

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.

Categories

Resources