How to remove a value from programatic-created checkbox? - java

The app is about making a simple survey with checkboxes. The checkbox values come from REST Api as list like ["option1", "option2"...]
I will post selected checkboxes as also a list. All set and working except for removing unselected items. How can I get and remove 'unselected' data from list?
(User may make changes) I tried with List and HashMap, couldn't make it. Thanks in advance!
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList= new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Button button_send;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout)findViewById(R.id.linear_checkbox);
button_send= (Button)findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(cevapList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this, "LIST: "+"\n"+ checkedList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList){
textList = answerList;
for(j=0; j<textList.size(); j++){
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
Toast.makeText(MainActivity.this, ""+cb.getText()+" selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
secilenlerList.add(cb.getText().toString());
}else{
Toast.makeText(MainActivity.this, ""+cb.getText()+" unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}

Update your code its working fine. You didn't make changes when user unselect any check box item.
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList = new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Button button_send;
int j;
private ArrayList<String> secilenlerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout) findViewById(R.id.linear_checkbox);
button_send = (Button) findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(answerList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "LIST: " + "\n" + secilenlerList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList) {
textList = answerList;
secilenlerList = new ArrayList<>();
for (j = 0; j < textList.size(); j++) {
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if (ischecked) {
Toast.makeText(MainActivity.this, "" + cb.getText() + " selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
if (!secilenlerList.contains(cb.getText().toString()))
secilenlerList.add(cb.getText().toString());
} else {
if (secilenlerList.contains(cb.getText().toString()))
secilenlerList.remove(cb.getText().toString());
Toast.makeText(MainActivity.this, "" + cb.getText() + " unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}

Related

I want to count my every right and wrong answer submitted in my quiz app and want to display score in textview

This is the method I have created to check the condition
For the right answer, I am showing the png image and the same for the wrong answer
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
I have called the method checkAnswer() method in the true button click and false button click below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(true);
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(false);
mFalseButton.setEnabled(false);
mTrueButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
Now, i have used intent method in Score Button click and in the ScoreActivity.class i want to show the
store in textview.
please tell me how to count the true answer and wrong answer and store the score in the variable which i
can show in textview
Please help me.
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
finish();
}
});
private int trueCount = 0;
private int falseCount = 0;
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
trueCount++;
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
falseCount++;
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
...
//Displaying int textView
textView.setText(String.format("Right count: %d False count: %d", rightCount, falseCount));
mFinalMarks = (TextView)findViewById(R.id.final_marks);
mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks out of 10 ");
getIntent().getStringExtra("PLUS_MARKS");
// it is showing null instead of score

how to make toast of current selected text from this array adaptor

i am getting problem to copy or print toast message from this array adaptor. I am using swipe cardview library and i want to copy current displayed text from cardview when i click on copy button. I tried to copy text but it is copying xml layout text not that text which i added to list.
This is my code
fillingcontainer = findViewById(R.id.frame);
textView = findViewById(R.id.hellotext);
copy=findViewById(R.id.copy);
button=findViewById(R.id.download);
layout=findViewById(R.id.lalla);
al = new ArrayList<String>();
al = new ArrayList<String>();
al.add("Ni");
al.add("Ro");
al.add("Ka");
al.add("Nar");
random= new Random();
lins= Arrays.asList(getResources().getStringArray(R.array.coorss));
arrayAdapter = new ArrayAdapter<String>(this, R.layout.itemas, R.id.hellotext, al);
fillingcontainer.setAdapter(arrayAdapter);
fillingcontainer.getSelectedView().setBackgroundColor(Color.RED);
copy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s= textView.getText().toString();
Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
}
});
fillingcontainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object o) {
Toast.makeText(MainActivity.this, "Left!", Toast.LENGTH_SHORT).show();
if (i%5==0) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
String s =textView.getText().toString();
}
#Override
public void onRightCardExit(Object o) {
Toast.makeText(MainActivity.this, "Right!", Toast.LENGTH_SHORT).show();
i++;
if (i%5==0) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAdapterAboutToEmpty(int i) {
al.add("NO more text ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}
#Override
public void onScroll(float v) {
}
});
fillingcontainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "clciekd", Toast.LENGTH_SHORT).show();
}
});
}

