Correct item is not selected in Listview - android

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>

Related

ListView CustomAdapter getView is not calling

Below is my code, here i am getting response..
Fetching Data from server in josn
getRequest();
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
//
private void getRequest(){
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//
try{
Log.d("Get top called","try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if(response!=null){
try{
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
for(int i=0;i<songs.length();i++){
defaultSongsDetails = new HashMap<String, String>();
String title,artist,language,imageUrl,songUrl,vocalUrl,duration=null;
String sdCardPathOfImage,sdCardPathOfOriginalSong,sdCardPathOfVocalSong=null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title",title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist",artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language",language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration",duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail=null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName=null; int cut = songUrl.lastIndexOf('/'); if (cut != -1) { fileName = songUrl.substring(cut + 1); }
sdCardPathOfOriginalSong = basepath+"/songs/" + fileName;
defaultSongsDetails.put("song_original_path",
sdCardPathOfOriginalSong);
String vocalFileName=null; int cutVocal = songUrl.lastIndexOf('/'); if (cut != -1) { vocalFileName =
songUrl.substring(cutVocal + 1); } sdCardPathOfVocalSong =
basepath+"/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
//Adding Hashmap to ArrayList
defaultSongsDetailList.add(defaultSongsDetails);
adapter = new CustomList(JsonActivity.this,defaultSongsDetailList);
}catch (Exception e){ e.printStackTrace(); } } }catch (Exception e) { e.printStackTrace(); } }
}); trd.start();
}
//CustomList Adapter class
public class CustomList extends ArrayAdapter<HashMap<String, String>>{
private final Activity context;
private ArrayList<HashMap<String, String>> songList;
public CustomList(Activity context,
ArrayList<HashMap<String, String>> songList) {
super(context, R.layout.list_item_view, songList);
this.context = context;
this.songList = songList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_item_view, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.list_image);
TextView txtArtist = (TextView) rowView.findViewById(R.id.artist);
TextView txtDuration = (TextView) rowView.findViewById(R.id.duration);
System.out.println(" title ** "+songList.get(position).get("song_title")+" duration **
"+songList.get(position).get("song_duration")
+" thumb ** "+songList.get(position).get("song_thumbnail")+" language **
"+songList.get(position).get("song_language"));
txtArtist.setText(songList.get(position).get("song_title"));
txtDuration.setText(songList.get(position).get("song_duration"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
imageView.setImageBitmap(BitmapFactory.decodeFile(defaultFilePath));
imageView.setImageURI(uri);
txtTitle.setText(songList.get(position).get("song_language"));
return rowView;
}
}
Any help would be appreciated...
//Fetching Data from server in josn
getRequest();
gAdapter = new BaseAdapter(HomeJsonActivity.this, defaultSongsDetailList);;
list = (ListView) findViewById(R.id.list);
gAdapter.notifyDataSetChanged();
list.setAdapter(gAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
private void getRequest() {
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
Log.d("Get top called", "try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if (response != null) {
try {
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
defaultSongsDetails = new HashMap<String, String>();
String title, artist, language, imageUrl, songUrl, vocalUrl, duration = null;
String sdCardPathOfImage, sdCardPathOfOriginalSong, sdCardPathOfVocalSong = null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title", title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist", artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language", language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration", duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail = null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName = null;
int cut = songUrl.lastIndexOf('/');
if (cut != -1) {
fileName = songUrl.substring(cut + 1);
}
sdCardPathOfOriginalSong = basepath + "/songs/" + fileName;
defaultSongsDetails.put("song_original_path", sdCardPathOfOriginalSong);
String vocalFileName = null;
int cutVocal = songUrl.lastIndexOf('/');
if (cut != -1) {
vocalFileName = songUrl.substring(cutVocal + 1);
}
sdCardPathOfVocalSong = basepath + "/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
defaultSongsDetailList.add(defaultSongsDetails);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
trd.start();
}
//Custom Base Adapter Class
public class BaseAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<HashMap<String, String>> songList;
public BaseAdapter(Context context, ArrayList<HashMap<String, String>> list) {
this.mInflater = LayoutInflater.from(context);
this.songList = list;
for (HashMap hh : songList) {
System.out.println("**** hh ***" + hh);
}
}
#Override
public int getCount() {
return songList.size();
}
#Override
public Object getItem(int position) {
return songList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
ViewHolder holder;
if (convertView == null) {
rowView = mInflater.inflate(R.layout.list_item_view, parent, false);
holder = new ViewHolder();
holder.title = (TextView) rowView.findViewById(R.id.title);
holder.thumb = (ImageView) rowView.findViewById(R.id.list_image);
holder.artist = (TextView) rowView.findViewById(R.id.artist);
holder.duration = (TextView) rowView.findViewById(R.id.duration);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = (ViewHolder) rowView.getTag();
}
holder.title.setText(songList.get(position).get("song_title"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
holder.thumb.setImageURI(uri);
holder.artist.setText(songList.get(position).get("song_artist"));
holder.duration.setText(songList.get(position).get("song_duration"));
System.out.println(" title ** " + songList.get(position).get("song_title") + " duration ** " + songList.get(position).get("song_duration")
+ " thumb ** " + songList.get(position).get("song_thumbnail") + " language ** " + songList.get(position).get("song_language"));
return rowView;
}
private class ViewHolder {
public ImageView thumb;
public TextView title, duration, artist;
}
}

GetView method from ArrayAdapter getting called onScroll up and down

I have a Custom ArrayAdapter that has a getview method, the thing is that method is being called for different views if i scroll down and up, and this make this views load again (e.g. downloading an image).
In my ListActivity class, i only call adapter = new Adapter... and list.setAdapter() , after i download and parse a json (im using AQuery library).
public class AdapterPostagem extends ArrayAdapter<Postagem>{
Context context;
LayoutInflater inflater;
boolean memCache = false;
boolean fileCache = true;
String BASE_URL = "https://graph.facebook.com/";
public AdapterPostagem(Context context, int textViewResourceId,
List<Postagem> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public class ViewHolder{
TextView postagem;
TextView likes;
ImageView foto;
View view;
TextView like;
TextView share;
ProgressBar pb;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
Postagem p = new Postagem();
p = getItem(position);
AQuery aq;
UrlImageViewHelper uHelper = new UrlImageViewHelper();
uHelper.setUseBitmapScaling(false);
if (convertView == null){
convertView = inflater.inflate(R.layout.postagem, parent, false);
Log.d("conv", "convertView_null");
Postagens posts = new Postagens();
Postagens.EndlessScrollListener end = posts.new EndlessScrollListener();
aq = new AQuery(convertView);
aq.scrolled(end);
holder = new ViewHolder();
holder.foto = (ImageView)convertView.findViewById(R.id.foto);
holder.postagem = (TextView)convertView.findViewById(R.id.postagem);
holder.like = (TextView)convertView.findViewById(R.id.likes);
holder.share = (TextView)convertView.findViewById(R.id.shares);
//holder.pb = (ProgressBar)convertView.findViewById(R.id.progress);
if (!p.getUrl_foto().equals("")){
getUrlPhoto(holder.foto, uHelper,p.getId(), aq, R.id.foto);
}else{
holder.foto.setVisibility(View.GONE);
}
holder.postagem.setText(p.getPostagem());
convertView.setTag(holder);
}else{
Log.d("conv", "convertView");
holder = (ViewHolder)convertView.getTag();
Postagens posts = new Postagens();
Postagens.EndlessScrollListener end = posts.new EndlessScrollListener();
aq = new AQuery(convertView);
aq.scrolled(end);
holder.foto = (ImageView)convertView.findViewById(R.id.foto);
holder.postagem = (TextView)convertView.findViewById(R.id.postagem);
if (!p.getId().equals("")){
getUrlPhoto(holder.foto, uHelper,p.getId(), aq, R.id.foto);
}else{
holder.foto.setVisibility(View.GONE);
}
//uHelper.setUrlDrawable(holder.foto, p.getUrl_foto());
setTextWithURL(holder.postagem, p.getPostagem());
//holder.postagem.setText(p.getPostagem());
//holder.likes.setText(Integer.toString(p.getLikes()));
}
return convertView;
}
public void setTextWithURL(TextView t, String s){
String [] parts = s.split("\\s");
String finals = "";
for( String item : parts ) try {
URL url = new URL(item);
// If possible then replace with anchor...
finals = finals + (""+ url + " " );
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
finals = finals + item + " ";
System.out.print( item + " " );
}
t.setClickable(true);
t.setPaintFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
t.setMovementMethod(LinkMovementMethod.getInstance());
t.setText(Html.fromHtml(finals));
}
public void setPhoto(ImageView img, UrlImageViewHelper uHelper, AQuery aq, JSONObject json, int id){
String URL = "";
try {
URL = json.getJSONArray("images").getJSONObject(1).getString("source");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//uHelper.setUrlDrawable(img, URL);
// File file = aq.getCachedFile(URL);
// Bitmap bp = BitmapFactory.decodeFile(file.getPath());
// if (bp != null){
//
// img.setImageBitmap(bp);
//
// }else{
aq.id(img).image(URL, memCache, fileCache, 0, 0, null, 0, AQuery.RATIO_PRESERVE);
//
// }
}
public void getUrlPhoto(final ImageView img, final UrlImageViewHelper uHelper, String id, final AQuery aq, final int id_photo){
aq.ajax(BASE_URL + id, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Log.d("url", url);
if(json != null){
setPhoto( img, uHelper, aq, json, id_photo);
}else{
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
}
}

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

Saving Android Preferences

Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}
In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)

Categories

Resources