change color of listview row - android

Let me explain in brief.
I have 2 Fragments:
1) Fragment A where user enters some text. here i have also defined 5 buttons each of different colors. From here, the entered text is added to database.
2) Fragment B which has a listview which populates data from that database using customadapter when user click the "Save" button in Fragment A.
Everything is working fine. Data is being saved, loaded into Listview and all. Now remember those 5 buttons with 5 different colors?
What I Want is that suppose while adding data in Fragment A, user selected button with color "Orange" suppose, then the row that will be inflated in getView() method of adapter should also have its background orange.
(Something ike Google Keep)
Is that possible?
My Adapter class :
public class notesAdapter extends BaseAdapter {
ArrayList<notesSingleRow> notes;
Context context;
View convertView;
private static final String TAG = "SampleAdapter";
private final LayoutInflater mLayoutInflater;
private final Random mRandom;
private SparseBooleanArray mSelectedItemsIds;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
public notesAdapter(Context context, ArrayList<notesSingleRow> notes) {
this.notes = notes;
this.context = context;
this.mLayoutInflater = LayoutInflater.from(context);
this.mRandom = new Random();
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return notes.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
this.convertView = convertView;
ViewHolder vh;
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.notes_single_row, parent, false);
vh = new ViewHolder();
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.txtView = detail(convertView, R.id.notes_grid_text, notes.get(position).getNotes());
vh.notes_title = detail(convertView, R.id.note_title_added, notes.get(position).getNotesTitle());
int len = vh.txtView.length();
if (len == 1 || len ==2){
vh.txtView.setTextSize(100);
}
else if (len == 3){
vh.txtView.setTextSize(80);
}
else if (len == 4){
vh.txtView.setTextSize(60);
}
else if (len ==5){
vh.txtView.setTextSize(50);
}
else if (len == 8){
vh.txtView.setTextSize(60);
}
double positionHeight = getPositionRatio(position);
vh.txtView.setHeightRatio(positionHeight);
vh.notes_title.setHeightRatio(positionHeight);
vh.notes_title.setPaintFlags(vh.notes_title.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
/* if ((position == 0 || position == 5 || position == 10 || position ==15)) {
convertView.setBackgroundColor(Color.rgb(255, 112, 67));
} else if (position == 1 || position == 6 || position == 11 || position ==16) {
convertView.setBackgroundColor(Color.rgb(29, 233, 182));
} else if (position == 2 || position == 7 || position == 12 || position ==17) {
convertView.setBackgroundColor(Color.rgb(121, 134, 203));
} else if (position == 3 || position == 8 || position == 13 || position ==18) {
convertView.setBackgroundColor(Color.rgb(205, 220, 57));
} else if (position == 4 || position == 9 || position == 14 || position ==19) {
convertView.setBackgroundColor(Color.rgb(224, 64, 251));
}*/
return convertView;
}
public void changeColorToOrange() {
convertView.setBackgroundColor(Color.rgb(255, 112, 67));
}
static class ViewHolder {
DynamicHeightTextView txtView, notes_title;
}
private double getPositionRatio(final int position) {
double ratio = sPositionHeightRatios.get(position, 0.0);
if (ratio == 0) {
ratio = getRandomHeightRatio();
sPositionHeightRatios.append(position, ratio);
Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
}
return ratio;
}
private double getRandomHeightRatio() {
return (mRandom.nextDouble() / 2.4) + 0.8;
}
private DynamicHeightTextView detail(View v, int resId, String text) {
DynamicHeightTextView tv = (DynamicHeightTextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
user add text in this fragment with buttons of different colors:
public class add_note_frag extends Fragment implements View.OnClickListener {
EditText note, noteTitle;
String user_note, user_note_title;
Button svenote;
ImageView ora, vio, yel, pin;
RelativeLayout rel;
ActionBar ab;
notesAdapter adapter;
private ArrayList<notesSingleRow> notes = new ArrayList<notesSingleRow>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_notes_fragment, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
ab = getActivity().getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
rel = (RelativeLayout) getActivity().findViewById(R.id.notes_rel_lay);
note = (EditText) getActivity().findViewById(R.id.note);
noteTitle = (EditText) getActivity().findViewById(R.id.note_title);
svenote = (Button) getActivity().findViewById(R.id.savenote);
adapter = new notesAdapter(getActivity(), notes);
ora = (ImageView) getActivity().findViewById(R.id.orange);
vio = (ImageView) getActivity().findViewById(R.id.violet);
yel = (ImageView) getActivity().findViewById(R.id.yellow);
pin = (ImageView) getActivity().findViewById(R.id.pink);
ora.setOnClickListener(this);
vio.setOnClickListener(this);
yel.setOnClickListener(this);
pin.setOnClickListener(this);
svenote.setOnClickListener(this);
}
public void saveNote() {
tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
user_note = note.getText().toString();
user_note_title = noteTitle.getText().toString();
long id1 = tasksDatabaseOperations.insertNote(user_note, user_note_title);
if (id1 < 0) {
Log.e("HirakDebug", "add_task_frag failed insertData operation");
} else {
Log.d("HirakDebug", "Data sent to be inserted");
}
}
#Override
public void onClick(View v) {
if (v == svenote) {
saveNote();
goBackToNoteFrag();
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar)));
}
if (v == ora) {
rel.setBackgroundColor(getResources().getColor(R.color.orange));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.orange)));
adapter.changeColorToOrange();
}
if (v == vio) {
rel.setBackgroundColor(getResources().getColor(R.color.violet));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.violet)));
}
if (v == yel) {
rel.setBackgroundColor(getResources().getColor(R.color.yellow));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.yellow)));
}
if (v == pin) {
rel.setBackgroundColor(getResources().getColor(R.color.pinkk));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.pinkk)));
}
}
public void goBackToNoteFrag() {
notesListFrag nLF = new notesListFrag();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
ft.remove(this);
ft.replace(R.id.dynamic_content, nLF, "nLF");
ft.commit();
}
#Override
public void onDetach() {
super.onDetach();
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar)));
}

