I have implemented the Universal Image Loader into my app with a gridview layout.
When I press a button I want to add a new imageUrl to the Array of Urls.
I managed to do that, but when I refresh my imageList, I still only see the images that were in the Array on StartUp.
How can I update the gridView with the new Array?
EDIT
MainActivity
public class MainActivity extends Activity {
Button btnView;
private ListView listView;
Socket client;
PrintWriter printwriter;
EditText textField;
Button button;
String messsage;
ObjectInputStream input;
ObjectOutputStream output;
int counter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.ac_home);
//startRunning();
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ViewImages.class);
startActivity(intent);
}
public void onTakeImageClick(View view) throws IOException {
ViewImages.addImg();
}
}
And here is the ViewImage class
public class ViewImages extends Activity {
private ListView listView;
ImageLoader loader;
private static ImageListAdapter adapter;
private static List<String> mItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<String>();
mItems.add("http://195.178.234.228/images/image8.jpg");
mItems.add("http://195.178.234.228/images/image7.jpg");
adapter = new ImageListAdapter(this, mItems);
//
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public static void addImg(){
mItems.add("http://195.178.234.228/images/image10.jpg");
adapter.notifyDataSetChanged();
}
}
ImageListAdapter
public class ImageListAdapter extends BaseAdapter {
List<String> list;
int size;
private Context context;
private ImageLoader imageLoader;
public ImageListAdapter(Context context,List<String> list) {
this.context = context;
this.list = list;
imageLoader = ImageLoader.getInstance();
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View v = convertView;
ViewHolder vh = null;
if (v == null) {
v = View.inflate(context, R.layout.list_item, null);
vh = new ViewHolder();
vh.imageView = (ImageView) v.findViewById(R.id.imageView);
v.setTag(vh);
}
else {
vh = (ViewHolder)v.getTag();
}
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imageLoader.displayImage(list.get(position), vh.imageView, options);
return v;
}
private class ViewHolder {
ImageView imageView;
}
}
Use notifyDataSetChanged on gridView Adapter to reflect changes in the gridview. Whenever there is a new imageUrl added to array of URL's refresh the adapter by :
adapter.notifyDataSetChanged();
Related
I really don't know how to do this. I have tried some tutorial but not worked for me ... i've already done the this with many Methods but unable to do this.
Here is my RecyclerView Holder
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView countryName;
public ImageView countryPhoto;
String s;
Bitmap image;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
}
#Override public void onClick(View view) {
Intent imageIntent = new Intent(view.getContext(),GalleryFullImage.class);
imageIntent.putExtra("id",getAdapterPosition());
view.getContext().startActivity(imageIntent);
Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}}
Here is my Recyclerview Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private ArrayList<String> arrayList;
private Context context;
public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
this.arrayList = itemList;
this.context = context;
}
#Override
public long getItemId(int position) {
return position;
}
#Override public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override public void onBindViewHolder(RecyclerViewHolders holder, int position) {
Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
holder.countryPhoto.setImageBitmap(bitmap);
}
#Override public int getItemCount() {
return this.arrayList.size();
}}
Here is my GalleryActivity
public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_gallery);
setTitle("Gallery");
stringList = new ArrayList<>();
// Be sure that this file is exist !!
String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Country";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
try
{
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File file : files) {
stringList.add(file.getAbsolutePath());
}
}catch (Exception e)
{
Log.e("Sort Error", e.getMessage());
}
RecyclerView rView = (RecyclerView)findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
rView.setAdapter(rcAdapter);
}
}
You just have to apply onClickListener in you viewholder, take the clicked adapter position in integer and pass it in next your fullscreen activity
Here is the full code, hope it helps
MainActivity
public class MainActivity extends AppCompatActivity {
private final Integer image_ids[] = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),gridColumnlayout);
recyclerView.setLayoutManager(layoutManager);
ArrayList<CreateList> createLists = prepareData();
MyAdapter adapter = new MyAdapter(getApplicationContext(), createLists);
recyclerView.setAdapter(adapter);
}
private ArrayList<CreateList> prepareData(){
ArrayList<CreateList> theimage = new ArrayList<>();
for(int i = 0; i< 5; i++){
CreateList createList = new CreateList();
createList.setImage_ID(image_ids[i]);
theimage.add(createList);
}
return theimage;
}
}
CreateList Class
public class CreateList {
private Integer image_id;
public Integer getImage_ID() {
return image_id;
}
public void setImage_ID(Integer android_image_url) {
this.image_id = android_image_url;
}
}
MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<CreateList> galleryList;
private Context context;
public final static String EXTRA_MESSAGE = "FullScreen Image";
public MyAdapter(Context context, ArrayList<CreateList> galleryList) {
this.galleryList = galleryList;
this.context = context;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item, parent, false));
}
#Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, int i) {
CreateList currentList = galleryList.get(i);
Glide.with(context).load(currentList.getImage_ID()).centerCrop().crossFade().into(viewHolder.img);
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = viewHolder.getAdapterPosition();
String stringID = Integer.valueOf(pos).toString();
Intent intent = new Intent(MyAdapter.this.context, FullScreen.class);
intent.putExtra(EXTRA_MESSAGE, stringID);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView img;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.image);
}
}
}
FullScreen Activity
public class FullScreen extends AppCompatActivity {
private final Integer image_ids[] = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
Intent intent = getIntent();
String message = intent.getStringExtra(MyAdapter.EXTRA_MESSAGE);
int position = Integer.parseInt(message);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(image_ids[position]);
}
}
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:scaleType="fitXY"
android:id="#+id/image"/>
</RelativeLayout>
Since you are loading the bitmap from file in onBindViewHolder, you can just pass the path instead in onClick and decode it again in your next activity. This may require a bit of work in your case since your ViewHolder is defined separately from your RecyclerView so it does not have access to your dataset. For starters, move your ViewHolder so it can be a static nested class of your RecyclerView. Something like this:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolders>
private ArrayList<String> arrayList;
....
public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
....
#Override
public void onClick(View view) {
Intent intent = new Intent(...);
intent.putExtra("path",arrayList.get(getAdapterPosition());
/* send intent*/
}
}
I have seen a lot of similar questions about this issue but I couldn't find any solution to this:
I have three fragments in a TabLayout handled by a ViewPager and I have a ListView in the third Fragment which is not displaying any items after I change the orientation of the screen. I have tried to set a background color to the convertView in the ArrayAdapter to see if it was displayed and indeed it is not being displayed after I change the orientation. But it's weird because in my First Fragment where I use the same ArrayAdapter for another ListView everything's working and I can't understand why it's not on the third Fragment.
One thing is sure: I have checked with logs almost everywhere that the ArrayList.size() is never zero.
Here's the Third Fragment's relevant code:
public class SavedScanFragment extends Fragment{
private ListView lv;
private Database db;
private ArrayList<Scan> scans;
private ScanAdapter adapter;
public static SavedScanFragment newInstance() {
return new SavedScanFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new Database(getContext());
getScans();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_saved_scan, container, false);
lv = (ListView) result.findViewById(R.id.saved_scan_list);
return result;
}
#Override
public void onResume() {
super.onResume();
db = new Database(getContext());
getScans();
}
public void getScans() {
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
scans = db.getScans();
if(scans!=null)
return true;
else {
scans = new ArrayList<>();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result)
populateList();
}
};
task.execute();
}
public void populateList() {
if(getContext()!=null) {
if (lv.getAdapter() == null) {
adapter = new ScanAdapter(getContext(), R.layout.scan_list_item, scans);
lv.setAdapter(adapter);
} else {
((ScanAdapter) lv.getAdapter()).update(scans);
}
}
}
And the ArrayAdapter's code:
public class ScanAdapter extends ArrayAdapter<Scan> implements ListAdapter {
private Context context;
private int layoutResourceID;
private ArrayList<Scan> results;
public ScanAdapter(Context context, int layoutResourceID, ArrayList<Scan> results) {
super(context, layoutResourceID, results);
this.context = context;
this.layoutResourceID = layoutResourceID;
this.results = results;
}
public void update(ArrayList<Scan> scans) {
results.clear();
results.addAll(scans);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView; //view = row
ViewHolder holder = null;
if(view == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layoutResourceID, parent, false);
view.setBackgroundColor(Color.GREEN);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.scan_name_and_date_text);
holder.ssid = (TextView)view.findViewById(R.id.scan_SSID_text);
holder.frequency = (TextView)view.findViewById(R.id.scan_frequency_text);
holder.level = (TextView)view.findViewById(R.id.scan_level_text);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
Scan sr = results.get(position);
holder.name.setText(sr.getName()+" ( "+sr.getDate()+" )");
holder.ssid.setText(sr.getSsid() + " ( " + sr.getBssid() + " )");
holder.frequency.setText(sr.getFrequency()+" MHz");
holder.level.setText(Integer.toString(sr.getLevel())+ " dBm");
return view;
}
static class ViewHolder {
TextView name,ssid, frequency, level;
}
}
Thanks in advance!
From this post. You can try to use onActivityCreated instead of onCreate. Try this:
public class SavedScanFragment extends Fragment{
//....to restore the saved state
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Restore the fragment state here
db = new Database(getContext());
getScans();
}
//add this to save instant state
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save your important variable here to outstate
}
}
I'am trying to learn how to pass a LinkedList<PassedObject> from MainActivity to SecondActivity.
So I created a listview in each activity to check if the objects are passed. The SecondActivity displays in a textview if the list is empty. I also made a PassedObject class which implements Parcelable. The problem is that when i get the List from Intent it is null. In the code below i changed LinkedList with ArrayList because i thought that's the problem. What i did wrong?
public class MainActivity extends AppCompatActivity {
private ArrayList<PassedObject> mainList;
private ListView listView;
private CustomArrayAdapter adapter;
Button test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mainList == null){
mainList = new ArrayList<PassedObject>();
}
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
listView = (ListView) findViewById(R.id.listViewMain);
adapter = new CustomArrayAdapter(getBaseContext(),R.layout.item_list,mainList);
listView.setAdapter(adapter);
Button test = (Button) findViewById(R.id.button_id);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putParcelableArrayListExtra("list",mainList);
startActivity(intent);
}
});
}
public class CustomArrayAdapter extends android.widget.ArrayAdapter<PassedObject>{
Context _context;
int layoutRestId;
ArrayList<PassedObject> data;
public CustomArrayAdapter(Context context, int resource, ArrayList<PassedObject> objects) {
super(context, resource, objects);
_context = context;
layoutRestId = resource;
data = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutRestId, parent, false);
}
TextView tv = (TextView) convertView.findViewById(R.id.textViewItem);
tv.setText(data.get(position).getName());
return convertView;
}
}
}
public class SecondActivity extends AppCompatActivity {
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv = (TextView) findViewById(R.id.seocndListText);
ArrayList<PassedObject> list =(ArrayList<PassedObject>) getIntent().getParcelableExtra("list");
tv.setText(list.isEmpty()+"");
}
}
public class PassedObject implements Parcelable{
private String _name;
PassedObject(String name){
_name = name;
}
public String getName(){
return _name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_name);
}
public PassedObject(Parcel in){
_name = in.readString();
}
public static final Parcelable.Creator<PassedObject> CREATOR = new Parcelable.Creator<PassedObject>() {
#Override
public PassedObject createFromParcel(Parcel source) {
return new PassedObject(source);
}
#Override
public PassedObject[] newArray(int size) {
return new PassedObject[size];
}
};
}
Change the following line
ArrayList<PassedObject> list =(ArrayList<PassedObject>) getIntent().getParcelableExtra("list");
To be
ArrayList<PassedObject> list = getIntent().getParcelableArrayListExtra("list");
Use this
Bundle bdl = getIntent().getExtras();
mArraylist1 = bdl.getParcelableArrayList("your list name");
i am using eclipse.
Basically what i am trying to implement is that , that i have a gridView which is fetching images from mysql database dynamically using JSON.
Now , instead of gridview i want to show them as coverflow view.
I have searched through the internet , but was not able to find any library or example for dynamic images , i only found for static images stored in the app itself and not on external database.
My code are as follows:-
MainActivity.java:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/photomania";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView gridView;
private CustomListAdapter adapter;
ImageButton blackcapture;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.gallary_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.list);
gridView = mPullRefreshGridView.getRefreshableView();
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.invalidateViews();
mPullRefreshGridView.onRefreshComplete();
}
adapter = new CustomListAdapter(this, movieList);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
Adapter Class:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) convertView.findViewById(R.id.title);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return convertView;
}
Movie.java:-
public class Movie implements Parcelable{
private String title,thumbnailUrl;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(String name, String thumbnailUrl
) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = "http://eventassociate.com/wedding/"+thumbnailUrl;
}
// Parcelling part
public Movie(Parcel in){
String[] data = new String[2];
in.readStringArray(data);
this.title = data[0];
this.thumbnailUrl = data[1];
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.title,
this.thumbnailUrl,
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
I successfully implemented this as GridView , but i am facing trouble in implementing this as coverflow design or something like that.
I searched on the net and i find this code , but only for static images:-
public class SimpleExample extends Activity {
// =============================================================================
// Child views
// =============================================================================
private FancyCoverFlow fancyCoverFlow;
// =============================================================================
// Supertype overrides
// =============================================================================
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.fancyCoverFlow);
this.fancyCoverFlow.setAdapter(new FancyCoverFlowSampleAdapter());
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
}
// =============================================================================
// Private classes
// =============================================================================
}
Adapter.java:-
public class FancyCoverFlowSampleAdapter extends FancyCoverFlowAdapter {
// =============================================================================
// Private members
// =============================================================================
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6,};
// =============================================================================
// Supertype overrides
// =============================================================================
#Override
public int getCount() {
return images.length;
}
#Override
public Integer getItem(int i) {
return images[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getCoverFlowItem(int i, View reuseableView, ViewGroup viewGroup) {
ImageView imageView = null;
if (reuseableView != null) {
imageView = (ImageView) reuseableView;
} else {
imageView = new ImageView(viewGroup.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(300, 400));
}
imageView.setImageResource(this.getItem(i));
return imageView;
}
}
Can someone help me , in solving my problem.
Thanks.
My final code with coverflow:-
MainActivity:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = album.MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/androidadminimages";
private ProgressDialog pDialog;
private List<Moviealbum> movieList = new ArrayList<Moviealbum>();
private FancyCoverFlow fancyCoverFlow;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.album_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
fancyCoverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Moviealbum m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),album.
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Moviealbum movie = new Moviealbum();
movie.setTitle(obj.getString("no"));
movie.setThumbnailUrl(obj.getString("alinks"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue...................................
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
AdapterClass :-
public class CustomListAdapter extends FancyCoverFlowAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Moviealbum> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Moviealbum> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getCoverFlowItem(int position, View reuseableView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (reuseableView == null)
reuseableView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) reuseableView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) reuseableView.findViewById(R.id.title);
// getting movie data for the row
Moviealbum m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return reuseableView;
}
The app runs fine , but after loading blank screen is shown with no images.
Logcat:-
Your issue isn't with the CoverFlow code, but rather where you're doing your network operation. On app load, begin your network request for your JSON payload, show a spinner to show the app is loading, and populate your Adapter once your images are loaded. I'm assuming you have network code already given your GridView implementation? Let me know if I've missed something. I hope that helps!
EDIT:
Once you've added images to your Adapter make sure you call notifyDataSetChanged() to tell your adapter to reload its views.
EDIT 2:
Look at this line here:
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
You're passing a new CustomListAdapter rather than passing in your adapter variable. Try fixing that and let me know if it works.
I'm trying to create a 2-line list view in my activity but I've come across one error that I don't know how to fix. How can I achieve this the AppCompat way? I want to achieve something like in the screenshot attached. My error is on line 52.
public class WCLineActivity extends ActionBarActivity {
private class Sample {
private CharSequence title;
private CharSequence summary;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, int summaryResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
this.summary = getResources().getString(summaryResId);
}
#Override
public String toString() { return title.toString(); }
public String getSummary(){ return summary.toString(); }
}
private static Sample[] mSamples;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
setListAdapter(new MyAdapter(this, mSamples));
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_subtitle);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].getSummary());
return convertView;
}
}
}
setListAdapter is a method of ListActivity, and it is not available in Activity. To overcame it, you can declare a ListView in your layout, retrieve the ListView with findViewById and call setAdapter, on that object. E.g.
ListView listView = (ListView) findViewById(R.id.id_list);
listView.setAdapter(new MyAdapter(this, mSamples));
I tried with your code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
ListView listView = (ListView) findViewById(R.id.listView);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
listView.setAdapter(new MyAdapter(this, mSamples));
}