GetText() for a chipgroup (entry) - java

I'm quite new in java/android and i need for a project to implement chip (entry). I followed a tutorial and the chip works. what i made
XML
<Button
android:id="#+id/email_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="Ajouter"
android:textSize="10sp"
app:layout_constraintBottom_toTopOf="#+id/chip_group"
app:layout_constraintLeft_toRightOf="#+id/fields_2_form"
app:layout_constraintTop_toBottomOf="#+id/title_field_3">
</Button>
<com.google.android.material.chip.ChipGroup
android:id="#+id/chip_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/fields_2_form">
</com.google.android.material.chip.ChipGroup>
Activity
public void buttonClick(View view) {
final EditText fieldForm2 = findViewById(R.id.fields_2_form);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
final Button emailButton = findViewById(R.id.email_button);
final Chip chip = new Chip(this);
ChipDrawable drawable = ChipDrawable
.createFromAttributes(this, null, 0, R.style.Widget_MaterialComponents_Chip_Entry);
chip.setChipDrawable(drawable);
chip.setCheckable(false);
chip.setClickable(false);
chip.setChipIconResource(R.drawable.ic_fingerprint_black_24dp);
chip.setIconStartPadding(3f);
chip.setPadding(60, 10, 60, 10);
chip.setText(fieldForm2.getText().toString());
// remove chip on click on the -
chip.setOnCloseIconClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chipGroup.removeView(chip);
}
});
if (!EmailValid(fieldForm2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Veuillez rentrer un email valide",
Toast.LENGTH_LONG).show();
fieldForm2.setText("");
} else {
chipGroup.addView(chip);
fieldForm2.setText("");
}
}
Well but my problem is when i need to get all the typed emails from the chip for another activity.
I tried to do it in this method :
public Intent getFormInfos() {
TextView mEditTextHour = findViewById(R.id.fields_1_form);
final Spinner spin = (Spinner) findViewById(R.id.Spinner);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
//FIXME
String chiptext = chipGroup.INEEDTOGETCHIPTEXTHERE();
String myEditedText1 = mEditTextHour.getText().toString();
String spinnerText = spin.getSelectedItem().toString();
Intent intent = new Intent(this, ActivityListMareu.class);
ApiService.getmReunions().add(new Reunion(myEditedText1, spinnerText, chiptext));
return intent;
}
I need to do something like chipgroup.getText() but it doesn't work i tried some stuff but i'm really confused with chip and actually i've no idea how to make it.
Does someone have an idea for this?
(sorry for my bad english)

Using this you can get all the text set over all Chip in that ChipGroup.
ArrayList<String> emails = new ArrayList<>();
for (int i = 0; i < chipGroup.getChildCount(); i++) {
String email = ((Chip) chipGroup.getChildAt(i)).getText().toString();
emails.add(email);
}
In your case if you have only one chip in chipGroup you can directly :
if (chipGroup.getChildCount() > 0) {
CharSequence yourText = ((Chip) chipGroup.getChildAt(0)).getText();
}

This is in Kotlin but you can essentially do a transform on the getChildren() just like any collection/sequence:
val emails = chipGroup.children.map {
(it as Chip).text.toString()
}.toList()

Related

flash cards showing blank card android

I am creating a flash card app in android.
For some reason when you hit the button for next card it will randomly show either the next card or a blank card. Sometimes it will be a whole heap of blank cards then one with information. Please find the code below. I am new to creating apps but have done java in the past, it works perfectly in netbeans but not when you run the app.
I want the cards to only appear once thats what the num arraylist is for, it holds the index numbers for the names arraylist. so it appears once but will show blank cards when it shouldnt be. eg: card with info, card without info, card with info. sometimes it will show multiple empty cards then one with info, that is my problem.
I know i havent commented the code,
The first activity:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Character.createArrays();
}
/**
* Called when the user taps the Start button
*/
public void sendMessage(View view) {
Character.getCharName();
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
}
}
The second activity where the cards are called:
public class DisplayMessageActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
;
}
public void refresh(View view) {
Character.getCharName();
overridePendingTransition(0, 0);
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
this.finish();
overridePendingTransition(0, 0);
}
The methods to get the cards, There are arraylists and the arrays are created correctly and the string arrays are inputted correctly. the CharacterNames array is just an array with names in them. the num array just has index numbers inputted and checked:
public void getCharName() {
RandomNumGen();
mMessage = "";
message = "";
while (num.contains(mRandom)) {
RandomNumGen();
}
for (int i = 0; i < CharacterNames.size(); i++) {
if (i == mRandom) {
mMessage = CharacterNames.get(i);
if (i == mRandom && CharacterNames.contains(mMessage)) {
num.add(mRandom);
card();
}
}
}
}
public void RandomNumGen() {
mRandom = (int) (Math.random() * CharacterNames.size());
}
public String card() {
String[] array;
for (int y = 0; y < names.size(); y++) {
if (Arrays.asList(names.get(y)).contains(mMessage)) {
array = (names.get(y));
for (String array1 : array) {
if (array1 != null && array1.length() > 0) {
message += "\n" + "\n" + (array1);
}
}
Arrays.fill(array, null);
}
}
return message;
}
I hope thats enough information to help.
Thank you so much for understanding an helping me
activity display message xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#string/textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="refresh"
android:text="#string/next_char"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Next character" />
</android.support.constraint.ConstraintLayout>
enter code here

