Dynamic Radio button store json response id and name in that - android

Hello guys in bottom I code something which work perfectly but I am using array list in that, but I want Dynamic radio button if user select any button so for user it should display name and for me i get selected id my json response is like divid,divisionname I have to show divisionname to user in Radio button and if user select any radio based on that i want divid any thing if we pass both id and name in one radio button, on submit button i want Id
ArrayList<String> divId = null;
ArrayList<String> divName = null;
RadioGroup divRadioGrouop;
String divsionId=null;
if (divisionCheck) {
RadioButton rdbDiv;
divId = new ArrayList<>();
divName = new ArrayList<>();
divisionLogin.setVisibility(View.VISIBLE);
divRadioGrouop.removeAllViews();
for (int j = 0; j < jsonArrayDiv.length(); j++) {
JSONObject jsonDiv = jsonArrayDiv.getJSONObject(j);
divId.add(jsonDiv.getString("divid"));
divName.add(jsonDiv.getString("divisionname"));
rdbDiv = new RadioButton(this);
rdbDiv.setId(View.generateViewId());
rdbDiv.setText(jsonDiv.getString("divisionname"));
divRadioGrouop.addView(rdbDiv);
}
divOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int divid = divRadioGrouop.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(divid);
String divSionNameFind = (String) radioButton.getText();
int idPostionIndex = divName.indexOf(divSionNameFind);
divsionId = divId.get(idPostionIndex);
divName.clear();
divId.clear();
logINDataForDiv();
}
});
divCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
});
}

You need to use tag in that case, first add divid in all your radio button like:
radioButton.setTag(divid);
on Submit, you can get back divid by this:
String divid=radioButton.getTag().toString();
Make sure you do setTag before getTag, otherwise getTag will return null and your app will crash.

Related

Android: getting wrong checked radio button text value

I am trying to view specific icons based on the selected radio button using an if statement.
I didn't want to use a listener since I'm clicking a submit button anyway.
I have 3 buttons: Party, Accident and Other.
When running my code my Log message shows that I always get "other" (else clause) as a checked value, even when it is not.
I have tried so many different ways from many different threads on Stack Overflow but I'm afraid I might be doing something else wrong.
Here is the code:
private void addMarkerToMap() {
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
View view = getLayoutInflater().inflate(R.layout.dialoglayout, null);
streetname = (EditText) view.findViewById(R.id.streetname_input);
title = (EditText) view.findViewById(R.id.title_input);
description = (EditText) view.findViewById(R.id.description_input);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
final int selectedID = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) view.findViewById(selectedID);
Button addButton = (Button) view.findViewById(R.id.add_button);
Button cancelButton = (Button) view.findViewById(R.id.cancel_button);
builder.setView(view);
final AlertDialog dialog = builder.create();
dialog.show();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addMarker(streetname, title, description);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
private void addMarker(EditText streetname, EditText title, EditText description) {
String streetnameText = streetname.getText().toString();
String titleText = title.getText().toString();
String descriptionText = description.getText().toString();
String radioText = radioButton.getText().toString();
BitmapDescriptor icon; //= BitmapDescriptorFactory.fromResource(R.drawable.standard); //has to have a standard value
//Log.d("id", "id" + ID);
Log.d("radioText", "text: " + radioText);
if(streetnameText.isEmpty() || titleText.isEmpty() || descriptionText.isEmpty()) {
Toast.makeText(this, "One of the textboxes is empty. Please fill in all textboxes", Toast.LENGTH_LONG).show();
} else {
if(radioText.equals("Accident")){
icon = BitmapDescriptorFactory.fromResource(R.drawable.accident);
}
else if(radioText.equals("Party")){
icon = BitmapDescriptorFactory.fromResource(R.drawable.party);
}
else {
icon = BitmapDescriptorFactory.fromResource(R.drawable.standard);
}
MarkerOptions markerOptions = new MarkerOptions().position(latlngGlobal)
.title(titleText)
.snippet(descriptionText)
.icon(icon);
//TODO add new marker
mMarker = mGoogleMap.addMarker(markerOptions);
// TODO Get location for marker, add to database
}
}
I have also tried using this instead but it's the same result (gives ID of "other"):
if(ID == R.id.accident_radio){
icon = BitmapDescriptorFactory.fromResource(R.drawable.accident);
}
else if(ID == R.id.party_radio){
icon = BitmapDescriptorFactory.fromResource(R.drawable.party);
}
else {
Log.d("id", "id" + ID);
icon = BitmapDescriptorFactory.fromResource(R.drawable.standard);
}
You declared radioButton as the selected radio button in the group at that specific time only, you don't do any new declarations for it before calling addMarker(...) so it will always be the same.
Instead of:
String radioText = radioButton.getText().toString();
Try something like this (but make it nicer):
String radioText = ((RadioButton) view.findViewById(((RadioGroup) view.findViewById(R.id.radioGroup)).getCheckedRadioButtonId())).getText().toString();