It is possible.
Pass that selected color to Fragment B on button click.
Pass that color as an argument to the adapter constructor from fragment B.
Now you know the color inside the adapter.
In getView() function of the adapter, based on the color, change the background color of the inflated view. using : view.setBackgroundColor(color);
See the sample here : https://github.com/vishalvijay/SampleColorListView

As far as I think all you have to do is to save color hex code also in your database alongwith your text. It is more simple and scaleable. when you fetch text from database, you should also fetch the color in the same ArrayList of custom objects and then in getView method of your adapter, just apply the corresponding Hex color code to your convertView.

Related

Listview add item one at a time

I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.

How to pass the background color of the clicked item in the RecyclerView to the Layout of the next activity?

I have a RecyclerView with multiple background colors of items.
I want that when i clicked an item in my recyclerView the Layout of the next activity will have the same background color of the clicked item. How can i do this in my setOnClickListener method ? thanks
This is my adapter:
public class AdapterColors extends RecyclerView.Adapter<AdapterColors.MyViewholder> {
List<Colors> listArray;
Context context;
public AdapterColors(List<Color> List,Context context){
this.listArray = List;
this.context = context;
}
#Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from ( parent.getContext ()).inflate ( R.layout.itemview,parent,false );
return new MyViewholder(view);
}
}
#Override
public void onBindViewHolder(MyViewholder holder, int position) {
Color data = listArray.get ( position );
if(position % 5 == 0){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color1));
}else if(position % 5 == 1){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color2));
}else if(position % 5 == 2){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color3));
}else if(position % 5 == 3){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color4));
}else if(position % 5 == 4){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color5));
}
holder.TextColor.setText ( data.getColor ( ) );
}
}
Pass color code via intent and next activity get value via getIntent().getStringExtra() then set backgroud color with parent view with .setBackgroudColor(Color.parse(getIntntStringExtra())).
Change your onBindViewHolder method code like this:
public void onBindViewHolder(MyViewholder holder, int position) {
Color data = listArray.get ( position );
if(position % 5 == 0){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color1));
holder.TextColor.setOnClickListener( View.OnCLickListener(){
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putInt("color_code", 0);
Intent intent = new Intent();
intent.putExtras(bundle);
startActivity(intent);
// Enter the Above code in all the below cases as well
}
}
}else if(position % 5 == 1){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color2));
}else if(position % 5 == 2){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color3));
}else if(position % 5 == 3){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color4));
}else if(position % 5 == 4){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color5));
}
holder.TextColor.setText ( data.getColor ( ) );
}
The in Next opening activity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
switch(bundle.getString("color_code")) {
case 0:
// Your code logic
break;
case 1:
// Your code logic
break;
case 2:
// Your code logic
break;
case 3:
// Your code logic
break;
case 4:
// Your code logic
break;
}
}
Try following approach which is ideal
public class AdapterColors extends RecyclerView.Adapter<AdapterColors.MyViewholder> {
List<Color> listArray;
Context context;
OnItemClickListener onItemClickListener;
public AdapterColors(List<Color> List,OnItemClickListener onItemClickListener){
this.listArray = List;
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(Color colors);
}
#Override
public void onBindViewHolder(MyViewholder holder, int position) {
Color data = listArray.get ( position );
if(position % 5 == 0){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color1));
}else if(position % 5 == 1){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color2));
}else if(position % 5 == 2){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color3));
}else if(position % 5 == 3){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color4));
}else if(position % 5 == 4){
holder.TextColor.setBackgroundColor(ContextCompat.getColor(context,R.color.color5));
}
holder.TextColor.setText ( data.getColor ( ) );
holder.TextColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(data);
}
});
}
}
In your Activity Class
AdapterColors adapterColors = new AdapterColors(yourColorList,new AdapterColors.OnItemClickListener() {
#Override
public void onItemClick(Color color) {
//Add your Activity code here
// Add color in your bundle
}
});
Try this :
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
//While passing in intent
intent.putExtra("backgroundColor",color);
Replace your "view" with your own view (recycler view parent item : ex Linear or Relative Layout )
Hope this helps !

