showing images in android grid - android

I am new to android so please be patient with me , I am creating this code to draw a gridview of images , and I am using asynctask , however my problem is the asynctask is running so binding the image becomes late and the image isnt shown , when i debug it's shown because i delay it so i know the problem but i hope someone fixes the syntax for me , thanks alot .
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImagesAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
ImageView currentImageView;
Bitmap bmImg;
// Constructor
public ImagesAdapter(Context c) {
super();
mContext = c;
GridViewConfig.addImageUrls();
}
#Override
public int getCount() {
return GridViewConfig.getResim_list().size();
}
#Override
public Object getItem(int position) {
return GridViewConfig.getResim_list().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
downloadFile(GridViewConfig.getResim_list().get(position));
imageView.setImageBitmap(bmImg);
// imageView.setImageDrawable(LoadImageFromURL(GridViewConfig
// .getResim_list().get(position)));
return imageView;
}
void downloadFile(String fileUrl) {
AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
#Override
protected String doInBackground(String... params) {
URL myFileUrl = null;
try {
myFileUrl = new URL(params[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String unused) {
/* if (currentImageView == null) {
currentImageView = new ImageView(mContext);
}
currentImageView.setImageBitmap(bmImg); */
}
};
task.execute(fileUrl);
}
gridviewconfig class returns the needed images.

Take a look at http://developer.android.com/training/displaying-bitmaps/index.html There is a BitmapFun sample project/app with the grid and many useful stuff. I recommend you not to reinvent the wheel but to use google's code who are the creators of Android
also I suggest you to study some LazyList implementation

Related

MainActvity not getting updated when App is first launched

I am developing a MovieApp which loads movie posters in MainActivity Fragment using AsyncTask background thread. I am using gridview and BaseAdapter to display images. Following is the code.
MainActivityFragment.java :
package com.android.example.cinemaapp.app;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class MainActivityFragment extends Fragment{
MoviePosterAdapter moviePosterAdapter;
GridView posterGridView;
public HashMap<String, JSONObject> movieMap;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart(){
super.onStart();
updateMovies();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.moviefragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovies();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_popular));
new FetchMoviePosterTask().execute(sortBy);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
posterGridView.setAdapter(moviePosterAdapter);
posterGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// logic to start detail activity
startActivity(intent);
}
});
return rootView;
}
public class FetchMoviePosterTask extends AsyncTask<String, String, Void> implements Serializable {
#Override
protected Void doInBackground(String... params) {
Log.v("FetchMoviePosterTask", "In background method");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr;
try {
//logic to create uri builder
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
// Log.v("MainActivityFragment", "Movie json "+movieJsonStr);
try {
String[] posterPaths = getPosterPaths(movieJsonStr);
for(String path : posterPaths){
publishProgress(path);
}
}catch(JSONException je){
Log.e("MoviePosterPath","Error while parsing JSON");
}
} catch (IOException e) {
Log.e("MoviePosterAdapter", "Error ", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MoviePosterAdapter", "Error closing stream", e);
}
}
}
return null;
}
public String[] getPosterPaths(String movieJsonStr) throws JSONException{
final String POSTER_PATH = //some value
final String POSTER_SIZE = //some value
JSONObject jsonObject = new JSONObject(movieJsonStr);
JSONArray results = jsonObject.getJSONArray("results");
String[] posterStrs = new String[results.length()];
movieMap = new HashMap<String, JSONObject>();
for(int i =0; i < results.length(); i++){
JSONObject movieObj = (JSONObject) results.get(i);
posterStrs[i] = POSTER_PATH + POSTER_SIZE + movieObj.getString("poster_path");
movieMap.put(posterStrs[i], movieObj);
}
return posterStrs;
}
#Override
protected void onProgressUpdate(String... posterValues){
Log.v("FetchMoviePosterTask", "In onProgress method");
moviePosterAdapter.add(posterValues[0]);
super.onProgressUpdate(posterValues);
}
#Override
protected void onPostExecute(Void result) {
Log.v("FetchMoviePosterTask", "In onPostExecute method");
moviePosterAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
MoviePosterAdapter.java :
package com.android.example.cinemaapp.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MoviePosterAdapter extends BaseAdapter {
ArrayList<String> movieArray = new ArrayList<String>();
private Context mContext;
public MoviePosterAdapter(Context c) {
mContext = c;
}
void add(String path){
movieArray.add(path);
}
void clear(){
movieArray.clear();
}
void remove(int index){
movieArray.remove(index);
}
#Override
public int getCount() {
return movieArray.size();
}
#Override
public Object getItem(int position) {
return movieArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(movieArray.get(position)).into(imageView);
return imageView;
}
}
Problem : When the application is first launched, UI is not getting populated with imageviews. In Logcat I could see control is flowing through doBackground(), onProgressUpdate() and onPostExecute().
When I click 'Refresh' button or If i navigate to some other activity or app and return to Movie app UI (onResume()) it is working perfectly fine. Images are displayed.
Many thanks in advance!
You should change updateMovies(); from onStart() to onCreateView. As Gabe Sechan said, you're wrong about the lifecycle. Try to do some research on the Fragment lifecycle.
Just you need to call method updateMovies(); from onCreateView() after posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
remove call from start();

After getting ListView updated or refrshed,button click not working

I am using 47deg/android-swipelistview library and i am facing some problem. I have listview containing buttons in each list item. but when I swipe one of the list item to dismiss it. It dismisses successfully but after that all my button in other list items stops working, Please Help me. I am using custom list adapter and view holder pattern.
Thank You.
Here is my code
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
public class FeedListAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private List<Word> feedItems;
Animation animFadeOut;
public static int postid=0;
Context context;
DatabaseHandler db;
AnimationDrawable drawable;
TextToSpeech ttobj;
public LruBitmapCache cache;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public static String URL_FEED = "http://hashmedia.in/vocabmeme/webservices/vote";
static WordHolder holder = null;
static class WordHolder{
TextView post_word,comment_count,post_id ;
ImageView post_image1;
NetworkImageView post_image;
ImageButton voice,openword;
}
public FeedListAdapter(Activity activity, List<Word> feedItems,Context context)
{
this.activity = activity;
this.feedItems = feedItems;
this.context=context;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
db = new DatabaseHandler(activity.getApplicationContext());
final View parentView=convertView;
holder = null;
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if(convertView == null)
{
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new WordHolder();
convertView = inflater.inflate(R.layout.feed_item,parent,false);
holder.post_word = (TextView) convertView.findViewById(R.id.post_word);
holder.voice = (ImageButton) convertView.findViewById(R.id.voice);
holder.openword=(ImageButton) convertView.findViewById(R.id.openword);
holder.comment_count=(TextView) convertView.findViewById(R.id.comment_count);
holder.post_id=(TextView) convertView.findViewById(R.id.post_id);
holder.post_image1 = (ImageView) convertView.findViewById(R.id.post_image1);
holder.post_image = (NetworkImageView) convertView.findViewById(R.id.post_image);
holder.post_image1.setTag(holder);
holder.post_image.setTag(holder);
holder.openword.setTag(holder);
holder.voice.setTag(holder);
convertView.setTag(holder);
}
else
{
holder = (WordHolder)convertView.getTag();
holder.post_image1.setTag(holder);
holder.post_image.setTag(holder);
holder.openword.setTag(holder);
holder.voice.setTag(holder);
System.out.println("Holder"+ convertView.getTag());
}
final Word item = feedItems.get(position);
holder.voice.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(final View v)
{
animFadeOut = AnimationUtils.loadAnimation(activity.getApplicationContext(),R.anim.splash);
animFadeOut.setAnimationListener(new AnimationListener()
{
#Override
public void onAnimationStart(Animation animation)
{
Drawable replacer = activity.getResources().getDrawable(R.drawable.ic_action_volume_off);
((ImageButton) v).setImageDrawable(replacer);
}
#Override
public void onAnimationEnd(Animation animation)
{
Drawable replacer = activity.getResources().getDrawable(R.drawable.ic_action_volume_on);
((ImageButton) v).setImageDrawable(replacer);
}
#Override
public void onAnimationRepeat(Animation animation)
{
}
});
holder = (WordHolder) v.getTag();
holder.voice.startAnimation(animFadeOut);
View test=(View) v.getParent().getParent();
// String textview2 = ((TextView) row.findViewById(R.id.post_word)).getText().toString();
AudioManager am = (AudioManager)activity.getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = am.getStreamMaxVolume(am.STREAM_MUSIC);
am.setStreamVolume(am.STREAM_MUSIC, amStreamMusicMaxVol, 0);
ttobj.speak(holder.post_word.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
ttobj=new TextToSpeech(activity.getApplicationContext(),new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
ttobj.setLanguage(Locale.ENGLISH);
}
}
});
holder.openword.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(final View v)
{
holder = (WordHolder) v.getTag();
Intent i = new Intent(activity, WordActivity.class);
i.putExtra("post_id",Integer.parseInt(holder.post_id.getText().toString()));
i.putExtra("post_image",item.getImage());
i.putExtra("post_word",item.getWord());
i.putExtra("post_comment", holder.comment_count.getText().toString());
context.startActivity(i);
}
});
holder.post_image.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(final View v)
{
holder = (WordHolder) v.getTag();
Intent i = new Intent(activity, WordActivity.class);
i.putExtra("post_id",Integer.parseInt(holder.post_id.getText().toString()));
i.putExtra("post_image",item.getImage());
i.putExtra("post_word",item.getWord());
i.putExtra("post_comment", holder.comment_count.getText().toString());
context.startActivity(i);
}
});
holder.post_image1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(final View v)
{
holder = (WordHolder) v.getTag();
Intent i = new Intent(activity, WordActivity.class);
i.putExtra("post_id",Integer.parseInt(holder.post_id.getText().toString()));
i.putExtra("post_image",item.getImage());
i.putExtra("post_word",item.getWord());
i.putExtra("post_comment", holder.comment_count.getText().toString());
context.startActivity(i);
}
});
holder.post_word.setText(item.getWord());
holder.post_id.setText(Integer.toString(item.getID()));
holder.comment_count.setText(Integer.toString(item.getCommentCount()));
final String imagefilename=item.getImage();
Bitmap myBitmap;
File imgFile = getOutputMediaFile(imagefilename);
cache = AppController.getInstance().getLruBitmapCache();
if(!imagefilename.substring(imagefilename.length()-4).equals(".gif"))
{
try
{
myBitmap=cache.get(item.getImage());
if(myBitmap!=null)
{
holder.post_image1.setImageBitmap(myBitmap);
holder.post_image1.setVisibility(View.VISIBLE);
holder.post_image.setVisibility(View.GONE);
}
else
{
if(imgFile.exists())
{
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
cache.put(item.getImage(), myBitmap);
holder.post_image1.setImageBitmap(myBitmap);
holder.post_image1.setVisibility(View.VISIBLE);
holder.post_image.setVisibility(View.GONE);
}
else
{
holder.post_image1.setVisibility(View.GONE);
holder.post_image.setVisibility(View.VISIBLE);
holder.post_image.setImageUrl("http://hashmedia.in/vocabmeme/images/words/"+item.getImage(), imageLoader);
}
}
}
catch(NullPointerException e)
{
e.printStackTrace();
}
}
else
{
holder.post_image.setVisibility(View.GONE);
holder.post_image1.setVisibility(View.GONE);
try
{
final String _url="http://hashmedia.in/vocabmeme/images/words/"+imagefilename;
if(imgFile.exists())
{
drawable = new GifAnimationDrawable(imgFile, false);
holder.post_image1.setImageDrawable(drawable);
holder.post_image1.setVisibility(View.VISIBLE);
}
else
{
new AsyncTask<Void, Void, Void>()
{
File pictureFile;
#Override
protected Void doInBackground(Void... params)
{
int count;
try
{
pictureFile = getOutputMediaFile(imagefilename);
URL url = new URL(_url);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
OutputStream output = new FileOutputStream(pictureFile);
byte data[] = new byte[1024];
long total_c = 0;
while ((count = input.read(data)) != -1)
{
total_c += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e)
{
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void file_url)
{
try
{
drawable = new GifAnimationDrawable(pictureFile, false);
} catch (IOException e)
{
e.printStackTrace();
}
holder.post_image1.setVisibility(View.VISIBLE);
}
}.execute();
}
}catch (Exception e)
{
e.printStackTrace();
}
}
return convertView;
}
private File getOutputMediaFile(String name)
{
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ "vocab.meme1"
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists())
{
if (! mediaStorageDir.mkdirs())
{
return null;
}
}
// Create a media file name
File mediaFile;
String mImageName=name;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
}