set and get android button text programatically [duplicate]

This question already has answers here:
Get text from pressed button
(8 answers)
Closed 8 years ago.
How can i get the text set on the button inside the on-click() class?
i need to get the button text for sq l select statement
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is");
}
});
c.moveToNext() ;
enter code here
You can type caste the view to button and use it to getText().
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(),
Toast.LENGTH_SHORT).show();
Button b = (Button)v;
String buttonText = b.getText().toString();
Log.d("TAG", "The text is " + buttonText);
}
});
c.moveToNext() ;
You are adding the Button to table row tableRow.addView(b);. I at first look at the code din't see it. Missed it.
So Make it final
final Button b = new Button(getApplicationContext());
// Use ActivtiyContext
final Button b = new Button(ActivityName.this);
// posted a link at the end read it.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
Inside onClick
public void onClick(View v) {
String value = b.getText().toString()
}
Also check
When to call activity context OR application context?
As per my way create String Array and :
String Title = new String[count];
And now implement like this:
for (int j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(j);
Title[a] = c.getString(c.getColumnIndex("jour");
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
Toast.makeText(getApplicationContext(), "Button click on(): "+Title[v1.getId()].toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is: "+v1.getId());
}
});
tableRow.addView(b);
c.moveToNext() ;
}
Try this code:
public void onClick(View v) {
String value = (Button)v.getText().toString()
}
First you give onclick event for Button like (buttonClick).
final Button testButton = new Button(getApplicationContext());
void buttonClick(View v){
Log.v("text", testButton.getText().toString()); // get the text
testButton.setText("sometext"); //to change the text
}

Get values of multiple checkboxes on Android

I have one of these for each day of the week:
mondayRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mondayRadioButton.isChecked()){
deleteAppointmentsLayout.removeAllViews();
daySelected = 1;
for(Iterator<Appointment> i = appointments.iterator(); i.hasNext();){
Appointment item = i.next();
if(item.getDay() == 1){
checkBox = new CheckBox(DeleteAppointmentActivity.this);
System.out.println("fucken did work");
id = item.getId();
time = item.getTime();
duration = item.getDuration();
description = item.getDescription();
boxText = time + ", " + duration + ", " + description;
checkBox.setText(boxText);
checkBox.setTextSize(12);
checkBox.setId((int) id);
deleteAppointmentsLayout.addView(checkBox);
}
else {
System.out.println("fucken didnt work");
}
}
}
}
});
When an onclick for a button is activated I want to retrieve the information for each of the selected checkboxes for the currently selected day (checkboxes are generated programmatically). How can I check which ones are selected when the onclick for the Delete button is activated?
Create a member variable Array like
public class MyClass extends Activity
{
ArrayList<CheckBox> cbArray = new ArrayList<CheckBox>();
then when you create a checkbox add it to the ArrayList. Now when you click the delete Button use a for loop to iterate over the ArrayList and call isChecked() on each one.
Then delete or add that to a checked Array to do whatever you need with it
for (int i=0; i<cbArray.size(); i++)
{
if (cbArray.get(i).isChecked())
{
// do whatever here

Button to transfer me to next page and start a game

It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.

Regarding android Development

I am doing an application in which I have to display the numbers on TextView randomly and automatically with the help of Timer. I am able to get the random Numbers in the log without repeating, but I am not able to print the same on device please help me...
Regards,
Akki
Source:
//RandomNumber.java
public class RandomNumber extends Activity{
static Random randGen = new Random();
int tambolanum,count=0;
private Button previousbutton;
private Button startbutton;
private Button nextbutton;
int bingonum[]=new int[90];
boolean fill;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
LinearLayout number=(LinearLayout)findViewById(R.id.numbersview);
final TextView randomnum=(TextView)findViewById(R.id.numberstext);
previousbutton=(Button)findViewById(R.id.previous);
nextbutton=(Button)findViewById(R.id.next);
startbutton=(Button)findViewById(R.id.start);
startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
//--- Initialize the array to the ints 0-90
do{
fill = true;
//Get new random number
tambolanum = randGen.nextInt(90) + 1;
//If the number exists in the array already, don't add it again
for(int i = 0; i < bingonum.length; i++)
{
if(bingonum == tambolanum)
{
fill = false;
}
}
//If the number didn't already exist, put it in the array and move
//To the next position
if(fill == true)
{
bingonum[count] = tambolanum;
count++;
}
} while(count < 90);
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
}
setText(CharSequence text)
The problem you're having is that you're overwriting your text in every itteration of this loop:
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
You need to build your string first then set it. Something like:
StringBuilder sb = new StringBuilder();
for(i=0;i /* where's the rest of this for-statement? */
{
sb.append(Integer.toString(bingonum[i]);
}
randomnum.setText(sb.toString());

Categories

Resources