displaying different messages depending on parameters

I'm new to android development. I have 10 different buttons and I want to display a toast for each one of them. The message is something like:
"This is the button: " + numButton
Where numButton is a prop passed to the function. This is the function code:
public void displayMensaje(View v) {
Toast.makeText(ActividadUno.this, "Test", Toast.LENGTH_SHORT).show();
}
And this is the xml:
<Button
android:id="#+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="400dp"
android:text="churro"
android:onClick="displayMensaje"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
You can cast the View in Button and get the text of button.
Something like this:
public void displayMensaje(View v) {
Button button = (Button) v;
String title = button.getText();
String message = "Test " + title;
Toast.makeText(ActividadUno.this, message, Toast.LENGTH_SHORT).show();
}
Edit:
According to my understanding from your comment below, you have multiple buttons in your activity, and you want to display different values on clicking different buttons.
You can have a Map with keys as button titles and values as nutrition values.
Below is a general example of how you can achieve this:
public class MyActivity extends Activity {
// Your Message Format
private static final String MSG_FORMAT = "Item Name: %s\n"
+ "Fat: %s\n"
+ "Protein: %s\n"
+ "Calories: %s";
// A Map to hold info of all items
// Key = button title
// Value = Array containing item info
private Map<String, String[]> info = new HashMap();
// Assuming you have 3 buttons in your activity
private Button btnMilk;
private Button btnEggs;
private Button btnChicken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
btnMilk = (Button) findViewById(R.id.btn_milk);
btnEggs = (Button) findViewById(R.id.btn_eggs);
btnChicken = (Button) findViewById(R.id.btn_chicken);
// 0 = Fat, 1 = Protein, 2 = Calories
String[] milkInfo = new String[]{"12", "20", "125"};
String[] eggsInfo = new String[]{"10", "50", "205"};
String[] chickenInfo = new String[]{"50", "5", "500"};
// load your Map with the data
info.put(btnMilk.getText(), milkInfo);
info.put(btnEggs.getText(), eggsInfo);
info.put(btnChicken.getText(), chickenInfo);
}
public void displayMessage(View v) {
Button button = (Button) v;
String title = button.getText();
// Get item info from your Map
String[] itemInfo = info.get(title);
// Create message using the format and values from the array
String message = String.format(MSG_FORMAT, title, itemInfo[0], itemInfo[1], itemInfo[2]);
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
Hope this helps

Getting text of buttons from an Activity and setting it as text in Text View in other Activity

I m working on a project i have two categories Cricketers and Animals on one activity as Button and a Text View on other activity i want to change the text of Text View when ever i presses the Button i.e If Cricketer then set text to cricketer same goes for animal.
OnClick Listner for both buttons: On Activity 1
public void onClickcricketer(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btncricket);
String crickettext = b.getText().toString();
i.putExtra("Cricket",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btnanimal);
String animaltext = b.getText().toString();
i.putExtra("Animal",animaltext);
startActivity(i);
}
Code on Activity 2:
Bundle cricketData = getIntent().getExtras();
if (cricketData == null){
return;
}
String Cricket = cricketData.getString("Cricket");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
Bundle AnimalData = getIntent().getExtras();
if (AnimalData == null){
return;
}
String Animal = AnimalData.getString("Animal");
final TextView a = (TextView)findViewById(R.id.txtCategryShow);
a.setText(Animal);
This method just show animal text in Text view.. when i click Crcketer button it shows nothing
First perform an onClick method:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toExtra = "" + btn.getText();
Intent i = new Intent(this,NextActivity.class);
i.putExtra("key",toExtra);
}
});
then in the new Activity OnCreate method add:
Intent i = getIntent();
String fromExtra = intent.getStringExtra("key");
and finally setText to your TextView:
txt.setText(fromExtra)
It is doing correct, see your code again, On same TextView you are setting text Animal which is null in case of clicking cricket ..
Try this in second activity:
String Cricket = getIntent().getStringExtra("KEY");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
And make your methods like this:
public void onClickcricketer(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_cricket);
String crickettext = b.getText().toString();
i.putExtra("KEY",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_animal);
String animaltext = b.getText().toString();
i.putExtra("KEY", animaltext);
startActivity(i);
}

