i have viewpager inside listview,According to requirements all images coming from server so i have to display in viewpager as a listview row,so i am using piccaso library for downloading ,the problem is the images resolution is too high ,when i am trying to scroll listview then it goes out of memory,let me know any better solution ,how can i achieve it smoothly
this is my code
this is my fragment class
public class home_fragment extends Fragment {
Session_manager session;
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
ArrayList<String> Array_img = new ArrayList<String>();
ArrayList<String> Array_single_image = new ArrayList<String>();
SampleAdapter adapter;
String accestoken;
String device_id;
CircularImageView img_profile;
private Resources mResources;
ListView Lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_activity, container, false);
Lv = (ListView) rootView.findViewById(R.id.listView);
mResources = getActivity().getResources();
// img_profile = (CircularImageView) rootView.findViewById(R.id.imageView_circular);
// img_profile.setBorderColor(mResources.getColor(R.color.Loginbg));
// img_profile.setBorderWidth(5);
//
// final Bitmap srcBitmap = BitmapFactory.decodeResource(mResources, R.drawable.avatar_girl);
//
// // Display the bitmap in ImageView
// img_profile.setImageBitmap(srcBitmap);
//
// Paint paint = new Paint();
//
// // Get source bitmap width and height
// int srcBitmapWidth = srcBitmap.getWidth();
// int srcBitmapHeight = srcBitmap.getHeight();
//
// /*
// IMPORTANT NOTE : You should experiment with border and shadow width
// to get better circular ImageView as you expected.
// I am confused about those size.
// */
// // Define border and shadow width
// int borderWidth = 25;
// int shadowWidth = 10;
//
// // destination bitmap width
// int dstBitmapWidth = Math.min(srcBitmapWidth,srcBitmapHeight)+borderWidth*2;
// //float radius = Math.min(srcBitmapWidth,srcBitmapHeight)/2;
//
// // Initializing a new bitmap to draw source bitmap, border and shadow
// Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth,dstBitmapWidth, Bitmap.Config.ARGB_8888);
//
// // Initialize a new canvas
// Canvas canvas = new Canvas(dstBitmap);
//
// // Draw a solid color to canvas
// canvas.drawColor(Color.WHITE);
//
// // Draw the source bitmap to destination bitmap by keeping border and shadow spaces
// canvas.drawBitmap(srcBitmap, (dstBitmapWidth - srcBitmapWidth) / 2, (dstBitmapWidth - srcBitmapHeight) / 2, null);
//
// // Use Paint to draw border
// paint.setStyle(Paint.Style.STROKE);
// paint.setStrokeWidth(borderWidth * 2);
// paint.setColor(Color.WHITE);
//
// // Draw the border in destination bitmap
// canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getWidth() / 2, paint);
//
// // Use Paint to draw shadow
// paint.setColor(Color.LTGRAY);
// paint.setStrokeWidth(shadowWidth);
//
// // Draw the shadow on circular bitmap
// canvas.drawCircle(canvas.getWidth()/2,canvas.getHeight()/2,canvas.getWidth()/2,paint);
//
// /*
// RoundedBitmapDrawable
// A Drawable that wraps a bitmap and can be drawn with rounded corners. You
// can create a RoundedBitmapDrawable from a file path, an input stream, or
// from a Bitmap object.
// */
// // Initialize a new RoundedBitmapDrawable object to make ImageView circular
// RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(mResources, dstBitmap);
//
// /*
// setCircular(boolean circular)
// Sets the image shape to circular.
// */
// // Make the ImageView image to a circular image
// roundedBitmapDrawable.setCircular(true);
//
// /*
// setAntiAlias(boolean aa)
// Enables or disables anti-aliasing for this drawable.
// */
// roundedBitmapDrawable.setAntiAlias(true);
//
// // Set the ImageView image as drawable object
// img_profile.setImageDrawable(roundedBitmapDrawable);
session = new Session_manager(getActivity().getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
// img_profile.setImageResource(R.drawable.profile_placeholder);
// access_token
accestoken = user.get(session.Acess_Token);
device_id = user.get(session.device_id);
new Login().execute();
return rootView;
}
private class Login extends AsyncTask<Void, String, Void> implements DialogInterface.OnCancelListener {
String android_id;
String myVersion, Hardware;
JSONObject jsonnode, json_User;
String str;
String Name, access_tocken, Ostype;
#Override
protected void onPreExecute() {
super.onPreExecute();
// mProgressHUD = ProgressHUD.show(HomeActivity.this, "Connecting", true, true, this);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
android_id = Settings.Secure.getString(getActivity().getContentResolver(),
Settings.Secure.ANDROID_ID);
myVersion = android.os.Build.VERSION.RELEASE;
Hardware = Build.MANUFACTURER;
data.clear();
Array_img.clear();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
publishProgress("Please wait...");
String Response = makeServiceCall(Constants.Fetch_posts);
if (Response != null) {
try {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(Response);
} catch (JSONException e) {
e.printStackTrace();
}
// Getting JSON Array node
// JSONArray array1 = null;
str = jsonObj.getString("status");
if (str.contentEquals("true")) {
//jsonnode = jsonObj.getJSONObject("data");
JSONArray array1 = null;
array1 = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < array1.length(); i++) {
JSONObject c = array1.getJSONObject(i);
String id = c.getString("id");
String user_id = c.getString("user_id");
String caption = c.getString("caption");
String Name = c.getString("name");
String username =c.getString("username");
String media1_thumb_url = c.getString("media1_thumb_url");
String media2_thumb_url = c.getString("media2_thumb_url");
String media3_thumb_url = c.getString("media3_thumb_url");
String media4_thumb_url = c.getString("media4_thumb_url");
String media1_url = c.getString("media1_url");
String media2_url = c.getString("media2_url");
String media3_url = c.getString("media3_url");
String media4_url = c.getString("media4_url");
String created_at = c.getString("created_at");
String updated_at = c.getString("updated_at");
String like_status = c.getString("liked");
String follow_status = c.getString("follow");
if(caption.contentEquals("null")){
caption="";
}
HashMap<String, String> Info = new HashMap<String, String>();
Info.put("Post_id", id);
Info.put("username", username);
Info.put("user_id", user_id);
Info.put("Name", Name);
Info.put("caption", caption);
Info.put("media1_thumb_url", media1_thumb_url);
Info.put("media2_thumb_url", media2_thumb_url);
Info.put("media3_thumb_url", media3_thumb_url);
Info.put("media4_thumb_url", media4_thumb_url);
Info.put("media1_url", media1_url);
Info.put("media2_url", media2_url);
Info.put("media3_url", media3_url);
Info.put("media4_url", media4_url);
Info.put("created_at", created_at);
Info.put("updated_at", updated_at);
Info.put("likestatus", like_status);
Info.put("followstatus", follow_status);
data.add(Info);
Array_img.add(media1_url + "," + media2_url + "," + media3_url + "," + media4_url);
Array_single_image.add(media1_url);
// String userid = jsonnode.getString("user_id");
// Name = json_User.getString("name");
// access_tocken= jsonnode.getString("access_token");
// Ostype= jsonnode.getString("device_id");
}
// looping through All Contacts
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
pDialog.dismiss();
adapter = new SampleAdapter(getActivity(),
android.R.layout.simple_list_item_1, data, Array_img,Array_single_image,
getActivity().getApplication());
// RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
// Lv.setLayoutManager(mLayoutManager);
// MyRecyclerAdapter adapter2 = new MyRecyclerAdapter(getActivity(), data,Array_img);
Lv.setAdapter(adapter);
// Lv.setItemAnimator(new DefaultItemAnimator());
}
#Override
public void onCancel(DialogInterface dialog) {
}
}
public String makeServiceCall(String url) {
String response = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
// if (params != null) {
// String paramString = URLEncodedUtils
// .format(params, "utf-8");
// url += "?" + paramString;
// }
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("X-TOKEN", accestoken);
httpGet.addHeader("X-DEVICE", device_id);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
and this adapter class
public class SampleAdapter extends ArrayAdapter<String> implements
OnClickListener {
private static final String KEY_SELECTED_PAGE = "KEY_SELECTED_PAGE";
private static final String KEY_SELECTED_CLASS = "KEY_SELECTED_CLASS";
private static final ArrayList<TransformerItem> TRANSFORM_CLASSES;
private static final String TAG = "SampleAdapter";
private static Context contexts;
private Application mAppContext;
private LayoutInflater mLayoutInflater = null;
private Random mRandom;
static String List_img;
double km, lat_to, lon_to;
String strlat_to, str_long_to;
String Str_km = "";
ImageLoader img_loader;
private LruCache<String, Bitmap> mMemoryCache;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
ArrayList<HashMap<String, String>> imagess = new ArrayList<HashMap<String, String>>();
ArrayList<String> Array_imgadpter = new ArrayList<String>();
static {
TRANSFORM_CLASSES = new ArrayList<>();
TRANSFORM_CLASSES.add(new TransformerItem(CubeOutTransformer.class));
//TRANSFORM_CLASSES.add(new TransformerItem(CubeInTransformer.class));
}
private int mSelectedItem;
private PageAdapter mAdapter;
ArrayList<String> Array_single_image = new ArrayList<String>();
static String[] items;
public SampleAdapter(Context context, int textViewResourceId,
ArrayList<HashMap<String, String>> images, ArrayList<String> Array_img, ArrayList<String> Array_singr, Application app) {
super(context, textViewResourceId);
this.mLayoutInflater = LayoutInflater.from(context);
this.mRandom = new Random();
this.imagess = images;
Array_single_image = Array_singr;
mAppContext = app;
//Array_imgadpter.clear();
this.Array_imgadpter = Array_img;
contexts = context;
}
#SuppressWarnings("static-access")
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
Resources mResources;
final ViewHolder vh;
final Context context = parent.getContext();
img_loader = new ImageLoader(mAppContext);
// if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.list_home_lv,
parent, false);
vh = new ViewHolder();
vh.mPager = (viewpager) convertView.findViewById(R.id.container);
vh.Name = (TextView) convertView.findViewById(R.id.textView7);
vh.Caption = (TextView) convertView.findViewById(R.id.textView10);
vh.Circular_imagview = (CircularImageView) convertView.findViewById(R.id.imageView4);
convertView.setTag(vh);
//vh.mPager.setId(position + 1);
// } else {
// vh = (ViewHolder) convertView.getTag();
//// vh.mPager.setId(position + 1);
// }
// vh.Circular_imagview.setBorderColor(mAppContext.getResources().getColor(R.color.Loginbg));
// vh.Circular_imagview.setBorderWidth(5);
vh.mPager.setId(position + 1);
vh.mPager.setOnItemClickListener(new viewpager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
int id = vh.mPager.getId();
id = id - 1;
String postion = String.valueOf(id);
List_img = Array_imgadpter.get(id);
String str_id =imagess.get(id).get("Post_id");
String status_like=imagess.get(id).get("likestatus");
String caption=imagess.get(id).get("caption");
//Toast.makeText(mAppContext,"click "+id,Toast.LENGTH_LONG).show();
Intent lObjIntent = new Intent(mAppContext, Images_comment_screen.class);
lObjIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
lObjIntent.putExtra("images",List_img);
lObjIntent.putExtra("Post_id",str_id);
lObjIntent.putExtra("status_like",status_like);
lObjIntent.putExtra("caption",caption);
mAppContext.startActivity(lObjIntent);
//finish();
}
});
Paint paint = new Paint();
mResources = mAppContext.getResources();
try {
final Bitmap srcBitmap = BitmapFactory.decodeResource(mResources, R.drawable.profile_placeholder);
// Get source bitmap width and height
int srcBitmapWidth = srcBitmap.getWidth();
int srcBitmapHeight = srcBitmap.getHeight();
/*
IMPORTANT NOTE : You should experiment with border and shadow width
to get better circular ImageView as you expected.
I am confused about those size.
*/
// Define border and shadow width
int borderWidth = 20;
int shadowWidth = 0;
// destination bitmap width
int dstBitmapWidth = Math.min(srcBitmapWidth, srcBitmapHeight) + borderWidth * 2;
//float radius = Math.min(srcBitmapWidth,srcBitmapHeight)/2;
// Initializing a new bitmap to draw source bitmap, border and shadow
Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth, dstBitmapWidth, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dstBitmap);
// Initialize a new canvas
// Draw a solid color to canvas
canvas.drawColor(Color.WHITE);
// Draw the source bitmap to destination bitmap by keeping border and shadow spaces
canvas.drawBitmap(srcBitmap, (dstBitmapWidth - srcBitmapWidth) / 2, (dstBitmapWidth - srcBitmapHeight) / 2, null);
// Use Paint to draw border
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(borderWidth * 2);
paint.setColor(Color.WHITE);
// Draw the border in destination bitmap
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getWidth() / 2, paint);
// Use Paint to draw shadow
paint.setColor(Color.LTGRAY);
paint.setStrokeWidth(shadowWidth);
// Draw the shadow on circular bitmap
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getWidth() / 2, paint);
/*
RoundedBitmapDrawable
A Drawable that wraps a bitmap and can be drawn with rounded corners. You
can create a RoundedBitmapDrawable from a file path, an input stream, or
from a Bitmap object.
*/
// Initialize a new RoundedBitmapDrawable object to make ImageView circular
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(mResources, dstBitmap);
/*
setCircular(boolean circular)
Sets the image shape to circular.
*/
// Make the ImageView image to a circular image
roundedBitmapDrawable.setCircular(true);
/*
setAntiAlias(boolean aa)
Enables or disables anti-aliasing for this drawable.
*/
roundedBitmapDrawable.setAntiAlias(true);
// Set the ImageView image as drawable object
vh.Circular_imagview.setImageDrawable(roundedBitmapDrawable);
}catch (OutOfMemoryError error){
error.printStackTrace();
}
//convertView.setTag(vh);
//int selectedPage = 0;
//vh.mPager.setId(position + 1);
try {
vh.mPager.setPageTransformer(true, TRANSFORM_CLASSES.get(0).clazz.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
//mPager.setCurrentItem(selectedPage);
List_img = Array_imgadpter.get(position);
vh.Name.setText(imagess.get(position).get("username"));
vh.Caption.setText(imagess.get(position).get("caption"));
vh.mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int positionn = vh.mPager.getId();
positionn = positionn - 1;
String postion = String.valueOf(positionn);
List_img = Array_imgadpter.get(positionn);
items = List_img.split(",");
}
#Override
public void onPageSelected(int position) {
int positionn = vh.mPager.getId();
positionn = positionn - 1;
String postion = String.valueOf(positionn);
List_img = Array_imgadpter.get(positionn);
}
#Override
public void onPageScrollStateChanged(int state) {
int positionn = vh.mPager.getId();
positionn = positionn - 1;
String postion = String.valueOf(positionn);
List_img = Array_imgadpter.get(positionn);
}
});
FragmentManager fm = ((Activity) context).getFragmentManager();
mAdapter = new PageAdapter(fm);
vh.mPager.setAdapter(mAdapter);
return convertView;
}
static class ViewHolder {
ImageView imgView, star1, star2, star3, star4;
TextView Name, Caption, fixed_meal, price, rating, distance, TxtVw_Afterdiscount, Txtvw;
Button BTN_DETAIL;
private viewpager mPager;
Button button2;
CircularImageView Circular_imagview;
}
#Override
public int getCount() {
return imagess.size();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// int positionn = vh.mPager.getId();
// positionn = positionn - 1;
// String postion = String.valueOf(positionn);
// List_img = Array_imgadpter.get(positionn);
// Intent intent = new Intent(mAppContext, Images_comment_screen.class);
// intent.putExtra("images", List_img);
//
//
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// mAppContext.startActivity(intent);
Toast.makeText(mAppContext, "click", Toast.LENGTH_LONG).show();
}
private static final class TransformerItem {
final String title;
final Class<? extends ViewPager.PageTransformer> clazz;
public TransformerItem(Class<? extends ViewPager.PageTransformer> clazz) {
this.clazz = clazz;
title = clazz.getSimpleName();
}
#Override
public String toString() {
return title;
}
}
public class PlaceholderFragment extends Fragment {
private static final String EXTRA_POSITION = "EXTRA_POSITION";
//private final int[] COLORS = new int[]{R.drawable.imgone, R.drawable.imgtwo, R.drawable.imgthree, R.drawable.imgfour};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final int position = getArguments().getInt(EXTRA_POSITION);
final ImageView textViewPosition = (ImageView) inflater.inflate(R.layout.fragment_main, container, false);
items = List_img.split(",");
String url = items[position];
try {
Picasso.with(contexts).load(items[position]).placeholder(R.drawable.placeholderdevzillad).into(textViewPosition);
//
// img_loader.DisplayImage(url,textViewPosition);
} catch (OutOfMemoryError error) {
}
//textViewPosition.setBackgroundResource(COLORS[position]);
return textViewPosition;
}
}
private class PageAdapter extends FragmentStatePagerAdapter {
public PageAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
final Bundle bundle = new Bundle();
bundle.putInt(PlaceholderFragment.EXTRA_POSITION, position);
final PlaceholderFragment fragment = new PlaceholderFragment();
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
}
Here are some suggestions:
You haven't recycle your ListView item, in your SampleAdapter-getView, convertView is not reused if it is not null.
Don't need to use Fragment as your ViewPager item, just use ViewGroup as ViewPager's item.
For more, I think you can Define a Recycled PagerAdapter to manage and recycle all the items in different ViewPagers of different ListView item.
Forgive my bad English, and hope this is helpful for you.
Related
I built a fragment which use data in a web service call to display gridView list. It has about .5 second of delay to actually grab data and display the gridView on xml. Issue is that Everytime I come back from other pages or reorient the view, the delay happens. I don't know what I am missing but should the system save the last view in memory to display before it gets the real data from web service whenever I come back from other pages?
public class fragment_grid_room extends Fragment{
private static final String TAG = fragment_grid_room.class.getName();
public fragment_grid_room() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//start async task to display rooms
DisplayGridRooms gridRooms = new DisplayGridRooms();
gridRooms.execute(new String[] { "params" });
View rootView = inflater.inflate(R.layout.fragment_roomgrid, container, false);
//rootView.findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
//add current date
TextView dayTV = (TextView) rootView.findViewById(R.id.currentDate);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
Date now = new Date();
String strDate = sdf.format(now);
Log.d(TAG, "*****strdate"+strDate);
dayTV.setText(strDate);
return rootView;
}
//async task to display rooms
private class DisplayGridRooms extends AsyncTask<String, Void, JSONArray> {
JSONArray jsonArrayRooms;
#Override
protected JSONArray doInBackground(String... url) {
String email = getResources().getString(R.string.temp_login);
String pwd = getResources().getString(R.string.temp_pwd);
String username = "apark#anexinet.com";
webServiceRoom wsRoom = new webServiceRoom();
jsonArrayRooms = wsRoom.getRoomList(email, pwd, username);
//System.out.println("222******returning jsonroom with: "+jsonRoom.length());
return jsonArrayRooms;
}
#Override
protected void onPostExecute(JSONArray jsonArrayRooms) {
ArrayList<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){ //count available rooms
availNum+=1;
};
} catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
final GridView gridView = (GridView) getActivity().findViewById(R.id.gridview_room);
//set availability bar
TextView avalBar = (TextView) getActivity().findViewById(R.id.availableBar);
String availbilityText = "Available "+availNum+" of "+totalNumRooms;
avalBar.setText(availbilityText);
Window window = getActivity().getWindow();
View v = window.getDecorView();
ImageButton imageGrid = (ImageButton) v.findViewById(R.id.gridButton);
imageGrid.setVisibility(View.GONE);
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int numColFinal = 1;
if (width > 350) {
double numCol = width / 350;
numColFinal = (int) numCol;
}
gridView.setNumColumns(numColFinal);
Log.d(TAG, "screen width, numColFinal=" + width + "," + numColFinal);
// getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
gridView.setAdapter(new CustomAdaptorRoomGrid(getActivity(), room_list));
//when list is clicked, move to detail page
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Object o = gridView.getItemAtPosition(position);
roomGrid fullObject = (roomGrid)o;
String roomName = fullObject.getRoomName();
Intent intent = new Intent(getActivity(), RoomTimeslotActivity.class)
.putExtra(Intent.EXTRA_TEXT, roomName);
startActivity(intent);
}
});
}
}
}
One way to fix the issue is by storing data in shared preferences every time you close your fragment.
First a little improvement. You can move the code below from onPostExecute() in doInBackground(). And then rather return JSONArray in onPostExecute() you can return your list of roomGrid
List<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){
//count available rooms
availNum+=1;
};
}
catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
In your class RoomGrid (the one you add in your list), add
method toJson() - which creates a JSONObjectinstance representing your data
static method public static RoomGrid from(JSONObject json) - which will create and return an RoomGrid instance (or null if json is null, empty, etc)
In you CustomAdaptorRoomGrid add
- getItems() which will return the list of RoomGrid you supplied when creating the adapter
in your fragment onDestroyView() add:
CustomAdaptorRoomGrid adapter = (CustomAdaptorRoomGrid) gridView.getAdapter();
int length = adapter != null && adapter.getItems() != null ? adapter.getItems().size() : 0;
if (length > 0) {
// create a JSONArray from the list
JSONArray array = new JSONArray();
for (RoomGrid item : adapter.getItems()) {
array.put(item.toJson();
}
// add the value in preferences
SharedPreferences prefs = ...;
prefs.edit().put("YOUR_KEY", array.toString()).apply();
}
And finally in your fragment onViewCreated() check for the array from the shared preferences and revert it to a list of your items and supply them to the adapter.
Then engage your task to download and refresh whatever you need.
I am using curlview for curl effect my data contain images for each page in curlview with my code i got blank pages without image which I seted in imageurllist doing json parsing how i got images instead of blank pages.
This is my code.
public class CurlActivity extends Activity {
private CurlView mCurlView;
public String cid;
public ArrayList<String>magazineidlist;
public String middata;
public String url;
public String imgurl;
public Bitmap bitmap;
public ImageLoader imageloder;
public ImageView imageView;
public ArrayList<String>imageurllist;
public GridImageAdapter gadapter;
public CurlActivity c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_curl);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getAllMagazineById();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle!=null){
cid = bundle.getString("mid");
Log.d("magazine id", cid);
}
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.sample};
//LinearLayout llout = (LinearLayout) findViewById(R.layout.sample);
#SuppressWarnings("unused")
//ImageView imageView = (ImageView) findViewById(R.id.imageviewsample);
#Override
public int getPageCount() {
return imageurllist.size();
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index",String.valueOf(index));
View v = inflater.inflate((mBitmapIds[index]),null);
v.measure(
MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight()
,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
/*// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;*/
}
}
}
/**
* CurlView size changed observer.
*/
class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
//mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
public Bitmap GetBitmapfromUrl(String scr) {
try {
URL url=new URL(scr);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
// Bitmap bmp = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void getAllMagazineById() {
new AsyncTask<Void, Void, String>() {
ProgressDialog mProgressDialog;
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
magazineidlist = new ArrayList<String>();
imageurllist = new ArrayList<String>();
//imageloder = new ImageLoader(CurlActivity.this);
// LayoutInflater factory = LayoutInflater.from(CurlActivity.this);
// View child = factory.inflate(R.layout.sample, null);
// imageView = (ImageView)child.findViewById(R.id.imageviewsample);
//imageView = (ImageView)findViewById(R.id.imageviewsample);
try {
JSONObject jsob = new JSONObject(result.toString());
if (jsob.getString("msg").equalsIgnoreCase("Success")) {
JSONArray datajson = jsob.getJSONArray("data");
for (int i = 0; i < datajson.length(); i++) {
JSONObject c = datajson.getJSONObject(i);
middata = c.getString("magazine_id");
imgurl = c.getString("image_url");
magazineidlist.add(middata);
imageurllist.add(imgurl);
Log.d("imageurllist value at index" +i, imageurllist.get(i));
//imageloder.DisplayImage(imageurllist.get(i),imageView);
String url = imageurllist.get(i);
Log.d("url val", url);
}
gadapter = new GridImageAdapter(c, imageurllist);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(0);
mCurlView.setBackgroundColor(0xFF202830);
} else if(jsob.getString("msg").equalsIgnoreCase("Failure")) {
System.out.println("not a valid data");
}
else
{
System.out.println("error");
}
} catch (Exception e) {
Log.e("error", "" + e);
}
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();
httppost1 = new HttpPost(JsonKey.MAIN_URL);
// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
2);
nameValuePairs1.add(new BasicNameValuePair("action",
"GetMagazinePageImagesbyid"));
nameValuePairs1.add(new BasicNameValuePair("iMagezineId",
cid));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1.getEntity()
.getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(" Get All magazine original data", sb1.toString());
return sb1.toString();
} catch (Exception e) {
Log.e("Get All magazine response problem", "" + e);
return " ";
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(CurlActivity.this);
mProgressDialog.setTitle("");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();
}
}.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
public class GridImageAdapter extends BaseAdapter {
public Context mContext;
// public final String[] web;
// final int ImageId[];
public CurlActivity activity;
public ImageLoader imageloader;
// Constructor
public GridImageAdapter(CurlActivity c, ArrayList<String> imageUrl) {
// TODO Auto-generated constructor stub
mContext = c;
imageurllist = imageUrl;
imageloader = new ImageLoader(CurlActivity.this);
}
public int getCount() {
return imageurllist.size();
}
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) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.sample, null);
ImageView img = (ImageView) grid.findViewById(R.id.imageviewsample);
imageloader.DisplayImage(imageurllist.get(position), img);
}
/*
* ImageView imageView; if (convertView == null) { imageView = new
* ImageView(mContext); imageView.setLayoutParams(new
* GridView.LayoutParams(85, 85));
* imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
* imageView.setPadding(8, 8, 8, 8); }
*/else {
grid = (View) convertView;
}
/*
* imageView.setImageResource(mThumbIds[position]); return
* imageView;
*/
return grid;
}
// Keep all Images in array
/*
* public Integer[] mThumbIds = { R.drawable.nightlife,
* R.drawable.coffee, R.drawable.shopping, R.drawable.seeanddo,
*
* };
*/
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64
.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
}
}
I want to crate curlview with dynemic data. I used imageview to display image into curlview because my api contain image in data. but image is not displayed into imageview how i do this?
Below is my code.
public class CurlActivity extends Activity {
private CurlView mCurlView;
public String cid;
public ArrayList<String>magazineidlist;
public String middata;
public String url;
public String imgurl;
public Bitmap bitmap;
public ImageLoader imageloder;
public ImageView imageView;
public ArrayList<String>imageurllist;
public GridImageAdapter gadapter;
public CurlActivity c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_curl);
gadapter = new GridImageAdapter(c, imageurllist);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getAllMagazineById();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle!=null){
cid = bundle.getString("mid");
Log.d("magazine id", cid);
}
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.sample};
//LinearLayout llout = (LinearLayout) findViewById(R.layout.sample);
#SuppressWarnings("unused")
//ImageView imageView = (ImageView) findViewById(R.id.imageviewsample);
#Override
public int getPageCount() {
return imageurllist.size();
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index",String.valueOf(index));
View v = inflater.inflate(mBitmapIds[index],null);
v.measure(
MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight()
,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
/*// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;*/
}
}
}
/**
* CurlView size changed observer.
*/
class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
//mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
public Bitmap GetBitmapfromUrl(String scr) {
try {
URL url=new URL(scr);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
// Bitmap bmp = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void getAllMagazineById() {
new AsyncTask<Void, Void, String>() {
ProgressDialog mProgressDialog;
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
magazineidlist = new ArrayList<String>();
imageurllist = new ArrayList<String>();
//imageloder = new ImageLoader(CurlActivity.this);
// LayoutInflater factory = LayoutInflater.from(CurlActivity.this);
// View child = factory.inflate(R.layout.sample, null);
// imageView = (ImageView)child.findViewById(R.id.imageviewsample);
//imageView = (ImageView)findViewById(R.id.imageviewsample);
try {
JSONObject jsob = new JSONObject(result.toString());
if (jsob.getString("msg").equalsIgnoreCase("Success")) {
JSONArray datajson = jsob.getJSONArray("data");
for (int i = 0; i < datajson.length(); i++) {
JSONObject c = datajson.getJSONObject(i);
middata = c.getString("magazine_id");
imgurl = c.getString("image_url");
magazineidlist.add(middata);
imageurllist.add(imgurl);
Log.d("imageurllist value at index" +i, imageurllist.get(i));
//imageloder.DisplayImage(imageurllist.get(i),imageView);
String url = imageurllist.get(i);
Log.d("url val", url);
}
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
//mCurlView.setCurrentIndex(0);
mCurlView.setBackgroundColor(0xFF202830);
} else if(jsob.getString("msg").equalsIgnoreCase("Failure")) {
System.out.println("not a valid data");
}
else
{
System.out.println("error");
}
} catch (Exception e) {
Log.e("error", "" + e);
}
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();
httppost1 = new HttpPost(JsonKey.MAIN_URL);
// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
2);
nameValuePairs1.add(new BasicNameValuePair("action",
"GetMagazinePageImagesbyid"));
nameValuePairs1.add(new BasicNameValuePair("iMagezineId",
cid));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1.getEntity()
.getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(" Get All magazine original data", sb1.toString());
return sb1.toString();
} catch (Exception e) {
Log.e("Get All magazine response problem", "" + e);
return " ";
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(CurlActivity.this);
mProgressDialog.setTitle("");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();
}
}.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
public class GridImageAdapter extends BaseAdapter {
public Context mContext;
// public final String[] web;
// final int ImageId[];
public CurlActivity activity;
public ImageLoader imageloader;
// Constructor
public GridImageAdapter(CurlActivity c, ArrayList<String> imageUrl) {
// TODO Auto-generated constructor stub
mContext = c;
imageurllist = imageUrl;
imageloader = new ImageLoader(CurlActivity.this);
}
public int getCount() {
return imageurllist.size();
}
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) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.sample, null);
ImageView img = (ImageView) grid.findViewById(R.id.imageviewsample);
imageloader.DisplayImage(imageurllist.get(position), img);
}
/*
* ImageView imageView; if (convertView == null) { imageView = new
* ImageView(mContext); imageView.setLayoutParams(new
* GridView.LayoutParams(85, 85));
* imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
* imageView.setPadding(8, 8, 8, 8); }
*/else {
grid = (View) convertView;
}
/*
* imageView.setImageResource(mThumbIds[position]); return
* imageView;
*/
return grid;
}
// Keep all Images in array
/*
* public Integer[] mThumbIds = { R.drawable.nightlife,
* R.drawable.coffee, R.drawable.shopping, R.drawable.seeanddo,
*
* };
*/
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64
.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
}
}
In my android project, I have a ListView which populates the data entered by the user on runtime. Along with this, I want to show some data from an existing JSON file. So I parsed this JSON file and stored it in a String. How can I show both of these in my application?Can I use same the Listview for both ?
This is my code
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonshoutdata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close(); // stop reading
}
catch (IOException e)
{
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
// Try to parse JSON
try {
//urlist = new ArrayList<HashMap<String, String>>();
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("message");
ArrayList<String> messages = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
messages.add(message);
}
This is my customList adapter for json data
customtest adapter = new customtest(Single.this,R.layout.list_single_shout_single,messages);
ListView list = (ListView)findViewById(R.id.list_shout_screen);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Single.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my customList adapter which i already have
final CustomListSingle adapter1 = new CustomListSingle(Single.this, web1,web,rounded,imageId2,imageId3,result1,result2);
//CustomListSingle adapter = new CustomListSingle(Single.this, web1,web,rounded,imageId2,imageId3,result1,result2);
list_shout_screen=(ListView)findViewById(R.id.list_shout_screen);
list_shout_screen.setAdapter(adapter1);
//list_shout_screen.setAdapter(adapter);
list_shout_screen.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
TextView txtTitle = (TextView)findViewById(R.id.txt);
txtTitle.length();
Toast.makeText(Single.this, "Length is " + txtTitle.getMeasuredWidth(), Toast.LENGTH_SHORT).show();
txtTitle.getTextSize();
}
}
);
//Button click activity......
final EditText et = (EditText)findViewById(R.id.EditText1);
final Button imb=(Button)findViewById(R.id.btn_send);
imb.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
String str = et.getText().toString();
web1.add(str);
Toast.makeText(Single.this, "You entered...."+str, Toast.LENGTH_SHORT).show();
adapter1.notifyDataSetChanged();
scrollMyListViewToBottom();
et.setText(" ");
}
This is my adapter class
public CustomListSingle(Activity context,ArrayList<String> web,ArrayList<String> web1,Bitmap rounded,Integer[] imageId2,Integer[] imageId3,Bitmap image1,Bitmap image)
{
super(context, R.layout.list_single_shout_single, web);
this.context = context;
this.web = web;
this.web1 = web1;
//this.imageId1 = imageId1;
this.rounded=rounded;
this.imageId2 = imageId2;
this.imageId3 = imageId3;
this.image=image;
this.image1=image1;
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single_shout_single, null, true);
/*msg*/
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
//pic
ImageView imageView1 = (ImageView) rowView.findViewById(R.id.img1);
ImageView imageView3 = (ImageView) rowView.findViewById(R.id.img);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
txtTitle.setLayoutParams(params);
txtTitle.setText(web.get(position));
txtTitle.setBackgroundResource(R.drawable.test);
imageView1.setImageBitmap(rounded);
imageView3.setImageBitmap(image1);
return rowView;
}
}
Method for making images circular
public static Bitmap getCircularBitmapFrom(Bitmap bitmap)
{
if (bitmap == null) {
return null;
}
float radius = bitmap.getWidth() > bitmap.getHeight() ? ((float) bitmap
.getHeight()) / 2f : ((float) bitmap.getWidth()) / 2f;
if (radius < 0) {
radius = 0;
}
Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP,
TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
radius, paint);
return canvasBitmap;
}
And this
Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.white);
Bitmap bmp1=BitmapFactory.decodeResource(getResources(), R.drawable.prof_pic_a);
Bitmap images = BitmapFactory.decodeResource(getResources
(),R.drawable.prof_pic_a);
Bitmap rounded;
rounded=getCircularBitmapFrom(images);
result1=getCircularBitmapFrom(bmp);
result2=getCircularBitmapFrom(bmp1);
suppose you have this arraylist
ArrayList<String> messages = new ArrayList<String>(); //add this line on top so it will be accessed globally
and your button code
final Button imb=(Button)findViewById(R.id.btn_send);
imb.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
String str = et.getText().toString();
messages.add(str);
Toast.makeText(Single.this, "You entered...."+str, Toast.LENGTH_SHORT).show();
adapter1.notifyDataSetChanged();
scrollMyListViewToBottom();
et.setText(" ");
adapter1.notifyDataSetChanged(); //list is the name of your listview
}
call notifyDataSetChanged whenever you want to update your listview(after adding data in your arraylist)
I have an list with an custom adapter, and upon refresh I want to add new data to be displayed(if any available).
But the list isn't being update. I tried all the methods with notifyDataSetChanged for the adapter but it's not updated.
Please help. I lost so much time with this and I feel like I'm loosing my mind with this one.
Here is the code:
NewsFeedArrayAdapter
public class NewsFeedArrayAdapter extends ArrayAdapter<FeedItem> {
private final String TAG_DEBUG = this.getClass().getName();
private LayoutInflater inflator;
public final static String PREFS_NAME = "shared_pref_eid";
ImageLoader imageLoader;
Utils utils;
public NewsFeedArrayAdapter(Activity context) {
super(context, R.layout.feed_story_content);
this.utils = new Utils(context);
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = ImageLoader.getInstance(context);
}
/**
* Static Inner class.
*
* Makes the ListView more efficient since Android recycles views in a ListView.
*/
public static class ViewHolder {
public ImageView profilePicture, image;
public TextView author, timePast, message, likes, comments;
public LinearLayout like, comment, share, likesCommentsCounter;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = null;
FeedItem feedItem = FeedItemParser.FEEDS.get(position);
ViewHolder holder = null;
if (convertView == null) {
rowView = inflator.inflate(R.layout.feed_story_content, parent, false);
holder = new ViewHolder();
holder.profilePicture = (ImageView) rowView.findViewById(R.id.feed_story_profile_picture);
holder.author = (TextView) rowView.findViewById(R.id.feed_story_author);
holder.timePast = (TextView) rowView.findViewById(R.id.feed_story_time_past);
holder.message = (TextView) rowView.findViewById(R.id.feed_story_message);
holder.image = (ImageView) rowView.findViewById(R.id.feed_story_image);
holder.like = (LinearLayout) rowView.findViewById(R.id.feed_feedback_like_container);
holder.comment = (LinearLayout) rowView.findViewById(R.id.feed_feedback_comment_container);
holder.share = (LinearLayout) rowView.findViewById(R.id.feed_feedback_share_container);
holder.likes = (TextView) rowView.findViewById(R.id.feed_story_likes);
holder.comments = (TextView) rowView.findViewById(R.id.feed_story_comments);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = ((ViewHolder) rowView.getTag());
}
Log.i(TAG_DEBUG, "feedItem = " + feedItem);
if (feedItem != null) {
if (!TextUtils.isEmpty(feedItem.feed_story_from_name)) {
holder.author.setText(feedItem.feed_story_from_name);
} else {
holder.author.setText("Unknown");
}
if (!TextUtils.isEmpty(feedItem.feed_story_created_time)) {
// Convert the date to calendar date
Calendar calendarDate = null;
try {
calendarDate = ISO8601.toCalendar(feedItem.feed_story_created_time);
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
calendarDate.getTimeInMillis(),
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS);
holder.timePast.setText(relativeTimeSpan);
} else {
holder.timePast.setText("Unknown");
}
Log.i(TAG_DEBUG, "feedItem.feed_story_message = " + feedItem.feed_story_message);
if (!TextUtils.isEmpty(feedItem.feed_story_message)) {
holder.message.setText(feedItem.feed_story_message);
} else {
holder.message.setText("Unkown");
// holder.message.setVisibility(View.GONE);
}
// Display the icon of the feed
int defaultResourceIcon = R.drawable.no_avatar;
if (feedItem.feed_story_from_id != null) {
String iconUrl = "https://graph.facebook.com/" + feedItem.feed_story_from_id + "/picture?type=normal";
if (Session.getActiveSession() != null &&
Session.getActiveSession().getAccessToken() != null) {
iconUrl += "&access_token=" + Session.getActiveSession().getAccessToken();
}
Log.i(TAG_DEBUG, "iconUrl = " + iconUrl);
imageLoader.displayImage(iconUrl, holder.profilePicture, 70, defaultResourceIcon);
} else {
imageLoader.cancelDisplayTaskFor(holder.profilePicture);
holder.profilePicture.setImageResource(defaultResourceIcon);
}
// Display the picture of the feed
int defaultResourcePicture = R.drawable.empty;
if (!TextUtils.isEmpty(feedItem.feed_story_picture)) {
holder.image.setVisibility(View.VISIBLE);
Log.i(TAG_DEBUG, "feed_picture = " + feedItem.feed_story_picture + "\nfeed_picture_height = " + feedItem.feed_story_picture_height);
imageLoader.displayImage(feedItem.feed_story_picture, holder.image, -1, defaultResourcePicture);
} else {
imageLoader.cancelDisplayTaskFor(holder.image);
// holder.image.setImageResource(defaultResourcePicture);
holder.image.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_likes)) {
holder.likes.setVisibility(View.VISIBLE);
String likes = feedItem.feed_story_likes + " like";
if (!feedItem.feed_story_likes.contentEquals("1")) {
likes += "s";
}
holder.likes.setText(likes);
} else {
holder.likes.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_comments)) {
holder.comments.setVisibility(View.VISIBLE);
String comments = feedItem.feed_story_comments + " comment";
if (!feedItem.feed_story_comments.contentEquals("1")) {
comments += "s";
}
holder.comments.setText(comments);
} else {
holder.comments.setVisibility(View.GONE);
}
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Like content - TBA");
}
});
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Comment section - TBA");
}
});
holder.share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Sharing content - TBA");
}
});
}
return rowView;
}
#Override
public int getCount() {
return FeedItemParser.FEEDS.size();
}
}
The adapter on the list is set after the first request, when I get my first results, like this:
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Set the custom adapter
customAddapter = new NewsFeedArrayAdapter(activity);
// Populate the fragment with the data from JSON
actualListView.setAdapter(customAddapter);
FeedItemParser is an custom class where I store my custom objects:
public class FeedItemParser {
// JSON Node names
public static final String
TAG_DATA = "data", // Array
TAG_ID = "id", // String
TAG_FROM = "from", // Object
TAG_FROM_ID = "id", // String
TAG_FROM_CATEGORY = "category", // String
TAG_FROM_NAME = "name", // String
TAG_TO = "to", // Object
TAG_TO_DATA = "data", // Array
TAG_TO_DATA_ID = "id", // String
TAG_TO_DATA_NAME = "name", // String
TAG_MESSAGE = "message", // String
TAG_PICTURE = "picture", // String
TAG_ACTIONS = "actions", // Array
TAG_ACTIONS_NAME = "name", // String
TAG_ACTIONS_LINK = "link", // String
TAG_PRIVACY = "privacy", // Object
TAG_PRIVACY_VALUE = "value", // String
TAG_TYPE = "type", // String
TAG_STATUS_TYPE = "status_type", // String
TAG_CREATED_TIME = "created_time", // String
TAG_UPDATED_TIME = "updated_time", // String
TAG_LIKES = "likes", // Object
TAG_LIKES_COUNT = "count", // String
TAG_COMMENTS = "comments", // Object
TAG_COMMENTS_DATA = "data", // Array
TAG_PAGING = "paging", // Object
TAG_PAGING_PREVIOUS = "previous",// String
TAG_PAGING_NEXT = "next"; // String
/**
* An array of Shelter items.
*/
public static List<FeedItem> FEEDS = new ArrayList<FeedItem>();
/**
* A map of Array items, by ID.
*/
public static Map<String, FeedItem> FEED_MAP = new HashMap<String, FeedItem>();
public static void addItem(FeedItem item) {
FEEDS.add(FEEDS.size(), item);
FEED_MAP.put(item.feed_story_id, item);
}
public static void addPicture (String feed_story_id, String picture, String height) {
FeedItem feedItem = FEED_MAP.get(feed_story_id);
feedItem.feed_story_picture = picture;
feedItem.feed_story_picture_height = height;
}
public static class FeedItem {
public String feed_story_id, feed_story_from_id, feed_story_from_category,
feed_story_from_name, feed_story_message, feed_story_picture, feed_story_picture_height,
feed_story_privacy, feed_story_type, feed_story_status_type, feed_story_created_time,
feed_story_updated_time, feed_story_likes, feed_story_comments;
/**
* #param feed_story_id
* #param feed_story_from_id
* #param feed_story_from_category
* #param feed_story_from_name
* #param feed_story_message
* #param feed_story_picture
* #param feed_story_privacy
* #param feed_story_type
* #param feed_story_status_type
* #param feed_story_created_time
* #param feed_story_updated_time
*/
public FeedItem(String feed_story_id, String feed_story_from_id, String feed_story_from_category,
String feed_story_from_name, String feed_story_message, String feed_story_picture,
String feed_story_picture_height, String feed_story_privacy, String feed_story_type,
String feed_story_status_type, String feed_story_created_time, String feed_story_updated_time,
String feed_story_likes, String feed_story_comments) {
this.feed_story_id = feed_story_id;
this.feed_story_from_id = feed_story_from_id;
this.feed_story_from_category = feed_story_from_category;
this.feed_story_from_name = feed_story_from_name;
this.feed_story_message = feed_story_message;
this.feed_story_picture = feed_story_picture;
this.feed_story_picture_height = feed_story_picture_height;
this.feed_story_privacy = feed_story_privacy;
this.feed_story_type = feed_story_type;
this.feed_story_status_type = feed_story_status_type;
this.feed_story_created_time = feed_story_created_time;
this.feed_story_updated_time = feed_story_updated_time;
this.feed_story_likes = feed_story_likes;
this.feed_story_comments = feed_story_comments;
}
#Override
public String toString() {
return feed_story_message;
}
}
}
When I request new data(refresh), I add the new data in my object (the same way I do the first time):
FeedItemParser.addItem(new FeedItem(
id,
from_id,
from_category,
from_name,
message,
null, // Will be gotten through another request
null,
privacy_value,
type,
status_type,
created_time,
updated_time,
likes,
comments));
After that I call
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Notify list adapter to update the list
customAddapter.notifyDataSetChanged();
SOLUTION
Based on the recommendations of #Selvin I have managed to update my list after adding more data. Basically I changed my adapter(I'm not using an filtered list anymore, but I'm directly using my custom objects). And after I add new Object, I update the list by calling notifyDataSetChanged() on the existing adapter.
I have also update my code, maybe it will help someone else that is stuck is this situation.
Thanks again #Selvin.