public class Cari extends AppCompatActivity implements TextWatcher,View.OnClickListener {
TextView hasil, teks, teks2;
AutoCompleteTextView edit;
Button prev, terpilih;
String[] item = { "Matahari","Merkurius","Venus","Bumi","Mars","Yupiter","Saturnus","Uranus","Neptunus" };
hasil = findViewById(R.id.hasil);
edit = findViewById(R.id.edit);
edit.addTextChangedListener(this);
edit.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item));
teks = findViewById(R.id.title);
Typeface customfont = Typeface.createFromAsset(getAssets(), "font/Starjout.ttf");
teks.setTypeface(customfont);
teks2 = findViewById(R.id.titleDes);
Typeface customfont2 = Typeface.createFromAsset(getAssets(), "font/Starjout.ttf");
teks2.setTypeface(customfont2);
terpilih = findViewById(R.id.pilih);
terpilih.setOnClickListener(this);
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
edit.getText();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//not used
}
public void afterTextChanged(Editable s) {
//not used
}
public void onClick(View a) {
switch (a.getId()) {
case R.id.pilih:
Toast.makeText(this, "Kamu memilih Planet "+edit.getText(), Toast.LENGTH_SHORT).show();
mpilih();
break;
}
}
private void mpilih() {
if (//what statement should add) {
//here too *hasil.setText();
}
else {
//here too
}
}
How to make if else statement and set TextView hasil to get res/value/string name sun
this my first time programming using android studio, so i don't know too much about java mobile code. And sorry for bad English. Hope you understand
Use getText() to get AutoCompleteTextView value.
Here's the example of checking condition if AutoCompleteTextView is empty.
private void mpilih() {
if (!TextUtils.isEmpty(edit.getText())) {
hasil.setText(getString(R.string.sun));
} else {
edit.setError("Please enter your selection");
}
}
If you're using only those fixed item as selection, i suggest you use Spinner instead..
EDIT
For multiple 'if' you can use it like this
if (edit.getText().equals("Matahari")) {
hasil.setText(getString(R.string.sun));
} else if (edit.getText().equals("Bumi"){
hasil.setText(getString(R.string.earth));
}
Related
based on the image below, I have NIK & NAMA fields. the concept is when I fill in the NIK field then I press the GET button it will display the name(NAMA FIELD)
Picture : Menu add
Database structure example
NIK
NAMA
96296
Farrasta
94878
Alfian
Java class
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NikKry = etNik.getText().toString();
getNama(); // THE FUNCTION
}
});
private void getNama(){
APIRequestData armNama = RetroMaster.konekRetrofit().create(APIRequestData.class);
Call<ResponseMaster> tampilNama = armNama.ardGetNama(NikKry);
tampilNama.enqueue(new Callback<ResponseMaster>() {
#Override
public void onResponse(Call<ResponseMaster> call, Response<ResponseMaster> response) {
// HOW TO CODE PROPERLY ?
}
#Override
public void onFailure(Call<ResponseMaster> call, Throwable t) {
}
});
}
PHP file
<?php
include ("koneksi.php");
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$NIK = $_POST["NIK"];
$query = "SELECT NAMA FROM MASTER_KRY WHERE NIK = '$NIK'";
$eksekusi = oci_parse($conn, $query);
$cek = oci_execute($eksekusi);
if($cek > 0){
$response["data"] = array();
while($ambil = oci_fetch_object($eksekusi)){
$F["NAMA"] = $ambil->NAMA;
array_push($response["data"], $F);
}
}else{
$response["pesan"] = "Data tidak tersedia";
}
}
else{
$response["pesan"] = "*&*%4668%*%^$%#*&*(()%$!##%";
}
echo json_encode($response);
oci_close($conn);
?>
If you used EditText then this method will be help you to notify when text change in EditText.
editTextObject.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// here you get text via "s.toString();"
NikKry = s.toString();
getNama();
}
});
If you used AutoCompleteTextView then this method will be help you like:
autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
NikKry = yourArrayList.get(position).getText().toString();
getNama();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
This depends on your entity of ResponseMaster. If the entity has field Nama and getter setter exists, you can use below:
if(response.isSuccessful()){
edNama.setText(response.body().getNama());
}else{
// show toast or log error
}
I am making a multiple choice app in which the questions are displayed in recyclerview with arraylist. And also the buttons to choose your answer. And get Right answers from sqlite and do if condition with the user input answers to calculate marks in each question. like this....
My problem is i have no idea how to calculate marks with the user input (clicked buttons bta1 true, bta1 false, etc....) when clicked finish button (that is in main activity).
i want to calculate marks in each question, total 5marks for each question. If i clicked finish button and if there is 10 questions and all user input answers are right, the total marks should be 50marks.
This is my recyclerview adapter class
public class Rvadapter extends RecyclerView.Adapter <Rvadapter.MyViewHolder> {
private Context context;
Activity activity;
MyDatabaseHelper myDB;
String questiontitle, question1, question2, question3, question4, question5, answer1, answer2, answer3, answer4, answer5;
String answerdb1, answerdb2, answerdb3, answerdb4, answerdb5;
Cursor cursor;
ArrayList<ItemList> arlist;
int marks, totalmark;
private ArrayList arquestiontitle, arquestion1, arquestion2, arquestion3, arquestion4, arquestion5, aranswer1, aranswer2, aranswer3, aranswer4, aranswer5, armarks;
String idtosee, orderid, orderdate, customername, customeraddress, customerphone, delifee, advance, tax, discount, itemname, itemcount, itemprice, mark;
int a;
Rvadapter(Activity activity, Context context, ArrayList arquestiontitle, ArrayList arquestion1, ArrayList arquestion2, ArrayList arquestion3, ArrayList arquestion4, ArrayList arquestion5, ArrayList aranswer1, ArrayList aranswer2, ArrayList aranswer3, ArrayList aranswer4, ArrayList aranswer5, ArrayList armarks){
this.activity = activity;
this.context = context;
this.arquestiontitle = arquestiontitle;
this.arquestion1 = arquestion1;
this.arquestion2 = arquestion2;
this.arquestion3 = arquestion3;
this.arquestion4 = arquestion4;
this.arquestion5 = arquestion5;
this.aranswer1 = aranswer1;
this.aranswer2 = aranswer2;
this.aranswer3 = aranswer3;
this.aranswer4 = aranswer4;
this.aranswer5 = aranswer5;
this.armarks = armarks;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardlayoutquestion, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.tvquestiontitle.setText(String.valueOf(arquestiontitle.get(position)));
holder.tvquestion1.setText(String.valueOf(arquestion1.get(position)));
holder.tvquestion2.setText(String.valueOf(arquestion2.get(position)));
holder.tvquestion3.setText(String.valueOf(arquestion3.get(position)));
holder.tvquestion4.setText(String.valueOf(arquestion4.get(position)));
holder.tvquestion5.setText(String.valueOf(arquestion5.get(position)));
holder.tvquestionid.setText(String.valueOf(position+1+". "));
marks = Integer.parseInt(String.valueOf(armarks.get(position)));
answerdb1 = String.valueOf(aranswer1.get(position));
answerdb2 = String.valueOf(aranswer2.get(position));
answerdb3 = String.valueOf(aranswer3.get(position));
answerdb4 = String.valueOf(aranswer4.get(position));
answerdb5 = String.valueOf(aranswer5.get(position));
holder.bta1true.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer1 == null){
answer1 = "T";
holder.bta1true.setBackgroundResource(R.drawable.selected120);
holder.bta1false.setBackgroundResource(R.drawable.unselected120);
}else if ( answer1.equals("F")){
answer1 = "T";
holder.bta1true.setBackgroundResource(R.drawable.selected120);
holder.bta1false.setBackgroundResource(R.drawable.unselected120);
}else {
answer1 = null;
holder.bta1true.setBackgroundResource(R.drawable.unselected120);
}
}
});
holder.bta1false.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer1 == null){
answer1 = "F";
holder.bta1false.setBackgroundResource(R.drawable.selected120);
holder.bta1true.setBackgroundResource(R.drawable.unselected120);
}else if ( answer1.equals("T")){
answer1 = "F";
holder.bta1true.setBackgroundResource(R.drawable.unselected120);
holder.bta1false.setBackgroundResource(R.drawable.selected120);
}else {
answer1 = null;
holder.bta1false.setBackgroundResource(R.drawable.unselected120);
}
}
});
}
private void checkmarks() {
if(answer1!=null){
if(answer1.equals(answerdb1)){
marks++;
}else {
marks--;
}
}
if(answer2!=null){
if(answer2.equals(answerdb2)){
marks++;
}else{
marks--;
}
}
if(answer3!=null){
if(answer3.equals(answerdb3)){
marks++;
}else{
marks--;
}
}
if(answer4!=null){
if(answer4.equals(answerdb4)){
marks++;
}else{
marks--;
}
}
if(answer5!=null){
if(answer5.equals(answerdb5)){
marks++;
}else{
marks--;
}
}
if(marks<0){
marks=0;
}
}
#Override
public int getItemCount() {
return arquestiontitle.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvquestiontitle, tvquestion1, tvquestion2, tvquestion3, tvquestion4, tvquestion5, tvquestionid, tvmarks;
Button bta1true, bta1false, bta2true, bta2false, bta3true, bta3false, bta4true, bta4false, bta5true, bta5false;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvquestiontitle = itemView.findViewById(R.id.tvquestiontitle);
tvquestion1 = itemView.findViewById(R.id.tvquestion1);
tvquestion2 = itemView.findViewById(R.id.tvquestion2);
tvquestion3 = itemView.findViewById(R.id.tvquestion3);
tvquestion4 = itemView.findViewById(R.id.tvquestion4);
tvquestion5 = itemView.findViewById(R.id.tvquestion5);
tvquestionid = itemView.findViewById(R.id.tvquestionid);
tvmarks = itemView.findViewById(R.id.tvmarks);
bta1true = itemView.findViewById(R.id.bta1true);
bta1false = itemView.findViewById(R.id.bta1false);
bta2true = itemView.findViewById(R.id.bta2true);
bta2false = itemView.findViewById(R.id.bta2false);
bta3true = itemView.findViewById(R.id.bta3true);
bta3false = itemView.findViewById(R.id.bta3false);
bta4true = itemView.findViewById(R.id.bta4true);
bta4false = itemView.findViewById(R.id.bta4false);
bta5true = itemView.findViewById(R.id.bta5true);
bta5false = itemView.findViewById(R.id.bta5false);
}
}
}
Please help me... how to calculate marks of each question (recycler cardview items) and Sum together all of those.. I can manage to get them with only one question at a time with next button, but this time i want to show all questions within the recyclerview..
Use checkboxes instead
First of all. If the user inputs (answers in this case) are Boolean type then you should use checkboxes instead of buttons (much easier to deal with).
The layout will looks something like that:
You can stick with buttons if you want
Create a class to store answers
Then make a class to store answers in it (let call it `Answer`)
public class Answer {
private int questionNumber;//number of the question
private Boolean bta1, bta2, bta3, bta4, bta5;//answers
public Answer() {
}
public Answer(int questionNumber, Boolean bta1, Boolean bta2, Boolean bta3, Boolean bta4, Boolean bta5) {
this.questionNumber = questionNumber;
this.bta1 = bta1;
this.bta2 = bta2;
this.bta3 = bta3;
this.bta4 = bta4;
this.bta5 = bta5;
}
public int getQuestionNumber() {
return questionNumber;
}
public void setQuestionNumber(int questionNumber) {
this.questionNumber = questionNumber;
}
public Boolean getBta1() {
return bta1;
}
public void setBta1(Boolean bta1) {
this.bta1 = bta1;
}
public Boolean getBta2() {
return bta2;
}
public void setBta2(Boolean bta2) {
this.bta2 = bta2;
}
public Boolean getBta3() {
return bta3;
}
public void setBta3(Boolean bta3) {
this.bta3 = bta3;
}
public Boolean getBta4() {
return bta4;
}
public void setBta4(Boolean bta4) {
this.bta4 = bta4;
}
public Boolean getBta5() {
return bta5;
}
public void setBta5(Boolean bta5) {
this.bta5 = bta5;
}
}
Create an object for each question
and create object for each question in the MainActivity
public class MainActivity extends AppCompatActivity {
ArrayList<Answer> answers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeAnswers();
.
.
.
}
// here we create object for each question and make it default value all false
public void initializeAnswers(){
for (int i=1;i<=20;i++){//replace 20 with how many questions you have
answers.add(new Answer(i,false,false,false,false,false));
}
}
// this is the methode that will be called when the user press a checkbox(change its value)
public void setQuestionResult(int questionNumber, int optionNumber, boolean value){
switch (optionNumber){
case 1:
answers.get(questionNumber+1).setBta1(value);
break;
case 2:
answers.get(questionNumber+1).setBta2(value);
break;
case 3:
answers.get(questionNumber+1).setBta3(value);
break;
case 4:
answers.get(questionNumber+1).setBta4(value);
break;
case 5:
answers.get(questionNumber+1).setBta5(value);
break;
}
}
}
Catch user inputs
After that we gonna set click listener to each button(or checkbox) in the recyclerview items, so when the user chose an answer we store it in the objects we made before.
We'll do that in the `ViewHolder`
class MyViewHolder extends RecyclerView.ViewHolder {
int questionNumber;
TextView tvquestiontitle, tvquestion1, tvquestion2, tvquestion3, tvquestion4, tvquestion5, tvquestionid, tvmarks;
CheckBox bta1, bta2, bta3, bta4, bta5;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvquestiontitle = itemView.findViewById(R.id.tvquestiontitle);
tvquestion1 = itemView.findViewById(R.id.tvquestion1);
tvquestion2 = itemView.findViewById(R.id.tvquestion2);
tvquestion3 = itemView.findViewById(R.id.tvquestion3);
tvquestion4 = itemView.findViewById(R.id.tvquestion4);
tvquestion5 = itemView.findViewById(R.id.tvquestion5);
tvquestionid = itemView.findViewById(R.id.tvquestionid);
tvmarks = itemView.findViewById(R.id.tvmarks);
bta1 = itemView.findViewById(R.id.bta1);
bta2 = itemView.findViewById(R.id.bta2);
bta3 = itemView.findViewById(R.id.bta3);
bta4 = itemView.findViewById(R.id.bta4);
bta5 = itemView.findViewById(R.id.bta5);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Is the view now checked?
boolean checked = ((CheckBox) v).isChecked();
int optionNumber;// e.g "1 is A" "2 is B" etc..
//get option number form the view id
switch (v.getId()) {
case R.id.bta1:
optionNumber = 1;
break;
case R.id.bta2:
optionNumber = 2;
break;
case R.id.bta3:
optionNumber = 3;
break;
case R.id.bta4:
optionNumber = 4;
break;
case R.id.bta5:
optionNumber = 5;
break;
default:
optionNumber = 0;
}
// here we will pass the changes to setQuestionResult to the Activity to process it
((MainActivity)context).setQuestionResult(questionNumber,optionNumber,checked);
}
};
bta1.setOnClickListener(onClickListener);
bta2.setOnClickListener(onClickListener);
bta3.setOnClickListener(onClickListener);
bta4.setOnClickListener(onClickListener);
bta5.setOnClickListener(onClickListener);
}
}
You may realize that I added an parameter in the top (int questionNumber;), that's gonna identify what question we're dealing with.
You also need to set a value for this parameter in onBindViewHolder.
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.questionNumber = position+1;//add one because the position of the first item is 0
.
.
.
}
Calculate marks of each question
Finally. when you want calculate marks of a question, the result is stored in answers to get it just call
answers.get(questioNumber+1)//add one because the index always start from 0
One Last thing. You may face a problem when changing the state of an item in recyclerview, so when you scroll down the first items became invisible and the recyclerview recycle those items, so any changes happened (e. g checking a checkbox) will be lost, and the items will reset to the first state.
If that happened check this solution
Update
As I mentioned before, you can still do it with buttons if you want or any input type you find it better
The only thing you need to change is the way of catching user inputs.
E.g. if you used buttons, you'll have 3 possible inputs:
True. If btn1 is pressed and btn2 is not
False. If btn1 in bot pressed bur btn2 in pressed
Neither. If btn1 and btn2 are not pressed
You can sill use Boolean type to store the input by putting null when the value is Neither true of false(e.g. bta1=null)
The problem with this method is that it's pretty complicated and confusing (but still possible)
So. My suggestion is to use 3 statues checkbox.
This is a third-party library witch you can add to your preject.
It's pretty much a checkbox with three stats
Checked
Unchecked
Indeterminate
You can find it here GitHub
And another one here GitHub
I have a form. I want to display a calculation in "live time" when the user enters different values into some int fields. I made my Activity implement the TextWatcher interface and set a listener on 3 different EditText fields but it appears the Textwatcher only detects the first EditText declared in the Activity's code.
You can see from the code below, I'm trying to grabe a few fields, convert them to ints and display the output in an EditText field at the bottom of the form. Where am I going wrong? Do I need to implement a textWatcher individually on all of the EditText fields involved? That would be a rather verbose solution making my code a lot longer than I would like
public class NewStageFormActivity extends AppCompatActivity implements TextWatcher{
Context mContext;
EditText mStageName, mPaperTargets, mHitsPerTarget, mSteelTargets, mSteelNPMs, mOutput;
Spinner mScoringType, mStrings;
CheckBox mNoShoots, mNPMs;
Button mSaveButton;
Match mGlobalMatch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage_form);
mContext = this;
mGlobalMatch = GlobalMatch.getMatch();
mStageName = (EditText)findViewById(R.id.stage_name_et);
mPaperTargets = (EditText)findViewById(R.id.paper_targets_et);
mHitsPerTarget = (EditText)findViewById(R.id.hits_per_target_et);
mSteelTargets = (EditText)findViewById(R.id.steel_targets_et);
mSteelNPMs = (EditText)findViewById(R.id.steel_npm_et);
mScoringType = (Spinner)findViewById(R.id.scoring_type_spinner);
mStrings = (Spinner)findViewById(R.id.strings_spinner);
mNoShoots = (CheckBox)findViewById(R.id.no_shoots_cb);
mNPMs = (CheckBox)findViewById(R.id.npm_cb);
mSaveButton = (Button)findViewById(R.id.save_button);
mOutput = (EditText)findViewById(R.id.output_et);
// paper * hitsPer + steel
mPaperTargets.addTextChangedListener(this);
mSteelTargets.addTextChangedListener(this);
mSteelTargets.addTextChangedListener(this);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mStageName.getText().toString().equals("") || mPaperTargets.getText().toString().equals("") ||
mHitsPerTarget.getText().toString().equals("") || mSteelTargets.getText().toString().equals("") ||
mSteelNPMs.getText().toString().equals("")){
Toast.makeText(mContext, "You must fill in all form fields", Toast.LENGTH_SHORT).show();
} else {
String name = mStageName.getText().toString();
String type = mScoringType.getSelectedItem().toString();
int strings = Integer.valueOf(mStrings.getSelectedItem().toString());
int paperTargets = Integer.valueOf(mPaperTargets.getText().toString());
int hitsPerTarget = Integer.valueOf(mHitsPerTarget.getText().toString());
boolean noShoots;
boolean npms;
if(mNoShoots.isChecked()){
noShoots = true;
} else {
noShoots = false;
}
if(mNPMs.isChecked()){
npms = true;
} else {
npms = false;
}
int steelTargets = Integer.valueOf(mSteelTargets.getText().toString());
int steelNPMs = Integer.valueOf(mSteelNPMs.getText().toString());
MatchStage matchStage = new MatchStage(name, type, strings, paperTargets, hitsPerTarget,
noShoots, npms, steelTargets, steelNPMs);
mGlobalMatch.getStages().add(matchStage);
String jsonString = new Gson().toJson(mGlobalMatch);
MatchHelper.updateFile(mContext, MatchHelper.createFileName(mGlobalMatch.getMatchId()),
jsonString);
Intent intent = new Intent(mContext, StagesListActivity.class);
startActivity(intent);
}
}
});
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int paper = Integer.valueOf(mPaperTargets.getText().toString());
int hitsPer = Integer.valueOf(mHitsPerTarget.getText().toString());
int steel = Integer.valueOf(mSteelTargets.getText().toString());
int minRound = (paper * hitsPer) + steel;
int points = minRound * 5;
mOutput.setText("Minimum rounds: " + (minRound) + "\t\t Points: " + points);
}
#Override
public void afterTextChanged(Editable editable) {
}
}
In my experience I've had issues with using the same TextWatcher on multiple EditText. You could get around this by creating a method that produces a new instance of TextWatcher for each EditText so your code isn't all verbose. Try something like this:
Get rid of implements TextWatcher for your Activity and it's associated methods. Implement a method createTextWatcher():
private TextWatcher createTextWatcher() {
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Copy your original code
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Copy your original code
}
#Override
public void afterTextChanged(Editable editable) {
// Copy your original code
}
};
}
Now to use it like this:
mPaperTargets.addTextChangedListener(createTextWatcher());
mSteelTargets.addTextChangedListener(createTextWatcher());
The most up-voted answer on #Natan Felipe's link also demonstrates using one instance of TextWatcher per EditText.
I'm trying to wrote android program which displays Greatest Common Divisor of two integers specified in two different EditText fields. First I've done it with button, everything worked (you can see onclick listener commented out in code below). Now I want to do this: app checks when both EditTexts are not empty and then automatically starts calculating and shows gcd. Buty app crashes when I start typing in any of EditText fields. Also I tried to add TextChangeListener only on one of EditTexts. Everything is good until I delete all input from one of the fields, then app crashes again. I'm only starting to understand android development and made this app mostly by modifying examples found on internet so maybe I did something wrong... Can anyone help me? Thanks
MainActivity.java
public class MainActivity extends Activity
{
EditText a;
EditText b;
TextView gcdResult;
Button calculateGcd;
int a, b, gcdValue
TextWatcher textWatcher = new TextWatcher(){
#Override
public void afterTextChanged(Editable s){}
#Override
public void beforeTextChanged(CharSequence s,int start, int count, int after){}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
AutoCalculateGcd();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a = (EditText)findViewById(R.id.aText1);
b = (EditText)findViewById(R.id.bText1);
gcdResult = (TextView)findViewById(R.id.resultTextView1);
calculateGcd = (Button)findViewById(R.id.calcButton1);
/* calculateGcd.setOnClickListener(new OnClickListener(){
public void onClick(View v){
AutoCalculateRatio();
}
});*/
a.addTextChangedListener(textWatcher);
b.addTextChangedListener(textWatcher);
}
//Euclidean alghorithm to find gcd
public static int gcd(int a, int b) {
if (b == 0) return w;
else return gcd(b a % b);
}
public static boolean isInputNotEmpty(EditText a, EditText b){
String a = a.getText().toString();
String b = b.getText().toString();
if(a.equals("") && b.equals("") ){
return false;
}
else{
return true;
}
}
public void AutoCalculateGcd(){
if(isInputNotEmpty(a, b)){
a = Integer.parseInt(width.getText().toString());
b = Integer.parseInt(height.getText().toString());
gcdValue = gcd(a, b);
ratioResult.setText(Integer.toString(gcdValue));
}
else{
//Toast.makeText(this, "No input", Toast.LENGTH_SHORT).show();
}
}
}
Actually, you should replace
public static boolean isInputNotEmpty(EditText a, EditText b) {
String a = a.getText().toString();
String b = b.getText().toString();
if (a.equals("") && b.equals("")) {
return false;
}
else {
return true;
}
}
with
public static boolean isInputNotEmpty(EditText a, EditText b) {
String a = a.getText().toString();
String b = b.getText().toString();
if (a.equals("") || b.equals("")) {
return false;
}
else {
return true;
}
}
Or even
public static boolean isInputNotEmpty(EditText a, EditText b) {
return !(a.getText().toString().isEmpty() || b.getText().toString().isEmpty());
}
Because you want to know if any ( || ) of them is empty, not if both (&&) are.
It might help if you post the stacktrace, but my guess is that you are getting a NumberFormatException from the Integer.parseInt() calls. One approach would be to do something like:
try {
a = Integer.parseInt(width.getText().toString());
b = Integer.parseInt(height.getText().toString());
gcdValue = gcd(a, b);
ratioResult.setText(Integer.toString(gcdValue));
} catch ( NumberFormatException e) {
ratioResult.setText("N/A")
}
I'm having problems to get the position of my View inside a ListView when TextWatcher triggers for changes in EditText.
Each CardView has two EditTexts and two Spinners. When I make some change in the values for the name of the product (the EditText in the left) and for the spinners, my code get the correctly the position of the CardView in the list.
However, when I change the value of the price by typing it, my code cannot get it's position.
The position of the CardView is gotten in the line...
final int posicao = Integer.parseInt(consumableInfo.getName()), which consumableInfo is the class listed in my Adapater, and consumableInfo.getName gets the name of the card, which is equal to the position of the card. Like "0", "1", "2"...
This happens because everytime I call...
holder.mAutoCompleteTextView.setOnItemClickListener for the AutoCompleteEditText on the left;
holder.mDivideConsumableSpinner.setOnItemSelectedListener for each spinner;
...my code iterates again over BindData. However, when I call...
holder.mConsumablePriceTextView.addTextChangedListener(priceTextWatcher) for the EditText on the right;
... my code DO NOT iterates again.
I'm trying to find another way to get it's position, but I'm having problems with that. Maybe forcing a way to posicao get the value, or creating a customTextWatcher that implements TextWatcher and gets consumableInfo as a parameter.
public class ConsumableAdapter extends RecyclerView.Adapter<ConsumableAdapter.ConsumableViewHolder> {
/*...some code ommited...*/
int posicaoGlobal;
public ConsumableAdapter(Context context, List<ConsumableInfo> contactList) {...}/*...some code ommited...*/
}
public class ConsumableViewHolder extends RecyclerView.ViewHolder {
public AutoCompleteTextView mAutoCompleteTextView;
public Spinner mDivideConsumableSpinner;
public Spinner mUnitsConsumableSpinner;
public EditText mConsumablePriceTextView;
public ConsumableViewHolder(View itemView) {
/*...*/
}
public void bindData(ConsumableInfo consumableInfo, ConsumableViewHolder holder, Context context) {
final int posicao = Integer.parseInt(consumableInfo.getName());
posicaoGlobal = posicao;
ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.select_dialog_item,
Constants.CONSUMABLE_CONSTANTS);
holder.mAutoCompleteTextView.setAdapter(adapter);
/* position is updated withmAutoCompleteTextView.setOnItemClickListener */
holder.mAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener({
updateTotalPrice(posicao);
/*...*/
});
/*position is NOT updated with addTextChangedListener*/
holder.mConsumablePriceTextView.addTextChangedListener(priceTextWatcher);
/*position is updated with setOnItemSelectedListener in both Spinners*/
holder.mDivideConsumableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
updateTotalPrice(posicao);
/*...*/
});
//product units
holder.mUnitsConsumableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
updateTotalPrice(posicao);
/*...*/
});
}
private void updateTotalPrice(int posicao) {
/*...*/
mTotalPrice = getTotalPrice(BotequimActivity.mProductList, mPercent);
BotequimActivity.mTotalPriceTextView.setText(getTotalPriceString());
FormatStringAndText.setPriceTextViewSize(mTotalPrice, BotequimActivity.mTotalPriceTextView);
}
}
private void updateTotalPrice(int posicao, String priceString) {
/*...*/
BotequimActivity.mTotalPriceTextView.setText(getTotalPriceString());
FormatStringAndText.setPriceTextViewSize(mTotalPrice, BotequimActivity.mTotalPriceTextView);
}
private final TextWatcher priceTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (count != 0) {
if (FormatStringAndText.isNumeric(s.toString())) {
mProductPriceBeforeChange = Double.parseDouble(s.toString());
}
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Toast.makeText(mContext, "posicao =" + posicaoGlobal, Toast.LENGTH_SHORT).show();
if (s.toString().length() == 0) {
updateTotalPrice(posicaoGlobal, "0.00");
} else {
if (!isAutoCompleteClicked) {
if (FormatStringAndText.isNumeric(s.toString())) {
mProductPriceAfterChange = Double.parseDouble(s.toString());BotequimActivity.mTotalPriceTextView.setText(getTotalPriceString());
// FormatStringAndText.setPriceTextViewSize(mTotalPrice, BotequimActivity.mTotalPriceTextView);
updateTotalPrice(posicaoGlobal, s.toString());
} else {
}
} else {
isAutoCompleteClicked = false;
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
public Double getTotalPrice(ArrayList<Product> productList, Double percent) {
mTotalPrice = 0;
for (Product product : productList) {
mTotalPrice = mTotalPrice + percent * (product.getUnits() * (product.getDoublePrice()) / product.getDividedBy());
}
return mTotalPrice;
}
}
You need to save the position when you create the TextWatcher. I would do this with an inner subclass:
// this is an inner class so it will have an implicit reference to
// the adapter (ConsumableAdapter.this)
public class PriceTextWatcher implements TextWatcher {
private int mPos;
public PriceTextWatcher(int position) {
super();
mPos = position;
}
// now add your TextWatcher implementation here and use mPos for position
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ...
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ...
}
#Override
public void afterTextChanged(Editable s) {}
}
Now you can initialize the position when you create the TextWatcher:
holder.mConsumablePriceTextView.addTextChangedListener(new PriceTextWatcher(posicao));
You will have multiple TextWatchers instead of the single final TextWatcher you currently have, but that's the trade-off for getting the position value where it needs to be.
Solved. I had to call priceTextWatcher as an argument with it's constructor, just like AdapterView.OnItemSelectedListener(). The correct one is:
holder.mConsumablePriceTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//...
}
//...methods inside here
}