How to show sort button on TableFixHeaders

I am using InqBarna's library for showing data in table format. I am facing issue for sort button change (ascending and descending order) when clicked on sort button on table header. Please help.
Here code snippet.
private View getHeader(int row, int column, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = activity.getLayoutInflater().inflate(R.layout.item_table_header, parent, false);
}
convertView.setBackgroundResource(column % 2 == 0 ? R.color.header_dark_gray : R.color.header_light_gray);
((TextView) convertView.findViewById(android.R.id.text1)).setText(headers[column + 1]);
imageButtons[column +1] = ((ImageButton) convertView.findViewById(R.id.sortButton));
imageButtons[column +1].setTag(headers[column + 1]);
imageButtons[column +1].setOnClickListener(onClickListener);
return convertView;
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageButton imageButton =(ImageButton)v.findViewWithTag(v.getTag());
String header = v.getTag().toString();
switch (header) {
// logic for change image
case Query.AQ_NO:
if (AQ_NO_FLAG) {
imageButton.setImageResource(R.drawable.sort_asc);
}
break;
}
}
It could help you.
This is a wrapper for InqBarna's library.
This is a code snippet of how to achieve the sorting headers. Anyway you will have to see the whole example to understand how it works.
Here you render the header view:
public class OriginalHeaderCellViewGroup extends FrameLayout
implements
TableFixHeaderAdapter.HeaderBinder<ItemSortable> {
private Context context;
public TextView textView;
public ImageView iv_order_asc, iv_order_desc;
public OriginalHeaderCellViewGroup(Context context) {
super(context);
this.context = context;
init();
}
private void init() {
LayoutInflater.from(context).inflate(R.layout.text_sotable_view_group, this, true);
textView = (TextView) findViewById(R.id.tv_text);
iv_order_asc = (ImageView) findViewById(R.id.iv_order_asc);
iv_order_desc = (ImageView) findViewById(R.id.iv_order_desc);
}
#Override
public void bindHeader(ItemSortable item, int column) {
textView.setText(item.text.toUpperCase());
drawOrderArrows(item.order);
}
private void drawOrderArrows(int order) {
iv_order_desc.setImageResource(order == -1 ? R.drawable.ic_arrow_drop_up_24dp : R.drawable.ic_arrow_drop_up_24dp_disabled);
iv_order_asc.setImageResource(order == 1 ? R.drawable.ic_arrow_drop_down_24dp : R.drawable.ic_arrow_drop_down_24dp_disabled);
}
and here you attach the listener to the table adapter and perform the sorting:
private void setListeners(final OriginalSortableTableFixHeaderAdapter adapter) {
TableFixHeaderAdapter.ClickListener<ItemSortable, OriginalHeaderCellViewGroup> clickListenerHeader = new TableFixHeaderAdapter.ClickListener<ItemSortable, OriginalHeaderCellViewGroup>() {
#Override
public void onClickItem(ItemSortable item, OriginalHeaderCellViewGroup viewGroup, int row, int column) {
updateOderIndicators(item, column, adapter);
boolean orderAsc = item.order == 1;
boolean orderSectionsAsc =firstHeader.orderSectionsAsc;
applyOrder(orderAsc, orderSectionsAsc, column, adapter);
}
};
adapter.setClickListenerHeader(clickListenerHeader);
}
private void updateOderIndicators(ItemSortable item, final int column, TableFixHeaderAdapter adapter) {
final boolean orderAsc = item.order == 1;
firstHeader.order = 0;
for (ItemSortable itemAux : header) itemAux.order = 0;
item.order = !orderAsc ? 1 : -1;
}
private void applyOrder(final boolean orderAsc, final boolean orderSectionsAsc, final int column, TableFixHeaderAdapter adapter) {
Collections.sort(body, new Comparator<NexusWithImage>() {
#Override
public int compare(NexusWithImage nexus1, NexusWithImage nexus2) {
if (nexus1.isSection() || nexus2.isSection()) return 1;
else if (orderAsc)
return nexus1.data[column + 1].compareToIgnoreCase(nexus2.data[column + 1]);
else
return nexus2.data[column + 1].compareToIgnoreCase(nexus1.data[column + 1]);
}
});
adapter.setBody(body);
}
Hope it helps you.

Android fragments and creating widgets dynamically

This is perhaps one of the simpler problems on here, but i am fairly new to android,so still having some challenges.I am downloading some data from a mysql server using JSON.-a list of questions.Each question is then created on its own fragment depending on the total number of questions.I display different widgets-edittext,radiobutton,spinner etc depending on what is specified for that question.
Problem 1
My challenge is that,i cannot seem to get the text values entered into/selected from these widgets.This works well in different activities of the application,but it is just this fragment class where i get issues.
Problem 2
I am also trying to get the positions of each question,from so that i can properly display the next/back buttons appropriately.e.g if i am at the 1st que,hide back button,if at the end,hide next and display done.something like that.My current implementation only works if i don't press button back to view a previous question.if i do,then button done is't displayed when i get to the last item,but it still shows 'next'
Problem 3
I also tried inserting checks for the input fields.e.g if user clicks next without entering anything,display toast and do not move to next item.But mine still goes to next page,and displays the toast msg "response is required"
Kindly help me see what i am doing wrong in my implementation.Thanks
My relevant code below
**fragmentStatePagerAdapter class**
public class PagerAdapter extends FragmentStatePagerAdapter {
public SQLiteDatabase db;
public PagerAdapter adapter;
Question question;
Context context2;
public PagerAdapter(Context c, FragmentManager fm) {
super(fm);
this.context2 = c;
}
#Override
public int getCount() {
System.out.println("inside get count");
return questions.size(); // get number of pages to be displayed
}
#Override
public Fragment getItem(int i) {
Log.i("at PagerAdapter", "yaaay!!At pager adapter");
Fragment fragment = null;
Question que = questions.get(i); //questions is the arraylist that has been populated with question objects from the server.
// pass value to be displayed in inflated view
fragment = new FragmentRadioButton(context2, que);
return fragment;
}
public CharSequence getPageTitle(int position) {
position++;
String s = "Question " + position;// setting the title
return s;
}
}
The Fragment class
public class FragmentRadioButton extends Fragment {
Context context3;
private Question question;
private RadioButton[] radioButton;
private RelativeLayout relativeLayout1;
static ViewPager mViewPager = FragmentStatePagerActivity.mViewPager;
private TextView question_txtView;
private RadioGroup radiogroup;
private Button btnNext;
private Spinner spinner;
private RatingBar ratingBar;
private Button btnBack;
private EditText editText;
private Button btnDone;
private TextView countRating_txt;
private RelativeLayout relativeLayout2;
private static final int radio_button = 1;
private static final int m_spinner = 2;
private static final int edit_text = 3;
private static final int rating_bar = 4;
public static ArrayList<Integer> num = new ArrayList<Integer>();
private List<RadioGroup> allRadioGroups = new ArrayList<RadioGroup>();
private List<Spinner> allSpinners = new ArrayList<Spinner>();
private List<EditText> allEds = new ArrayList<EditText>();
List<RatingBar> allRatingBars = new ArrayList<RatingBar>();
public FragmentRadioButton() {
}
public FragmentRadioButton(Context c, Question que) {
this.context3 = c;
this.question = que;
}
//#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = getActivity().getLayoutInflater().inflate(
R.layout.fragment_radio_button, null);
ScrollView scrollView = (ScrollView) view
.findViewById(R.id.scrollViewRadioButton);
relativeLayout1 = (RelativeLayout) scrollView
.findViewById(R.id.relativeLayout1);
relativeLayout2 = (RelativeLayout) relativeLayout1
.findViewById(R.id.relativeLayout2);
context3 = getActivity().getApplicationContext();
try {
question_txtView = (TextView) relativeLayout1
.findViewById(R.id.question_text_radio_button);
question_txtView.setText(question.getDescription());
num.add(question.getQuestionId());
if (question.getWidgetId() == radio_button) {
radiogroup.setVisibility(View.VISIBLE);
radioButton = new RadioButton[question.getAnswers().size()];
Typeface font4 = Typeface.createFromAsset(getActivity()
.getAssets(), "fonts/enriqueta/Enriqueta-Regular.otf");
for (int i = 0; i < question.getAnswers().size(); i++) {
radioButton[i] = new RadioButton(context3);
radioButton[i].setLines(3);
radioButton[i].setText(question.getAnswers().get(i)
.getAnswer_Text());
radioButton[i].setTag(question.getAnswers().get(i)
.getAnswer_Id());
radioButton[i].setTextColor(Color.BLACK);
radioButton[i].setTypeface(font4);
radioButton[i].setTextSize(30);
radiogroup.addView(radioButton[i]);
radiogroup.isClickable();
}
allRadioGroups.add(radiogroup);
} else if (question.getWidgetId() == m_spinner) {
spinner.setVisibility(View.VISIBLE);
List<String> list = new ArrayList<String>();
for (int b = 0; b < question.getAnswers().size(); b++) {
String data = question.getAnswers().get(b).getAnswer_Text()
.toString();
spinner.setTag(question.getAnswers().get(b).getAnswer_Id());
list.add(data);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
context3, R.layout.my_style, list) {
public View getView(int position, View convertView,
ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(22);
return v;
}
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View v = super.getDropDownView(position, convertView,
parent);
((TextView) v).setTextColor(Color.BLACK);
return v;
}
};
spinner.setAdapter(dataAdapter);
allSpinners.add(spinner);
} else if (question.getWidgetId() == edit_text) {
editText.setVisibility(View.VISIBLE);
allEds.add(editText);
} else if (question.getWidgetId() == rating_bar) {
ratingBar.setVisibility(View.VISIBLE);
countRating_txt.setVisibility(View.VISIBLE);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar rating_bar,
float rating, boolean fromUser) {
rating = rating_bar.getRating();
countRating_txt.setText(String.valueOf(rating)
+ "Ratings");
}
});
allRatingBars.add(ratingBar);
}
// }
} catch (Exception e) {
Log.e("Log error :",
"could not write the text views in radioButton fragment");
}
ItemPosition();
return view;
}
OnClickListener btnNextOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (question.getWidgetId() == radio_button) {
validatedRadioGroup();
} else if (question.getWidgetId() == m_spinner) {
validatedSpinner();
} else if (question.getWidgetId() == edit_text) {
validatedEditText();
} else if (question.getWidgetId() == rating_bar) {
validatedRatingBar();
}
mViewPager.setCurrentItem(getItem(+1), true);
}
};
OnClickListener btnBackOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
mViewPager.setCurrentItem(getItem(-1), true);
}
};
OnClickListener btnDoneOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
int lastItem = question.getQuestionIds().size();
if (lastItem == question.getQuestionIds().size()) {
if (question.getWidgetId() == radio_button) {
radioText();
} else if (question.getWidgetId() == m_spinner) {
spinnerText();
} else if (question.getWidgetId() == edit_text) {
EditText_Value();
} else if (question.getWidgetId() == rating_bar) {
ratingText();
}
Intent a = new Intent(getActivity(), FinishedSurvey.class);
startActivity(a);
}
}
};
}
public void ItemPosition() {
for (int j = 0; j < num.size(); j++) {
// int item = num.indexOf(j);
if (j == 0) {
btnBack.setVisibility(View.GONE);
btnNext.setVisibility(View.VISIBLE);
btnDone.setVisibility(View.GONE);
System.out.println("the first part");
} else if (!(j == 0 || (j == question.getQuestionIds().size() - 1))) {
btnBack.setVisibility(View.VISIBLE);
btnNext.setVisibility(View.VISIBLE);
btnDone.setVisibility(View.GONE);
System.out.println("the second part");
} else {
if (j == question.getQuestionIds().size() - 1) {
btnNext.setVisibility(View.INVISIBLE);
btnDone.setVisibility(View.VISIBLE);
System.out.println("the last part");
}
}
}
}

Automatically check the checkbox that corresponds to the value from the database

I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.

Categories

Resources