Here is my main class and Adapter together
public class MainActivity extends Activity {
public MyAdapter adapter;
private View view;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
public SharedPreferences preferences;
public SharedPreferences.Editor editor;
int [] btnNums={66,150,94,72,206,489,1481,731,131,91,145,137,662,770};
int [] tuesdaynum={351,14,308,19,134,514,305,68,104,129,62,47,409,630};
int [] wednesdaynum={744,131,184,846,37,336,812,88,1020,1286,1106,551,202,156};
int [] thursdaynum={206,662,731,1281,801,351,117,770,302,526,212,1100,1060,1100};
int [] fridaynum={232,998,209,80,73,270,312,55,110,78,209,114,161,1001};
int [] saturdaynum={20,48,573,319,108,66,116,500,46,68,286,201,256,113};
int [] sundaynum={137,148,56,124,68,490,18,156,14,48,20,86,514,298};
int [] btnNumsrefs={66,150,94,72,206,489,1481,731,131,91,145,137,662,770};
int yesterday;
public void storeYesterday(Calendar a){
yesterday=a.get(Calendar.DAY_OF_MONTH);
preferences=getSharedPreferences("yesterday",0);
editor=preferences.edit();
editor.putInt("yesterday",yesterday);
editor.commit();
}
public Integer getFromYesterday(){
preferences=getSharedPreferences("yesterday",0);
int get =preferences.getInt("yesterday", 0);
return get;
}
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14};
int[] tuesday = {R.drawable.elkahhar, R.drawable.elvehhab, R.drawable.errezzak, R.drawable.elvahid, R.drawable.essamed, R.drawable.elkabid, R.drawable.elkadir, R.drawable.elhakem, R.drawable.eladl,
R.drawable.ellatif, R.drawable.elbatin, R.drawable.elvali, R.drawable.ettevvab, R.drawable.elmuntekim};
int[] wednesday = {R.drawable.elmuktedir, R.drawable.esselam, R.drawable.elmukaddim, R.drawable.elmuaahir, R.drawable.elevvel, R.drawable.elmusavvir, R.drawable.elhabir, R.drawable.elhalim, R.drawable.elazim,
R.drawable.elgafur, R.drawable.ezzahir, R.drawable.elmuteali, R.drawable.elberr, R.drawable.elafuv };
int[] thursday = {R.drawable.elcebbar, R.drawable.elmutekebbir2, R.drawable.elhaliik, R.drawable.elgafffar, R.drawable.ellahir, R.drawable.errafi, R.drawable.elmuiz, R.drawable.elmuzil, R.drawable.elbasir,
R.drawable.essekur, R.drawable.malikulmulk, R.drawable.zulcelalilikram, R.drawable.elganiy, R.drawable.elmugni };
int[] friday = {R.drawable.elkebir, R.drawable.elhafiz, R.drawable.elmukit, R.drawable.elhasib, R.drawable.elcelil, R.drawable.elkerim, R.drawable.elrakib, R.drawable.elmucib, R.drawable.elaliy,
R.drawable.elhakim, R.drawable.elmuksit, R.drawable.elcami, R.drawable.elmani, R.drawable.eddar};
int[] saturday = {R.drawable.elvedud, R.drawable.elmecid, R.drawable.elbais, R.drawable.essehid, R.drawable.elhak, R.drawable.elvekil, R.drawable.elkaviy, R.drawable.elmetin, R.drawable.elveliy,
R.drawable.elhamid, R.drawable.errauf, R.drawable.ennafi, R.drawable.ennur, R.drawable.elbaki};
int[] sunday = {R.drawable.elvasi, R.drawable.elmuhsi, R.drawable.elmubdi, R.drawable.elmuid, R.drawable.elmuhyi, R.drawable.elmumit, R.drawable.elhay, R.drawable.elkayyum, R.drawable.elvacid,
R.drawable.elmacid, R.drawable.elhadi, R.drawable.elbedi, R.drawable.erresid, R.drawable.essabur };
String[] exp;
String[] exp2;
String[] exp3;
String[] exp4;
String[] exp5;
String[] exp6;
String[] exp7;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
view=getWindow().getDecorView().getRootView();
Admob.createLoadBanner(getApplicationContext(), view);
Admob.createLoadInterstitial(getApplicationContext(), null);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
exp2= res.getStringArray(R.array.faz2);
exp3= res.getStringArray(R.array.faz3);
exp4= res.getStringArray(R.array.faz4);
exp5= res.getStringArray(R.array.faz5);
exp6= res.getStringArray(R.array.faz6);
exp7= res.getStringArray(R.array.faz7);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
Calendar cal2=Calendar.getInstance();
cal2.setTime(new Date());
int today = cal.get(Calendar.DAY_OF_MONTH);
if(today==Calendar.Monday){
adapter.setData(this,exp3,thursday,mean,thursdaynum);
}else if(today==Calendar.TUESDAY){
adapter.clear();
adapter=new MyAdapter(this,exp2,tuesday,mean,tuesdaynum);
}//goes on
if(getFromYesterday()==null){
storeYesterday(cal);
}else {
if(today!=getFromYesterday()) {
storeYesterday(cal);
adapter = new MyAdapter(this, exp, images, mean, t);
storeYesterday(cal);
edit.putInt("Count", btnNumsrefs.length);
int count = 0;
for (int i : btnNums) {
edit.putInt("IntValue_" + count++, i);
}
}
edit.commit();
}
int[] ret;
Integer count1 = prefs.getInt("Count", 0);
if(count1!=null) {
ret = new int[count1];
for (int i = 0; i < count1; i++) {
ret[i] = prefs.getInt("IntValue_" + i, i);
t=ret;
}
}
if(t!=null)
{
adapter = new MyAdapter(this, exp, images, mean, t);
}else
{
adapter = new MyAdapter(this, exp, images, mean, btnNums);
}
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<14;i++){
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + ma.t[position]);
}
// button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<14;i++){
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + btnNums[position]);
}
// button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i <14; i++) {
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + temp[position]);
}
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
In my app, I use custom list view with different datas. these datas come from arrays , I want to send new arrays via constructor to my adapter by checking date but it doesn't work .
after these codes I used these lines
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Please help I am stucked.
Why don't you create a setData() method in your adapter where you're clearing the current data and setting the new one and then call the notifyDataSetChanged method.
This way you will not create and set the same adapter multiple times when you want to change the data.
I have a shared preference in my Custom list view. I am using it to keep numbers on the button but I have a condition where the row disappears when the button becomes 0 but when I scroll down it returns to its old form and becomes visible to it's user again. Is it possible to apply the same logic for view in SharedPreference like to keep last situation?
My code is the following:
import static android.view.View.INVISIBLE;
public class MainActivity extends Activity {
public MyAdapter adapter;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
int [] btnNums={100,150,94,72,206,489,1481,731,131,91,145,137,662,770,196,351,258,131,180,1281};
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14, R.drawable.a15, R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19, R.drawable.a20, R.drawable.a21};
String[] exp;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
//
// edit.putInt("Count", btnNums.length);
// int count = 0;
// for (int i: btnNums){
// edit.putInt("IntValue_" + count++, i);
// }
// edit.commit();
//
int[] ret;
int count1 = prefs.getInt("Count", 0);
ret = new int[count1];
for (int i = 0; i < count1; i++){
ret[i] =prefs.getInt("IntValue_"+ i, i);
}
t=ret;
if(t!=null)
{
adapter=new MyAdapter(this,exp,images,mean,t);
}else
{
adapter=new MyAdapter(this,exp,images,mean,btnNums);
}
list.setAdapter(adapter);
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<21;i++){
button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<21;i++){
button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
if (btnNums[position] == 0) {
button.setEnabled(false);
button.setVisibility(INVISIBLE);
row.setVisibility(INVISIBLE);
}
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i < 21; i++) {
button.setText("" + temp[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public void storeIntArray(int[] array){
ma.edit.putInt("Count", array.length);
int count = 0;
for (int i: array){
ma.edit.putInt("IntValue_" + count++, i);
}
ma.edit.commit();
}
public int[] getFromPrefs(){
int[] ret;
int count = ma.prefs.getInt("Count", 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] =ma.prefs.getInt("IntValue_"+ i, i);
}
return ret;
}
}
First, please format your code, so its more readable.
Question: Can a Shared Preference be applied to custom ListView?
Answer: Yes it possible to use/access shared preferences in a Listview.
Upon reading your code, I believe the problem lies in your implementation of Listview and its adapter. The reason why it gets back to original state when scrolled down. Please note, that GetView is always called when scrolling.
You can refer to this topic: ListView & ViewHolder Pattern.
I created a custom ListView, and put some CheckBoxes in it.
At First, I check all the CheckBoxes and then I scroll down the ListView, then the CheckBoxes become unchecked.
What should I do?
CustomListItem.java
public class HomeListAdapter extends ArrayAdapter<HashMap<String, Object>> {
//new
//private final boolean[] mCheckedState;
// private final Context mContext;
boolean[] itemChecked;
//
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
public HomeListAdapter(Context context, ArrayList<HashMap<String, Object>> dataMap) {
super(context, 0, dataMap);
//new
itemChecked = new boolean[dataMap.size()];
// mContext = context;
//
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.com_facebook_profile_picture_blank_square)
.showImageForEmptyUri(R.drawable.com_facebook_profile_picture_blank_square)
.showImageOnFail(R.drawable.log)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20)).build();
this.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
HashMap<String, Object> dataMap = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item1, parent, false);
}
TextView description = (TextView) convertView.findViewById(R.id.description);
description.setText(dataMap.get(Home1.TAG_CNAME).toString());
TextView email = (TextView) convertView.findViewById(R.id.company);
email.setText(dataMap.get(Home1.TAG_EMAIL).toString());
final CheckBox check= (CheckBox) convertView.findViewById(R.id.ck);
//new
/*
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check.isChecked())
itemChecked[position] = true;
Toast.makeText(getContext(),itemChecked,);
else
itemChecked[position] = false;
}
});*/
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (check.isChecked())
itemChecked[position] = true;
// Toast.makeText(getContext(),itemChecked,);
else
itemChecked[position] = false;
}
});
//
if (dataMap.get(Home1.TAG_LIKE).toString().equals("true")) {
check.setChecked(true);
}else{
check.setChecked(false);
}
ImageView logo = (ImageView) convertView.findViewById(R.id.logo);
ImageLoader.getInstance().displayImage(dataMap.get(Home1.TAG_IMAGE).toString(),logo, options, animateFirstListener);
return convertView;
}
This is my Adapter Classs please help me guys to resolve this issue....
#Override
public void onCreate(Bundle savedInstanceState) {
//Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// apikey
apikey = user.get(SessionManager.KEY_api);
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ImageView back = (ImageView) findViewById(R.id.sel);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent intent = new Intent(Home1.this, Selected.class);
// finish();
// startActivity(intent);
try {
ListView lv = getListView();
ids = "";
int count = 0;
String text = "";
//CheckBox cbView;
TextView textView;
int total = lv.getCount();
for (int i = 0; i < total; i++) {
if (lv.getChildAt(i) != null) {
textView = (TextView) lv.getChildAt(i).findViewById(R.id.company);
text = textView.getText().toString();
cbView = (CheckBox) lv.getChildAt(i).findViewById(R.id.ck);
if (cbView.isChecked()) {
count += 1;
ids += text + ", ";
}
}
}
ids = ids.substring(0, ids.length()-2);
//Toast.makeText(getApplicationContext(), "Company emails: " + ids + " Total Checked: " + count, Toast.LENGTH_SHORT).show();
new DownloadOperation().execute();
}
catch(Exception ex){
System.out.println("My Message");
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
});
You can overcome this easily by using the ChoiceMode option CHOICE_MODE_MULTIPLE for the ListView as used in the API Demo -
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
EDIT
Alternate for your context-
Have an extra boolean object with your HashMap<String, Object> isChecked and initialize it to false when you populate your list.
Set your CheckBox in getView() method as-
check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked"));
Now in the listener OnCheckedChangeListener() set the value of your dataMap true or false accordingly.
I have a listactivity app , consist of 5 rows , each row contain one TEXT and 5 BUTTON , both text and buttons are clickable , text will open MyDay activity whic is textview and when you click any button it must open videoview screen .
every things run nicely except when turn mobile to landscape mode and scrolling the list it force closed and gave NullPointerException in logcat report in this line
(51) of MyArrayAdapter Class .
logcat:
java.lang.NullPointerException
at com.test.demo.MyArrayAdapter.getView(MyArrayAdapter.java:51)
Line (51) in MyArrayAdapter Class is :
holder.textView.setText(s);
any advice will be appreciated to solve that , thanks .
MyArrayAdapter Class:
public class MyArrayAdapter extends ArrayAdapter<String> {
private final String[] mClasses;
private Context mContext;
private Typeface tf;
private LayoutInflater mInflater;
private String[] mData = { "button1", "button2", "button3", "button4",
"button5" };
private int[] ids = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5 };
int[][] rowDrawables = {
{R.drawable.row_1, R.drawable.row_2, R.drawable.row_3,
R.drawable.row_4, R.drawable.row_5},
{R.drawable.row_6, R.drawable.row_7, R.drawable.row_8,
R.drawable.row_9, R.drawable.row_10},
{R.drawable.row_11, R.drawable.row_12, R.drawable.row_13,
R.drawable.row_14, R.drawable.row_15},
{R.drawable.row_16, R.drawable.row_17, R.drawable.row_18,
R.drawable.row_19, R.drawable.row_20},
{R.drawable.row_21, R.drawable.row_22, R.drawable.row_23,
R.drawable.row_24, R.drawable.row_25}};
public MyArrayAdapter(Context context, String[] classes) {
super(context, 0, classes);
mClasses = classes;
mContext = context;
tf = Typeface.createFromAsset(context.getAssets(), "BFantezy.ttf");
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null, true);
holder = new ViewHolder();
holder.textView = (TextView) convertView
.findViewById(R.id.row_label);
holder.textView.setTypeface(tf);
holder.bt1 = (Button) convertView.findViewById(R.id.button1);
holder.bt2 = (Button) convertView.findViewById(R.id.button2);
holder.bt3 = (Button) convertView.findViewById(R.id.button3);
holder.bt4 = (Button) convertView.findViewById(R.id.button4);
holder.bt5 = (Button) convertView.findViewById(R.id.button5);
} else {
holder = (ViewHolder) convertView.getTag();}
String s = mClasses[position];
holder.textView.setText(s);
int[] rowDr = rowDrawables[position];
holder.bt1.setBackgroundResource(rowDr[0]);
holder.bt2.setBackgroundResource(rowDr[1]);
holder.bt3.setBackgroundResource(rowDr[2]);
holder.bt4.setBackgroundResource(rowDr[3]);
holder.bt5.setBackgroundResource(rowDr[4]);
holder.textView.setTag(Integer.valueOf(position));
holder.textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Integer pos = (Integer) v.getTag();
Intent ourIntent = new Intent(mContext, MyDay.class);
ourIntent.putExtra("cheese", mClasses[pos]);
mContext.startActivity(ourIntent);
}
});
holder.bt1.setTag(Integer.valueOf(position));
holder.bt1.setOnClickListener(mListener);
holder.bt2.setTag(Integer.valueOf(position));
holder.bt2.setOnClickListener(mListener);
holder.bt3.setTag(Integer.valueOf(position));
holder.bt3.setOnClickListener(mListener);
holder.bt4.setTag(Integer.valueOf(position));
holder.bt4.setOnClickListener(mListener);
holder.bt5.setTag(Integer.valueOf(position));
holder.bt5.setOnClickListener(mListener);
return convertView;
}
static class ViewHolder {
TextView textView;
Button bt1, bt2, bt3, bt4, bt5;
}
private OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
Integer realPos = (Integer) v.getTag();
int video = 0;
String night = null;
for (int i = 0; i < ids.length; i++) {
if (v.getId() == ids[i]) {
video = i;
break;
}
}
Intent i = new Intent(mContext, My_videos.class);
i.putExtra("video", video);
i.putExtra("row", realPos);
mContext.startActivity(i);
}
};
}
ListButtons:
public class ListButtons extends ListActivity {
String classes[] = {"First", "Second", "Third","Fourth", "Fifth" };
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new MyArrayAdapter(this, classes)); }}
I have code for ListwithImage list. But when i try to onclickItem shows with Dialog, but Dialog shows null. I implement onclickItemListener . I tried this code without image, Dialog shows selected list. But when i try with image, it won't work.
MyCode:
public class MainActivity extends Activity {
EditText edittext;
ListView listview;
String[] text = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten" };
int[] image = { R.drawable.one, R.drawable.two, R.drawable.three,
R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven,
R.drawable.eight, R.drawable.nine, R.drawable.ten };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
edittext.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after)
{
}
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++)
{
if (textlength <= text[i].length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) text[i].subSequence(0, textlength)))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter
(text_sort, image_sort));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
// TODO Auto-generated method stub
listview.getItemAtPosition(position);
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("List");
adb.setMessage(" selected Item is="
+ listview.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
});
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
int[] data_image;
MyCustomAdapter()
{
}
MyCustomAdapter(String[] text, int[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image)
{
data_text = new String[text.size()];
data_image = new int[image.size()];
for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
your getting wrong values in Your Alert
wrong
+listview.getItemAtPosition(position));
right
adb.setMessage(" selected Item is="+text_sort.get(position).toString());
Try changing this:
adb.setMessage(" selected Item is= " + listview.getItemAtPosition(position));
To this:
adb.setMessage(" selected Item is= " + text_sort.get(position));