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");
}
}
}
}
Related
I want to saveInstance when changing from portrait to landscape. But when I try to restoreInstance of my letter button's background and enable, it tells me this error.
The program went well when I comment out those codes.
This is letter class
public class Letter extends BaseAdapter {
private String[] letters;
private LayoutInflater letterInf;
public Letter(Context c){
letters = new String[26];
for(int a = 0; a < letters.length; a++){
letters[a] = ""+(char)(a+'A');
}
letterInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return letters.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button btnLetter;
if(convertView == null){
btnLetter = (Button) letterInf.inflate(R.layout.letter, null, false);
}else{
btnLetter = (Button) convertView;
}
btnLetter.setText(letters[position]);
return btnLetter;
}
}
This is what I try to restore onRestoreInstance (the whole version)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currPart = savedInstanceState.getInt("currPart");
numChars = savedInstanceState.getInt("numChars");
numCorr = savedInstanceState.getInt("numCorr");
int[] savedBodyPartVisibility = savedInstanceState.getIntArray("bodyPartVisibility");
for(int i = 0; i<savedBodyPartVisibility.length; i++){
bodyParts[i].setVisibility(savedBodyPartVisibility[i]);
}
//saved word
currWord = savedInstanceState.getString("currWord");
hint = savedInstanceState.getString("hint");
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){//get orientation
tvHint.setText("Hint:"+hint);// if landscape, show hint
//Toast.makeText(getBaseContext(), "This is landscape!", Toast.LENGTH_SHORT).show();
}
charViews = new TextView[currWord.length()];
wordLayout.removeAllViews();
for(int c = 0; c<currWord.length(); c++){
charViews[c] = new TextView(this);
charViews[c].setText(""+currWord.charAt(c));
charViews[c].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
charViews[c].setGravity(Gravity.CENTER);
charViews[c].setTextColor(Color.WHITE);
charViews[c].setBackgroundResource(R.drawable.letter_bg);
wordLayout.addView(charViews[c]);
}
//saved charView
int[] savedCharViewColor = savedInstanceState.getIntArray("charViewColor");
for(int i = 0; i< savedCharViewColor.length; i++){
charViews[i].setTextColor(savedCharViewColor[i]);
}
//int numLetters = savedInstanceState.getInt("numLetters");
//letter enable//letter button background color
boolean[] savedLetterEnable = savedInstanceState.getBooleanArray("letterEnable");
int[] savedLettersColor = savedInstanceState.getIntArray("lettersColor");
for(int i = 0; i<savedLetterEnable.length; i++){
letters.getChildAt(i).setEnabled(savedLetterEnable[i]);
//letters.getChildAt(i).setBackgroundColor(savedLettersColor[i]);
}
}
You cannot restore it this way because views are recycled in RecyclerView/ListView. It means that only some of them is rendered and when you scroll it reuses already rendered views.
So in most of the cases it will not have that many child views as items in datasource.
The proper approach is to store information about items' state inside adapter.
I have created simple example to give you an idea how could it look. Note that setOnSelectedListener(new OnSelectedListener(){...} is fake code and you should write proper listener (onClick, or if you want to use Checkboxes then onCheckedCHange or anything else based on your needs).
public class Letter extends BaseAdapter {
private String[] letters;
private LayoutInflater letterInf;
private Set<String> selectedLetters = new ArraySet();
public Letter(Context c){
letters = new String[26];
for(int a = 0; a < letters.length; a++){
letters[a] = ""+(char)(a+'A');
}
letterInf = LayoutInflater.from(c);
}
Set<String> getState() {
return selectedLetters;
}
void restoreState(Set<String> selectedLetters) {
this.selectedLetters = selectedLetters;
notifyDataSetInvalidated();
}
#Override
public int getCount() {
return letters.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button btnLetter;
if(convertView == null){
btnLetter = (Button) letterInf.inflate(R.layout.letter, null, false);
}else{
btnLetter = (Button) convertView;
}
if(selectedLetters.contains(letters[position])) {
btnLetter.setSelected(true);
} else {
btnLetter.setSelected(false);
}
btnLetter.setOnSelectedListener(new OnSelectedListener() {
void onSelected(..., boolean isSelected) {
if(isSelected) {
selectedLetters.add(letters[position]);
} else {
selectedLetters.remove(letters[position]);
}
}
});
btnLetter.setText(letters[position]);
return btnLetter;
}
}
Then whenever you save state, you get it from adapter getState and put it in savedInstanceState.
Whenever you restore state you get it from savedState and put in adapter restoreState
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.
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
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.
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.