Listview not displaying the right image in android

In my app I have a listview. Each listview item contains an image view and several textviews. To display the image I use Drawable. But the images are displayed in the wrong row when scrolling. The image in a row changes several times until the right image appears. I have searched the web but I found nothing working for me. I am posting my code below. Please help me! Thanks in advance!
MainActivity.java
package com.makemyandroidapp.example.stacksites;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String posID = mAdapter.getItem(pos).getID();
Intent i = new Intent(getApplicationContext(), PositionDesc.class);
i.putExtra("posID", posID);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://duapune.com/mobile/listaeplote.php", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplication(), TabActivity.class);
finish();
startActivity(objIntent);
}
}
SitesAdapter.java
package com.makemyandroidapp.example.stacksites;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
/*
* Custom Adapter class that is responsible for holding the list of sites after they
* get parsed out of XML and building row views to display them on the screen.
*/
public class SitesAdapter extends ArrayAdapter<StackSite> {
//ImageLoader imageLoader;
//DisplayImageOptions options;
Context c;
String url1;
String url2;
Drawable backgr;
ImageView iconImg;
int posi;
RelativeLayout row;
public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
super(ctx, textViewResourceId, sites);
c=ctx;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
posi=pos;
row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
//final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
kompaniaTxt.setText(getItem(pos).getKompania());
pozicioniTxt.setText(getItem(pos).getPozicioni());
kategoriaTxt.setText(getItem(pos).getKategoria());
qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return row;
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try { iconImg = (ImageView)row.findViewById(R.id.iconImg);
backgr=drawable_from_url(url1,"kot");
//backgr=drawable_from_url("https://duapune.com/photos/duapune#duapune.com1349707357.png","kot");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
iconImg.setBackground(backgr);
}
Drawable drawable_from_url(String url, String src_name) throws
java.net.MalformedURLException, java.io.IOException
{System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
return Drawable.createFromStream(((java.io.InputStream)
new java.net.URL(url.trim()).getContent()), src_name);
}
}
}
Try this..
You have to use ViewHolder for that issue
private class ViewHolder {
ImageView iconImg;
TextView kompaniaTxt,pozicioniTxt,kategoriaTxt,qytetiTxt;
}
EDIT
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.row_site, parent, false);
holder = new ViewHolder();
holder.iconImg = (ImageView) view.findViewById(R.id.iconImg);
holder.kompaniaTxt = (TextView) view.findViewById(R.id.nameTxt);
holder.pozicioniTxt = (TextView) view.findViewById(R.id.aboutTxt);
//holder.kategoriaTxt = (TextView) view.findViewById(R.id.kategoriaTxt);
holder.qytetiTxt = (TextView) view.findViewById(R.id.qytetiTxt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=holder.kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
holder.kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
holder.kompaniaTxt.setText(getItem(pos).getKompania());
holder.pozicioniTxt.setText(getItem(pos).getPozicioni());
holder.kategoriaTxt.setText(getItem(pos).getKategoria());
holder.qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return view;
}
and onPostExecute
#Override
protected void onPostExecute(Void result){
holder.iconImg.setBackground(backgr);
}
EDIT
Instead of using SitesDownloadTask AsyncTask use Universal Image Loader lib
https://github.com/nostra13/Android-Universal-Image-Loader
lazy image loader
https://github.com/thest1/LazyList