Setting defaults when .getIntent().getExtras() is null

I'm attempting to pull user input from a couple EditText fields into another activity. In particular, I'd like to utilize team names input by the user in another activity of the app.
So, taking input from here:
and using it here:
As seen in the photo above, I've been successful in implementing this when the user enters in a couple team names, which I'm handling with getIntent().getExtras().
However, if the user clicks the "Start Scorekeeper" button without entering in any team names, I get the following:
However, I'd like to set default team names of "Team A" and "Team B".
I've tried to accomplish this with the following (which hasn't worked):
TeamSelector.java:
public void onClick(View view) {
Intent i = new Intent(this, ScoreKeeper.class);
final EditText teamAInput = (EditText) findViewById(R.id.team_a_input);
String teamAName = teamAInput.getText().toString();
i.putExtra("teamA", teamAName);
final EditText teamBInput = (EditText) findViewById(R.id.team_b_input);
String teamBName = teamBInput.getText().toString();
i.putExtra("teamB", teamBName);
startActivity(i);
}
Then creating a conditional as I pick up the intent.
ScoreKeeper.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_keeper);
Bundle teamNames = getIntent().getExtras();
if(teamNames==null){
final TextView teamAText = (TextView) findViewById(R.id.teamAText);
teamAText.setText(getString(R.string.team_a_name));
final TextView teamBText = (TextView) findViewById(R.id.teamBText);
teamBText.setText(getString(R.string.team_b_name));
}
else {
String teamA = teamNames.getString("teamA");
final TextView teamAText = (TextView) findViewById(R.id.teamAText);
teamAText.setText(teamA);
String teamB = teamNames.getString("teamB");
final TextView teamBText = (TextView) findViewById(R.id.teamBText);
teamBText.setText(teamB);
}
}
I've also tried coding default strings in the XML, which hasn't been effective (only one team included for brevity):
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:padding="16dp"
android:text="#string/team_a_name"
android:id="#+id/teamAText"
android:textColor="#android:color/black"
android:textSize="14sp" />
Is there a way to effectively set a default when .getIntent().getExtras() is null?
A String from EditText is never null. It can be empty but not null.
A simple check like this would work
teamAText.setText(!teamA.isEmpty() ? teamA : "Team A");
Try this:
public void onClick(View view) {
Intent i = new Intent(this, ScoreKeeper.class);
final EditText teamAInput = (EditText) findViewById(R.id.team_a_input);
String teamAName = teamAInput.getText().toString();
if(teamAName.trim().equals("")) teamAName="Team A";
i.putExtra("teamA", teamAName);
final EditText teamBInput = (EditText) findViewById(R.id.team_b_input);
String teamBName = teamBInput.getText().toString();
if(teamBName.trim().equals("")) teamBName="Team B";
i.putExtra("teamB", teamBName);
startActivity(i);
}
The strings will not be null, nor will the intent necessarily. The strings will be zero length strings, which you can use String.isEmpty() to test against.
Try to change this:
teamAText.setText(getString(R.string.team_a_name));
teamBText.setText(getString(R.string.team_b_name));
to this:
teamAText.setText(R.string.team_a_name);
teamBText.setText(R.string.team_b_name);
It is because getString needs an int as parameter and your R.string.team_a_name and R.string.team_b_name are Strings so you don't have to convert it again (Further that they are not ints).
I expect it will be helpful for you!

Dialog not scrollable when fill the screen

