Displaying json data in ListView? - android

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)

Related

Handle large bitmap in viewpager inside listview

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.

Correct item is not selected in Listview

I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.
This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????
Class Blog.java
public class Blog extends Activity {
ListView listView;
ArrayList< String>arrayList; // list of the strings that should appear in ListView
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
listView = (ListView) findViewById(R.id.lstDemo);
// LIST OF STRINGS / DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED IT WE CAN TAKE THIS INPUT FROM USER AS WELL
arrayList = new ArrayList();
arrayList.add("India");
arrayList.add("USA");
arrayList.add("England");
arrayList.add("Singapur");
arrayList.add("China");
arrayList.add("Canada");
arrayList.add("Srilanka");
arrayList.add("SouthAfrica");
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList);
listView.setAdapter(arrayAdapter);
// LETS HIGHLIGHT SELECTED ITEMS
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long itemId) {
/*
* when we click on item on list view we can get it catch item here.
* so view is the item clicked in list view and position is the position
* of that item in list view which was clicked.
*
* Now that we know which item is click we can easily change the color
* of text but when we click on next item we we have to deselect the old
* selected item means recolor it back to default , and then hight the
* new selected item by coloring it .
*
* So here's the code of doing it.
*
*
* */
CheckedTextView textView = (CheckedTextView) view;
for (int i = 0; i < listView.getCount(); i++) {
textView= (CheckedTextView) listView.getChildAt(i);
if (textView != null) {
textView.setTextColor(Color.WHITE);
}
}
listView.invalidate();
textView = (CheckedTextView) view;
if (textView != null) {
textView.setTextColor(Color.BLUE);
}
}
});
}
}
My xml View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Define your variables like this
private ProgressDialog pDialog;
private ListView lv;
private ArrayList<GoModelAll> m_ArrayList = null;
GoArrayAdapter gaa;
Define your AsyncTask like this
new GoAsyncTask().execute();
Your AsyncTask class Code like this
class GoAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
pd.show();
}
#Override
protected String doInBackground(String... params) {
sal = new StaticApiList();
myUrl = StaticApiList.go_api;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
Log.i("talk_all_json", jsonString);
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
return null;
}
#SuppressWarnings("static-access")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
vivek = true;
try{
m_ArrayList = new ArrayList<GoModelAll>();
if (jsonString.length() > 0) {
JSONArray jArray = new JSONArray(jsonString);
dh.open();
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
description = jObject.getString("description");
excert = jObject.getString("excert");
thumsrc = jObject.getString("thumsrc");
title = jObject.getString("title");
postid = jObject.getInt("postid");
Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc
+ " , excert -> " + excert + " , description -> " + description);
Log.d("talklog", "============================= end of " + i + " ===============================");
gma = new GoModelAll();
gma.description = description;
gma.excert = excert;
gma.thumsrc = thumsrc;
gma.title = title;
gma.postid = postid;
Cursor cursor = dh.getSeenStatus(gma.postid);
if(cursor.getCount()>0)
{
cursor.moveToFirst();
if(cursor.getInt(0) == 0)
{
gma.isSeen = false;
}
else
{
gma.isSeen = true;
}
}
else
{
ContentValues cv = new ContentValues();
cv.put(DbHandler.KEY_ID, postid);
cv.put(DbHandler.KEY_VALUE, 0);
dh.addData(DbHandler.TABLE_SEEN, cv);
}
m_ArrayList.add(gma);
}
dh.close();
}
gaa = new GoArrayAdapter(getActivity(), m_ArrayList);
lv = (ListView) getActivity().findViewById(R.id.go_list);
lv.setVisibility(View.VISIBLE);
lv.setAdapter(gaa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
dh.open();
dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1);
m_ArrayList.get(arg2).isSeen = true;
dh.close();
GoDetail fragment = new GoDetail();
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc);
bundle.putString("header_title", "Go");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
}catch(Exception e){
e.printStackTrace();
}
//pDialog.dismiss();
pd.dismiss();
}
}
Your Adapter class
public class GoArrayAdapter extends ArrayAdapter<GoModelAll> {
private final Context context;
ImageLoader imgLoader;
private final ArrayList<GoModelAll> values;
DataHelper dh;
public GoArrayAdapter(Context context,
ArrayList<GoModelAll> values) {
super(context, R.layout.go_row, values);
this.context = context;
this.values = values;
imgLoader = new ImageLoader(context);
dh = new DataHelper(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.go_row, parent, false);
/** Get view over here.. */
GoModelAll asm = values.get(position);
TextView title = (TextView) rowView.findViewById(R.id.go_tv);
ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image);
ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red);
if(asm.isSeen)
{
go_red.setVisibility(View.INVISIBLE);
}
/**Set view over here..*/
title.setText(asm.title);
// Loader image - will be shown before loading image
int loader = R.drawable.image_not_available;
String image_url = asm.thumsrc;
imgLoader.DisplayImage(image_url, loader, business_logo);
return rowView;
}
}
At last your Model class
public class GoModelAll {
public String description = "";
public String excert = "";
public String thumsrc = "";
public String title = "";
public int postid = 0;
public boolean isSeen = false;
}
Show us your adapter code as well and try not to change an item of list view from setOnItemClickListener instead change your data and notify adapter to refresh the view.
Set this as background to your list item :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/white" />
<item android:color="#color/black" />
</selector>