How to solve empty costume list view issue?

I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}
You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line

Not adding new list of images by using EndlessAdapter

I am using EndlessAdapter to display a list of images, but the new list not adding after the scrolling.
My code is like this:
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.sample.endlessdemo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class EndlessAdapterDemo extends ListActivity {
String name[];
String urls[];
int j,limit;
//ListView listValues;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
RestClient post=new RestClient("http://iconnect.myappdemo.com/listusers.php");
try {
post.ExecutePost();
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String response=post.getResponse();
Log.e("Respopnse :",response);
JSONArray json = null;
try {
json = new JSONArray(response);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
name=new String[json.length()];
for(int i=0;i<json.length();i++)
try {
name[i]=json.getJSONObject(i).getString("picture").toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urls=new String[10];
for (int i=0;i<10;i++) { urls[i]=name[i]; }
setListAdapter(new DemoAdapter(urls));
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
DemoAdapter(String list[]) {
super(new StartingView(EndlessAdapterDemo.this,R.layout.row,list));
rotate=new RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);
rotate.setDuration(1000);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
Log.e("Demo Adapter","getPendingView");
View row=getLayoutInflater().inflate(R.layout.listrow,null);
View child=row.findViewById(android.R.id.list);
//View child=row.findViewById(R.id.image);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
SystemClock.sleep(10000); // pretend to do work
Log.e("Demo Adapter","In cacheInBackground");
return(getWrappedAdapter().getCount()<20);
}
#Override
protected void appendCachedData()
{
// if (getWrappedAdapter().getCount()<75) {
// Log.e("Demo Adapter","In appendCachedData");
// #SuppressWarnings("unchecked")
// ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
// for (int i=0;i<5;i++) { a.add(name[a.getCount()]); }
// }
#SuppressWarnings("unchecked")
ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
for(int i=0;i<5;i++){
Log.e("a.getCount()+i value :",String.valueOf(a.getCount()+i));
a.getView(a.getCount()+i,null,null);
}
}
}
class StartingView extends ArrayAdapter<String>{
String startUrls[];
public StartingView(Context context, int ResourceId,String[] objects) {
super(context, ResourceId, objects);
startUrls=new String[objects.length];
startUrls=objects;
// TODO Auto-generated constructor stub
}
public View getView(int pos,View counterview,ViewGroup parent){
View row=getLayoutInflater().inflate(R.layout.row,null);
ImageView image=(ImageView)row.findViewById(R.id.image);
Log.e("position :",String.valueOf(pos));
image.setImageBitmap(convertImage(name[pos]));
return row;
}
}
public Bitmap convertImage(String imgstr){
URL aURL = null;
try {
final String imageUrl =imgstr.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
is.close();
return bm;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
I hope the following code will help you.
PS: The original source code and question can be found here.
public class Test extends ListActivity
implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v,
int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
} }
Add this after finish loading:
StartingView.notifyDataSetChanged()

Categories

Resources