Store checkbox values in firebase using android studio

I am working on recommendation application I using firebase to store information about user.I have used checkboxes for health status information.
I want to save all the checkbox values I selected.but in my code if I check more then one checkbox it always save the last checkbox.
This is my code How can I fix it to store all checked values?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Toolbar toolbar =findViewById(R.id.toolbarotherpages);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
databaseUser = FirebaseDatabase.getInstance("https://bonappetit-808c5.firebaseio.com").getReference("users");
users = new ArrayList<>();
addusername= findViewById(R.id.editTextname);
addphone=findViewById(R.id.editTextphone2);
mFirstCheckBox=findViewById(R.id.cbox1);
mSecondCheckBox=findViewById(R.id.cbox2);
mThirdCheckBox=findViewById(R.id.cbox3);
addhealthstatus=findViewById(R.id.editTexthealthstatus);
btnsignup =findViewById(R.id.buttonsignup2);
btnsignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signup dosignup = new Signup(); // this is the Asynctask
dosignup.execute("");
}
});
}
protected void onStart() {
super.onStart();
//attaching value event listener
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
users.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
users user = postSnapshot.getValue(users.class);
//adding artist to the list
users.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class Signup extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String username = addusername.getText().toString();
String phone = addphone.getText().toString();
String healthstatus = addhealthstatus.getText().toString();
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("") || phone.trim().equals("")) {
z += "Please fill in all fields";
} else {
int count = 0;
for (users user2 : users) {
if (user2.getPhonenumber().equals(phone)) {
count = 1;
}
}
if (count == 0) {
try {
if(mFirstCheckBox.isChecked()) {
users user = new users(username, phone,"Diabetes");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mSecondCheckBox.isChecked()) {
users user = new users(username, phone, "pressure");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mThirdCheckBox.isChecked()) {
users user = new users(username, phone,
healthstatus);
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
z = "Account created";
isSuccess = true;
}
catch (Exception ex) {
z = "Mobile number was used";
isSuccess = false;
}
}
}
return z;
}
}
To get the selected checked values you can use Switch case following code
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkBox1:
....
break;
case R.id.checkBox2:
......
break;
case R.id.checkBox3:
......
break;`

Sending videolink from listview to videoview in same activity

I have a videoview and listview/gridview in my playvideo activity.
One video is already playing in the videoview. But now i want to play the other video which are showing in the listview/gridview how can i do that?
Playvideo Activity
public class playvideoactivity extends Activity {
GridViewWithHeaderAndFooter grid;
String videourl="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
private static final String url = "http://dakwf.org/api/bd_english.json";
private List<ChannelItem> chanellist = new ArrayList<ChannelItem>();
private static final String TAG = MainActivity.class.getSimpleName();
public static VideoView player;
public static ImageButton btnPlayPause;
private ImageView btnFullscreen;
private ProgressBar spinner;
private RelativeLayout mediaController;
private Handler btnHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar) findViewById(R.id.progressBar);
player=(VideoView) findViewById(R.id.player);
mediaController=(RelativeLayout) findViewById(R.id.media_controller);
spinner.setVisibility(View.VISIBLE);
mediaController.setVisibility(View.INVISIBLE);
btnPlayPause=(ImageButton) findViewById(R.id.btn_playpause);
btnFullscreen=(ImageView) findViewById(R.id.btn_fullscreen);
final CustomGridviewadapter customGridview= new CustomGridviewadapter(this,chanellist);
grid = (GridViewWithHeaderAndFooter) findViewById(R.id.grid_view);
setGridViewHeaderAndFooter();
grid.setAdapter(customGridview);
//----------- Creating volley request obj--------------------
JsonArrayRequest movieReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ChannelItem item = new ChannelItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
// adding movie to movies array
chanellist.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
customGridview.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
//------------------- Mediacontroller Visiblity-------------------------------------
player.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(final View paramAnonymousView, MotionEvent paramAnonymousMotionEvent)
{
if (paramAnonymousMotionEvent.getAction() == 0){
if (MainActivity.this.mediaController.getVisibility() != View.INVISIBLE) {
}
MainActivity.this.mediaController.setVisibility(View.VISIBLE);
MainActivity.this.btnHandler.postDelayed(new Runnable(){
public void run(){
MainActivity.this.mediaController.setVisibility(View.INVISIBLE);
}
}, 2000L);
}
for (;;){
return true;
}
}
});
//------FullScreen Button -----
btnFullscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView) {
Intent i = new Intent(MainActivity.this, FullScreenView.class);
startActivity(i);
}
});
//------Play Pause Button ----------
btnPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView){
if ( (player != null) && (MainActivity.this.player.isPlaying()) ){
MainActivity.this.player.pause();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_play);
return;
}
MainActivity.this.player.start();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_pause);
return;
}
});
//----------------------------------------
try {
MediaController mController = new MediaController(MainActivity.this);
mController.setAnchorView(player);
Uri video = Uri.parse(videourl);
player.setMediaController(mController);
player.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
player.setMediaController(null);
player.requestFocus();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
player.start();
hidespinner();
}
});
}
// ------------ Header Gridview ----------------
#SuppressLint({"InflateParams", "SetTextI18n"})
private void setGridViewHeaderAndFooter() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.grid_header, null, false);
//locate views
TextView headerText = (TextView)headerView.findViewById(R.id.textViewheader);
headerText.setText("Suggestion");
headerView.setOnClickListener(onClickListener(0));
grid.addHeaderView(headerView);
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
// Toast.makeText(MainActivity.this, "Header Clicked!", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(MainActivity.this, "Footer Clicked!", Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
hidespinner();
}
private void hidespinner() {
if (spinner != null) {
spinner.setVisibility(View.INVISIBLE);
spinner = null;
}
}
}
When opening starting the app you need to get the data and store on a variable or into database.
Create a ChannelList type List (List<ChannelList>) and store ChannelList data into it.
List<ChannelList> list = new ArrayList<>(); // containing all data
You can store Title, VideoUrl, iconUrl and add it to the list.
When clicking on a List Item you will get the position by using setOnItemClickListener.
And then use the position to get the clicked ChannelList position.
Suppose your list type variable is channelList.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChannelList channelList= list.get(position);
// now you have all data of clicked ChannelList
// do whatever you like
//channelList.getVideoUrl(); etc as your getter method
}
}
});
For more about List, you can check it Here

Activity and Voice recognition

I have this code:
public class VoiceActivity extends Activity implements OnClickListener {
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyActivity";
public String str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button speakButton = (Button) findViewById(R.id.speakButton);
mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener {
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech() {
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB) {
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer) {
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech() {
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error) {
Log.d(TAG, "error " + error);
mText.setText("error " + error);
}
public void onResults(Bundle results) {
str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
mText.setText("results: " + str);
}
public void onPartialResults(Bundle partialResults) {
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params) {
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.speakButton) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.moc");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
sr.startListening(intent);
}
}
}
How to make an automatic transition to another Activity after recognition voice (press button - say - open next Activity and result in it)? In my example, it says error in line
intent.setClass (this, SecondActivity.class).
Example:
public void onResults(Bundle results) {
str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
Intent intent = new Intent();
Bundle b = new Bundle();
b.putString("StrID", str);
intent.putExtras(b);
intent.setClass(this, SecondActivity.class);
startActivity(intent);
}
you should relpace the this with VoiceActivity.this , because the this is refering the the listener instance not of the context of your activity :
intent.setClass (VoiceActivity.this, SecondActivity.class);

Categories