Updating a listview from a HTTP request

I am trying to display a list of items I am getting from a mysql database on a webserver. Here is my create for the page.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getlist);
showBusyDialog();
new GetData()
.execute(picdetails);
}
Here is my GetData class. The problem here is with the lines that are adding items to the listview. I am passing a JSON array as a text result.
public class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... pic) {
// You might be tempted to display the busy dialog here, but you
// CAN'T update the UI from this method!
return loadImageFromNetwork(pic[0]);
}
#Override
protected void onPostExecute(String result) {
// Our long-running process is done, and we can safely access the UI thread
int ct_id;
String item_make;
String item_model;
String item_price;
String item_desc;
String item_location;
String item_image;
dismissBusyDialog();
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout1);
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("id");
item_make=json_data.getString("make");
item_model=json_data.getString("model");
item_price = json_data.getString("price");
item_desc = json_data.getString("cardesc");
item_location = json_data.getString("location");
item_image = json_data.getString("image");
String image_URL = "http://www.myurl.com/images/" + car_image;
TableRow tr = new TableRow(null);
tr.setId(ct_id);
tr.setClickable(true);
tr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
String sdet_id;
int det_id;
// v.setBackgroundColor(Color.GRAY);
det_id = v.getId();
sdet_id = String.valueOf(det_id);
final Intent i = new Intent();
i.setClassName("demo.example.com", "demo.example.com.viewdetails");
i.putExtra("Det_id", sdet_id);
startActivity(i);
// v.setBackgroundColor(Color.TRANSPARENT);
// TODO Auto-generated method stub
}
});
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin=20;
int topMargin=10;
int rightMargin=15;
int bottomMargin=20;
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(tableRowParams);
/* Create a Button to be the row-content. */
ImageView myimage = new ImageView(R.layout.getlist);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
myimage.setImageBitmap(bm);
tr.addView(myimage);
TextView tmake=new TextView(R.layout.getlist);
// tmake.setText(item_make);
tmake.setText(Html.fromHtml("<H1>" + " " + item_location + "</H1>" + "<br /> ;" + item_desc
));
tr.addView(tmake);
TextView tmodel=new TextView(R.layout.getlist);
tmodel.setText(Html.fromHtml("<b><H1>" + " " + "€" + item_price + "</b></H1></br></br>" ));
tr.addView(tmodel);
/* Add row to TableLayout. */
// tr.setPadding(50, 0, 0, 0);
tl.addView(tr);
View v = new View(R.layout.getlist);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
tl.addView(v);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Category Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
The problem appears to be with creating new items to add to the view, lines like this
View v = new View(R.layout.getlist);
Is my overall structure ok or do I need to do this another way?
1.Usually we show the busy dialog in the onPreExecute of the
asyncTask.
2.You need to inflater your views thanks to an inflater.
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.view, null);
Hope this will help you.

i have one error passing of constructor as this in listfragments

I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);

How to display the custom listview using base adapter in listfragments?

I want do custom listview using base adapter in listfragment
I try this code:
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tmp_view = inflater.inflate(R.layout.applistviewfragment, container, false);
ListView list = (ListView) tmp_view.findViewById(R.id.list);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(getActivity(), json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
return tmp_view;
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
public static ArrayList<String> arr = new ArrayList<String>();
public static ArrayList<String> itemprice = new ArrayList<String>();
public static ArrayList<Bitmap> image = new ArrayList<Bitmap>();
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
**System.out.println(price);**
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
I can able to print price value. If I do separately as custom listview I can able to image, text, desc, price. But in MyFragmentlist1 extends with listfragment means I cannot able to view in custom listview. I thought MyListFragment1 in this class only I have problem.
First Create a separate layout layout_txtview. I am just using a textview. You can create layout according to items you want to show in a single row.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceSmall" />
Now Use this layout to inflate in getView() method of your custom adapter.
Now in onCreate() method of MyListFragment1 class just set the adapter to your custom adapter
setAdapter(new MyListFragment1 (<apss your constructor argument>));
and its done.
Try moving the setAdapter in the onActivityCreated callback, in this way
#Override
public void onActivityCreated(Bundle savedInstanceState) {
ListView list = getListView();
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

Categories

Resources