I'm working on an android app. In one of the activities, I have a list of services and I want the user to rate each service. The services are in a TableLayout (each service in its own row). At the end of the row, I have a Rate button. When the user click on it, a Dialog pops up with ratingBar, EditView and two buttons at the bottom. My problem is that when the keyboard pops up on the button, and the user writes few lines in the EditText box, the keyword hides the buttons. Therefore, the user can't press the buttons, the user needs to minimize the keyboard in order to see the buttons.
Now, I saw few questions about the topic, but all of them had xml solutions. In my case, the dialog is all code, I don't use xml layout at this case. (I'm not sure it's the right way, but it works for my needs)
Here is a picture
This is the code of the dialog. This is what happen when clicking on the rate button.
Any ideas?
e.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean same = false;
TableRow row = new TableRow(QAListActivity.this);
RatingBar ratingBar = new RatingBar(QAListActivity.this);;
Dialog rankDialog = new Dialog(QAListActivity.this);
rankDialog.setContentView(R.layout.qa_rate);
rankDialog.setCancelable(true);
rankDialog.setCanceledOnTouchOutside(true);
TableLayout table1 = new TableLayout(QAListActivity.this);
ArrayList<RatingBar> ratingBars = new ArrayList<RatingBar>();
EditText comment = new EditText(QAListActivity.this);
for(int z = 0; z < tour.QAList.size(); z++){
if(tour.QAList.get(z).getServiceType().equalsIgnoreCase(tour.voucherList.get(position).getServiceType())){
rankDialog.setTitle("Rate " + tour.voucherList.get(position).getDescription());
same = true;
row = new TableRow(QAListActivity.this);
TextView text = new TextView(QAListActivity.this);
ratingBar = new RatingBar(QAListActivity.this);
ratingBars.add(ratingBar);
text.setText(tour.QAList.get(z).getQualityDesc());
text.setTextSize(20);
text.setHeight(40);
text.setGravity(Gravity.CENTER_VERTICAL);
row.addView(text);
row.addView(ratingBar);
row.setGravity(Gravity.CENTER);
table1.addView(row,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tour.voucherList.get(position).voucher_rating.add(tour.QAList.get(z));
}
}
if(same){
String type = tour.voucherList.get(position).getServiceType();
if (type.equalsIgnoreCase("CNV")){
String[] qa_bus = {"Bus Make","Bus Year","Number of Seats","Bus Company","Bathroom on Bus?","Driver's Name",
"Driver speaks English","Helpfulness of driver (on/off bus)","Were there Gate1 signs on the bus?"};
TableLayout table_bus = new TableLayout(QAListActivity.this);
for(int count = 0; count < qa_bus.length; count++){
TableRow row_make = new TableRow(QAListActivity.this);
EditText make = new EditText(QAListActivity.this);
make.setHint(qa_bus[count]);
make.setWidth(table.getWidth()/2+50);
row_make.addView(make);
row_make.setGravity(Gravity.CENTER);
table_bus.addView(row_make, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT));
}
table1.addView(table_bus);
}
else{
TableLayout table_comment = new TableLayout(QAListActivity.this);
TableRow row_comment = new TableRow(QAListActivity.this);
comment = new EditText(QAListActivity.this);
comment.setHint("Remarks");
comment.setWidth(table.getWidth()/2+50);
row_comment.addView(comment);
row_comment.setGravity(Gravity.CENTER);
table_comment.addView(row_comment, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT));
table1.addView(table_comment);
}
TableLayout table_buttons = new TableLayout(QAListActivity.this);
TableRow save_row = new TableRow(QAListActivity.this);
Button save = new Button(QAListActivity.this);
save.setText("Save");
save_row.addView(save);
save_row.setGravity(Gravity.CENTER);
final Dialog rankDialogTemp = rankDialog;
final ArrayList<RatingBar> ratingBarsTemp = ratingBars;
final EditText remarksTemp = comment;
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int xx = 0; xx < ratingBarsTemp.size(); xx++){
Log.d("ratingBar", "" + ratingBarsTemp.get(xx).getRating());
tour.voucherList.get(position).voucher_rating.get(xx).setRating(ratingBarsTemp.get(xx).getRating());
}
tour.voucherList.get(position).setQAcompleted(true);
tour.voucherList.get(position).setRemarks(remarksTemp.getText().toString());
rowTemp.setBackgroundColor(Color.GREEN);
getInfo.saveOfflineData(QAListActivity.this, new Gson().toJson(TourListActivity.TourList), DateFormat.getDateTimeInstance().format(new Date()));
rankDialogTemp.dismiss();
}
});
Button back = new Button(QAListActivity.this);
back.setText("Back");
save_row.addView(back);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialogTemp.dismiss();
}
});
table_buttons.addView(save_row);
table1.addView(table_buttons);
}
rankDialog.addContentView(table1, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
My qa_rate.xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/qa_rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableLayout
android:id="#+id/rating"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:stretchColumns="*"
android:paddingRight="5dp"
android:orientation="vertical" >
</TableLayout >
</ScrollView>
Maybe play with the windowSoftInputMode
http://developer.android.com/guide/topics/manifest/activity-element.html#wsoft
Or maybe put your buttons in a scroll view so the user can scroll down to it.

Categories

Resources