i have EditText in second activity.so the value enter here will be added to the custom listview in first activity.
i first activity in list i have textview,checkbox and button(edit). here textview will be from second activity edittext data. so here if i click on edit then it navigates to second activity of that particular data .am getting all these now .. in second acitity i want to edit the textfield value .so it has to display the edited value with this data in listview of particular row.
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
String cardNumberData=null;
}
public class Second extends Activity{
EditText cardNumber;
String cardNumberReceived;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.editcredit);
cardNumberReceived = getIntent().getStringExtra("cardwithoutstring");
System.out.println("cardWithOutStringReceived"+cardNumberReceived);
app = ((MyApplication) getApplicationContext());
cardNumber =(EditText)findViewById(R.id.cardnumber);
cardNumber.setText(cardNumberReceived);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.cardNumberData =cardNumber.getText().toString();
System.out.println("Gotcardname"+app.cardNumberData);
app.arryList.add(app.cardNumberData);
System.out.println("Array List Size "+app.arryList.size());
System.out.println("Array List Size "+app.cardTypeList.size());
Intent saveIntent =new Intent(Second.this,First.class);
startActivity(saveIntent);
}
});
}
}
public class First extends Activity{
protected ListItemsState[] mDeletedItemsStates;
protected ArrayAdapter<ListItemsState> mListAdapter;
protected ListView mFoldersListView;
protected Context mContext;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
mDeletedItemsStates = (ListItemsState[])getLastNonConfigurationInstance();
if (mDeletedItemsStates == null) {
mDeletedItemsStates = new ListItemsState[app.arryList.size()];
for (int i = 0; i < app.arryList.size(); i++) {
mDeletedItemsStates[i] = new ListItemsState(app.arryList.get(i),i);
}
}
ArrayList<ListItemsState> gridItemsList = new ArrayList<ListItemsState>();
gridItemsList.addAll(Arrays.asList(mDeletedItemsStates));
mListAdapter = new DeletedItemsStateArrayAdapter(this, gridItemsList);
mFoldersListView.setAdapter(mListAdapter);
mFoldersListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mFoldersListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "am thelist",
Toast.LENGTH_LONG).show();
}
});
}
private static class ListItemsState {
private String produ = "";
private boolean checked = false;
private int position;
public ListItemsState(String produ, int position) {
this.position = position;
}
public String getProdu() {
return produ;
}
public int getPosition() {
return position;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
/** Holds child views for one row. */
private static class ListItemsStateViewHolder {
private RadioButton checkBox;
private TextView produ;
private Button edit;
public TextView getProdu() {
return produ;
}
public Button getEdit() {
return edit;
}
public RadioButton getCheckBox() {
return checkBox;
}
}
private class DeletedItemsStateArrayAdapter extends
ArrayAdapter<ListItemsState> {
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private LayoutInflater inflater;
public DeletedItemsStateArrayAdapter(Context context,
List<ListItemsState> sentItemsStateList) {
super(context, R.layout.customlist, R.id.card,
sentItemsStateList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ListItemsState deletedItemsState = (ListItemsState) this
.getItem(position);
ListItemsStateViewHolder viewHolder = new ListItemsStateViewHolder();
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.customlist, null);
convertView.setTag(new ListItemsStateViewHolder());
}
else {
viewHolder = (ListItemsStateViewHolder) convertView.getTag();
viewHolder.checkBox = viewHolder.getCheckBox();
viewHolder.produ = viewHolder.getProdu();
viewHolder.edit = viewHolder.getEdit();
}
viewHolder.produ = (TextView) convertView.findViewById(R.id.card);
viewHolder.checkBox = (RadioButton) convertView.findViewById(R.id.radioButton1);
viewHolder.edit=(Button)convertView.findViewById(R.id.editbutton);
try {
viewHolder.checkBox.setTag(deletedItemsState);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
viewHolder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent edit =new Intent(getApplicationContext(), Second.class);
edit.putExtra("cardNumberSending",app.arryList.get(position));
edit.putExtra("Indexvalue",mFoldersListView.getItemIdAtPosition(position));
System.out.println("Index value ::::::::: "+mFoldersListView.getItemIdAtPosition(position));
startActivity(edit);
}
});
viewHolder.produ.setText(deletedItemsState.getProdu());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return mDeletedItemsStates;
}
}
You are adding the edited data to the ArrayList Again avoid it inside the Second Activity
app.cardNumberData = cardNumber.getText().toString();
if(arryList.indexOf(cardNumberReceived) != -1)
{
app.arryList.set(arryList.indexOf(cardNumberReceived), app.cardNumberData);
}else
{
app.arryList.add(app.cardNumberData);
}
In your second Activity do this onClick of save.
Related
I have three fragments, the second and the third one, have a listView in their respective layout.
initially, the listView of both "second and third Frament", is populated with the same items. i other words, initially the the listView of
the second fragment and the third one, contain the following where CB: is checkBox and IV: is ImageView and t is: textview, and SaveButton is a buton
t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton
what i am trying to do is, while i am in the second fragment and selected an item(s) from the listView "using the checkbox" and clicked "Save" button, then, that item i selected, should be deleted from the listView in the third Fragment.
to achieve this,in getview(), i checked if the the checkBox is checked from the the listView of the second fragment, and if it is checked, i add the checked items
to a list. as shown in getView():
Second Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, ECO_FRAG_ID);
this.listView.setAdapter(adapter);
}
Third Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
BaseAdapter:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}
if (this.checkedItemsList1 == null) {
this.checkedItemsList1 = new ArrayList<String>();
}
if (this.checkedItemsList2 == null) {
this.checkedItemsList2 = new ArrayList<String>();
}
final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);
tv.setText(this.topicsList.get(position));
if (cb.isChecked() && (this.id == 1) ) {
this.checkedItemsList1.add(this.topicsList.get(position));
this.setCheckedItemsList1(this.checkedItemsList1);
}
if (cb.isChecked() && (this.id == 2) ) {
this.checkedItemsList2.add(this.topicsList.get(position));
this.setCheckedItemsList2(this.checkedItemsList2);
}
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);
topicsList.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
And i created an interface, which is initialised in onAttach() and called when i click the savebuton in the secondFragment as folows:
private OnClickListener btnSaveListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Save to SQLite", Toast.LENGTH_SHORT).show();
Log.d(TAG, "size: " + adapter.getCheckedItemsList1().size());
iCSC.onCheckedStateChanged(adapter.checkedItemsList1, ECO_FRAG_ID);
}
};
this inerface, the mainActivity implements it, and in the implemntation of the interface, i pass the list f the checked items from the second Fragment to the third
Fragment through a public method in the third fragmet that updates the list and then assign the list to the adapter, as follows:
#Override
public void onCheckedStateChanged(ArrayList<String> list, int id) {
// TODO Auto-generated method stub
switch (id) {
case 1:
((Logger_Settings_Frag) this.fragList.get(2)).updateTopicList(list);
break;
case 2:
break;
}
}
**updateTopicList in the third fragment**
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
updateTopicList in the third fragment
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
when i run that code, in the saveButton listener of the second fragment, the log.d message displays that the size of the list that should contain the items that was checked, is zero size?!
please have a look at the code and let me know what i am missing?
try this: Its a sample Project OneActivity with two Fragments:
public ArrayList myBeansList_frgnt1;
public ArrayList myBeansList_frgnt2;
by clicking the save button iterate the myBeansList_frgnt1 and checking the condition that any item is selected or not. if item is selected i am adding that item to myBeansList_frgnt2 .showing in fragment2.
MainActivity:
public class MainActivity extends FragmentActivity {
private FragmentManager mFragmentManager;
private MyFragment1 myFragment1;
public ArrayList<MyBean> myBeansList_frgnt1;
public ArrayList<MyBean> myBeansList_frgnt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
myBeansList_frgnt1 = new ArrayList<MyBean>();
myBeansList_frgnt2 = new ArrayList<MyBean>();
}
#Override
protected void onResume() {
super.onResume();
myFragment1 = new MyFragment1();
FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
mTransaction.replace(R.id.framid, myFragment1, "applock").commit();
}
}
MyBaseAdpter: maintaining the states in the MyBean object
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder.mTextView = (TextView) view.findViewById(R.id.textView1);
holder.mBox = (CheckBox) view.findViewById(R.id.checkBox1);
holder.mImageView = (ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final MyBean mBean = mBeansList.get(position);
holder.mBox.setOnCheckedChangeListener(null);
holder.mBox.setChecked(mBean.isChecked());
holder.mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBean.setChecked(true);
} else {
mBean.setChecked(false);
}
}
});
// setting text and image
holder.mTextView.setText(mBean.getmName());
holder.mImageView.setImageResource(mBean.getmImgId());
return view;
}
private class ViewHolder {
TextView mTextView;
CheckBox mBox;
ImageView mImageView;
}
Fragment1:
public class MyFragment1 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
private Button mButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
mButton = (Button) view.findViewById(R.id.bttnid);
return view;
}
#Override
public void onResume() {
super.onResume();
final MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt1, getActivity());
mListView.setAdapter(myBaseAdpter);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int size = mActivity.myBeansList_frgnt1.size();
for (int i = 0; i < size; i++) {
MyBean mMyBean = mActivity.myBeansList_frgnt1.get(i);
if (mMyBean.isChecked()) {
mActivity.myBeansList_frgnt2.add(mMyBean);
}
}
}
});
}
}
Fragment2:
public class MyFragment2 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
return view;
}
#Override
public void onResume() {
super.onResume();
MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt2, getActivity());
mListView.setAdapter(myBaseAdpter);
}
}
MyBean:
public class MyBean {
private String mName;
private int mImgId;
private boolean isChecked;
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getmImgId() {
return mImgId;
}
public void setmImgId(int mImgId) {
this.mImgId = mImgId;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public MyBean() {
super();
// TODO Auto-generated constructor stub
}
}
The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,
I am working on the quiz application.For that I am using listview for the dispaly the answers options, I want to change the listview background color when user select the listview item, If answer is correct then set the green background and wrong then set red background
I am tring so much, but i don,t get the solution.
Adapter class
public class ListviewAdapter extends BaseAdapter{
public List<String> Questions;
public Activity context;
public LayoutInflater inflater;
private int[] colors = new int[] { 0x30505050, 0x30808080 };
private String[] opt_no;
public static View change_color;
public ListviewAdapter(Activity context,List<String> answers, String[] que_opt_no) {
super();
this.context = context;
this.Questions = answers;
this.opt_no = que_opt_no;
//this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Questions.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return Questions.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtquestion;
TextView txtquestion_no;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
// this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String fontPath = "fonts/Face Your Fears.ttf";
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.quiz_questions_listitem, null);
holder.txtquestion = (TextView) convertView.findViewById(R.id.textView_option);
holder.txtquestion_no = (TextView) convertView.findViewById(R.id.textView_option_no);
// holder.txtquestion .setTypeface(Typeface.createFromAsset(convertView.getContext().getAssets(),fontPath));
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
/* int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]); */
change_color = convertView;
// convertView.setBackgroundResource(R.drawable.listview_background);
holder.txtquestion.setText(Questions.get(position));
holder.txtquestion_no.setText(opt_no[position]);
return convertView;
}
/*public static void setbackground(){
String answer = SelectedAnswer.getAnswer();
if (Display_questions.currentQ.getAnswer().trim().equals(answer.trim()))
{
Toast.makeText(change_color.getContext(), "red",Toast.LENGTH_SHORT).show();
change_color.setBackgroundResource(R.drawable.listview_background);
//ListviewAdapter.change_color.setBackgroundResource(R.drawable.listview_background);
//Display_questions.currentGame.incrementRightAnswers();
}
else{
Toast.makeText(change_color.getContext(), "Blue",Toast.LENGTH_SHORT).show();
change_color.setBackgroundResource(R.drawable.listview_false_background);
//Display_questions.currentGame.incrementWrongAnswers();
}
}*/
}
Java class
public class Display_questions extends Activity{
public static Question currentQ;
public static GamePlay currentGame;
ListView listview;
ListviewAdapter adapter;
String que_opt_no[] = {"a) ","b)","c) ","d) "};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_questions);
listview = (ListView) findViewById(R.id.questions_list);
listview.setItemsCanFocus(false);
GoToNextQuestion();
}
private void GoToNextQuestion() {
// TODO Auto-generated method stub
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
String selectedFromList = (String) listview.getItemAtPosition(pos);
SelectedAnswer.setAnswer(selectedFromList);
if (!checkAnswer(pos)) return;
if (currentGame.isGameOver()){
Intent i = new Intent(Display_questions.this, Display_result.class);
i.putExtra("Timer_Value", TimerTime);
startActivity(i);
finish();
}
else{
GoToNextQuestion();
}
}
});
setQuestions();
}
private void setQuestions() {
// set the question text from current question
String question = currentQ.getQuestion().trim();
TextView qText = (TextView) findViewById(R.id.txt_questions);
qText.setText(question);
// set the available options
List<String> answers = currentQ.getQuestionOptions();
adapter = new ListviewAdapter(this,answers,que_opt_no);
listview.setAdapter(adapter);
}
static boolean checkAnswer(int selectedPosition) {
String answer = SelectedAnswer.getAnswer();
if (answer==null){
return false;
}
else {
AnswerStates state = AnswerStates.NONE;
if (currentQ.getAnswer().trim().equals(answer.trim()))
{
//listview.setBackgroundResource(R.drawable.listview_background);
currentGame.incrementRightAnswers();
state = AnswerStates.RIGHT;
}
else{
//ListviewAdapter.setbackground();
currentGame.incrementWrongAnswers();
state = AnswerStates.WRONG;
}
adapter.setSelectedAnswerState(selectedPosition, state);
adapter.notifyDataSetChanged();
return true;
}
}
}
Edit :
check My images :
1.)
2.)
Do you want to change the background of listview or the selected item when a correct answer is selected.
#Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
String selectedFromList = (String) listview.getItemAtPosition(pos);
if(selectedFromList.equals("your_answer")) {
// to change the listview background
listview.setBackgroundColor(getResources().getColor(R.color.your_color_id));
// to change the selected item background color
myView.setBackgroundColor(getResources().getColor(R.color.your_color_id));
}
I would suggest to go with the following way:
Adapter class:
add storing of selected position and its state (CORRECT/INCORRECT) or color, e.g.:
public class ListviewAdapter extends BaseAdapter{
enum AnswerStates {
// Colors can be provided also for bg
WRONG(R.drawable.wrong_bg),
RIGHT(R.drawable.right_bg),
NONE(R.drawable.list_item_bg);
/** Drawable id to be used for answer state */
private int mBg;
private AnswerStates(int bg) {
mBg = bg;
}
/** getter for drawabale for answer state */
int getBg() {
return mBg;
}
}
...
/** Position of selected answer */
private int mSelectedPosition = -1;
/** State of selected answer */
private AnswerStates mSelectedAnswerState = AnswerStates.NONE;
...
/** Setter for selected answer */
public void setSelectedAnswerState(int selectedPosition, AnswerStates state) {
mSelectedPosition = selectedPosition;
mSelectedAnswerState = state;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
// Your stuff
...
if (position == mSelectedPosition) {
convertView.setBackgroundResource(mSelectedAnswerState.getBg());
} else {
// use default bg
convertView.setBackgroundResource(AnswerStates.NONE.getBg());
}
return convertView;
}
...
}
And Activity class:
public class Display_questions extends Activity{
...
// Added position parameter to the function
static boolean checkAnswer(int selectedPosition) {
//getSelectedAnswer();
String answer = SelectedAnswer.getAnswer();
if (answer==null){
return false;
}
else {
AnswerStates state = AnswerStates.NONE;
if (currentQ.getAnswer().trim().equals(answer.trim()))
{
// here set the background Green color
currentGame.incrementRightAnswers();
state = AnswerStates.RIGHT;
}
else{
// here set the background red color
//ListviewAdapter.setbackground();
currentGame.incrementWrongAnswers();
state = AnswerStates.WRONG;
}
adapter.setSelectedAnswerState(selectedPosition, state);
adapter.notifyDataSetChanged();
return true;
}
}
}
This way is more reliable than another answer, because it will work even if list with answers get scrolled and views get reused by list view.
I want to select all check boxes in a listview but I'm not able to get checkbox objects from the listview. I can select a single check box but not multiple check boxes.
Your suggestion are appreciable.
Code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bir);
mainListView = (ListView) findViewById(R.id.mainListView);
selectall = (Button) findViewById(R.id.button1);
selectall.setOnClickListener(this);
save = (Button) findViewById(R.id.button2);
save.setOnClickListener(this);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
}
});
}
}
class Amphian:
private static class Amphian
{
private String name = "" ;
private boolean checked = false ;
public Amphian( String name )
{
this.name = name ;
}
public Amphian( String name, boolean checked )
{
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
#Override
public String toString() {
return name ;
}
public void toggleChecked()
{
checked = !checked ;
}
}
class AmphiansArrayAdapter:
public class AmphiansArrayAdapter extends ArrayAdapter<Amphian>
{
Integer name[] =
{
R.raw.ducks_landing_in_water,
R.raw.flicker_chicks_feeding,
R.raw.geese_honking_loud,
R.raw.geese_honking_distant,
R.raw.gold_finch,
R.raw.humming_bird_feeding,
R.raw.indigo_bunting,
R.raw.loons,
R.raw.little_blue_heron_fishing,
R.raw.pelican_chick,
R.raw.purple_martins,
R.raw.red_winged_blackbird,
R.raw.shorebirds_close,
R.raw.shorebirds_distant,
R.raw.shorebirds_misc,
R.raw.shoreseabirds,
R.raw.snow_geese_flock,
R.raw.terns,
R.raw.tufted_titmouse,
R.raw.tundra_swans,
R.raw.wood_stork_chicks,
R.raw.woodpecker_tapping
};
private final LayoutInflater inflater;
public AmphiansArrayAdapter(Context context, List<Amphian> amphianList)
{
super( context, R.layout.simplerow, R.id.rowTextView, amphianList );
inflater = LayoutInflater.from(context) ;
}
#Override
public View getView( final int position, View convertView , ViewGroup parent)
{
final Amphian amphian=this.getItem(position);
mp=new MediaPlayer();
if ( convertView == null )
{
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById( R.id.rowTextView );
checkBox = (CheckBox) convertView.findViewById( R.id.checkBox1 );
button = (Button)convertView.findViewById(R.id.button1);
// Optimization: Tag the row with it's child views, so we don't have to
// call findViewById() later when we reuse the row.
convertView.setTag( new AmphianViewHolder(textView,checkBox,button) );
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cb= (CheckBox) v;
Log.e("cb",String.valueOf(cb));
Amphian amphian = (Amphian) cb.getTag();
Log.e("cb",String.valueOf(cb.getTag()));
amphian.setChecked(cb.isChecked());
Log.e("dd", "ddd");
}
});
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Button bu=(Button)v;
Amphian amphian;
//= (Amphian) bu.getTag();
//Log.e(String.valueOf(amphian),"ddd");
Try this.
public class MainActivity extends Activity implements OnClickListener {
public class LVSample3Adapter extends BaseAdapter{
private Context context;
private List<LVSample3Item> itemList;
public LVSample3Adapter(List<LVSample3Item> lstItems,
MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.context=mainActivity;
this.itemList=lstItems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("lstItems1:", String.valueOf(position));
LVSample3Item item = itemList.get(position);
convertView =LayoutInflater.from(context).inflate(R.layout.list, parent, false);
TextView t1=(TextView)convertView.findViewById(R.id.textView1);
t1.setText(item.getTitle());
CheckBox chb1=(CheckBox)convertView.findViewById(R.id.checkBox1);
chb1.setChecked(item.getstate());
return convertView;
}
}
/** Called when the activity is first created. */
private ListView lv;
private ListAdapter adapter;
private Button btn1,btn2;
private List<LVSample3Item> lstItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
lstItems = new ArrayList<LVSample3Item>();
LVSample3Item item = new LVSample3Item("drinks",false);
lstItems.add(item);
item = new LVSample3Item("chat",false);
lstItems.add(item);
item = new LVSample3Item("chat1",true);
lstItems.add(item);
item = new LVSample3Item("chat2",false);
lstItems.add(item);
adapter = new LVSample3Adapter(lstItems, this);
lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.button1){
Log.e("lstItems:", String.valueOf(lstItems.size()));
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(!item.getstate()){
item.setpath(true);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}else if(v.getId()==R.id.button2){
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(item.getstate()){
item.setpath(false);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
public class LVSample3Item implements Serializable {
private String title;
private boolean state;
public LVSample3Item(String title,boolean imagepath) {
this.title = title;
this.state=imagepath;
}
public String getTitle() {
return title;
}
public boolean getstate() {
return state;
}
public void setTitle(String title) {
this.title = title;
}
public void setpath(boolean imagepath) {
this.state = imagepath;
}
}
There is too much code to read, so I give you a sample how to do that:
int count = list.getCount();
for (int i = 0; i < count; i++) {
View child = list.getItemAtPosition(i);
//check that child..
}
or
int count = list.getChildCount();
for (int i = 0; i < count; i++) {
View child = list.getChildAt(i);
//check that child..
}
selectall.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
list.getItem(i).setChecked(true);
}
}
});
try doing soething like this
Problem : in Listview swaps text inside of EditText. it happen when keyboard invisible or visible. as shown in below images.
Code : ListView Activity Class :
public class DayPlannerFormActivity extends Activity {
private TextView txtHeader;
private Context mContext;
private ListView lvDayplannerFrom;
private FormDayPlannerAdapter adapter;
private Activity activity;
final Handler mHandler = new Handler();
private Vector<DayPlannerForm> list = new Vector<DayPlannerForm>();
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dayplanner);
mContext = this;
activity = this;
txtHeader = (TextView) findViewById(R.id.txtHeader);
txtHeader.setText(R.string.haivlate);
lvDayplannerFrom = (ListView) findViewById(R.id.lvDayplanner);
startfetchOperation();
}
private void updateResultsInUi() {
adapter= new FormDayPlannerAdapter(activity,list);
lvDayplannerFrom.setAdapter(adapter);
}
protected void startfetchOperation() {
Thread t = new Thread() {
#Override
public void run() {
getData();
}
};
t.start();
}
private void getData() {
try{
list.clear();
DayPlannerForm dpf = new DayPlannerForm("Task Name 1","","");
list.add(dpf);
dpf =new DayPlannerForm("Task Name 2","","");
list.add(dpf);
mHandler.post(mUpdateResults);
} catch (Exception e){
mHandler.post(mUpdateResults);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try{
if(lvDayplannerFrom != null)
lvDayplannerFrom.setAdapter(null);
} catch (Exception e){}
}
}
Code : List View Adapter Class
public class FormDayPlannerAdapter extends BaseAdapter {
private Activity mActivity;
private static Vector<DayPlannerForm> list;
private static LayoutInflater inflater;
private Context mContext;
public FormDayPlannerAdapter ( Activity _activity,Vector<DayPlannerForm> _list) {
mActivity = _activity;
mContext = _activity;
list = _list;
inflater = (LayoutInflater)mActivity.getSystemService(mActivity.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder{
public TextView txtTaskName;
public CheckBox chbAction;
public EditText edtDecription;
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.dayplanner_listitem_form, null);
holder=new ViewHolder();
holder.txtTaskName=(TextView)vi.findViewById(R.id.txtTaskName);
holder.chbAction = (CheckBox) vi.findViewById(R.id.chbAction);
holder.edtDecription = (EditText) vi.findViewById(R.id.edtDecription);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.txtTaskName.setText(list.get(position).getTaskName());
return vi;
}
}
How to resolve this problem
Problem solve bye Adding android:windowSoftInputMode="adjustPan" this attribute in activity tag in the manifest.xml
On first look i think that problem occurring by the the following code:-
DayPlannerForm dpf = new DayPlannerForm("Task Name 1","","");
list.add(dpf);
dpf =new DayPlannerForm("Task Name 2","","");
list.add(dpf);
You should take different objects of DayPlannerForm Class for each Task Name.
DayPlannerForm dpf1,dpf2;
dpf1 = new DayPlannerForm("Task Name 1","","");
list.add(dpf1);
dpf2 =new DayPlannerForm("Task Name 2","","");
list.add(dpf2);
I think this might solve your problem.