Empty EditText return string into name, id - android

I am trying to get the string of the EditText and if it is " I want to get " also but the string is appearing this in the EditText
android.support.v7.widget.AppCompatEditText{42e33310 VFED..CL .F ....ID40,40-1160,315 #7f0c006f app:id\CalculatorDisplay}
after getting it and giving it to the EditText again
and here is a part of the onClick that works when I press a button and the rest of it is not dealing with this problem the problem is in NoRepeatNumber as I tested that when I get it in TestTV TextView I saw the code above
public void onClick(View view) {
TestTV.setText("enterd ");
String buttonPressed = ((Button) view).getText().toString();
PublicButtonPressed = buttonPressed;
if (DIGITS.contains(buttonPressed)) {
SinOrNumber=2;
TestTV.append("numbering");
// digit was pressed
if (!Started) {
mCalculatorDisplay.setText("");
TestTV.append("\nenterd setText");
} else {
TestTV.append("\nenterd setText eslse");
}
if (Started) {
OperationEnded = true;
}
if (NumberingEnded) {
FullNumber = String.valueOf(Number[Ni]);
Ni++;
NumberingEnded = false;
FullCalculation= FullNumber + " ";
NoRepeatNumber="";
DisplayCalculations();
}
FullNumber = FullNumber + buttonPressed;
Number[Ni] = Integer.parseInt(FullNumber);
TestTV.append("\nNumber[" + Ni + "] =" + + Number[Ni] + "\n" + "buttonPressed =" + buttonPressed + "\nFullNumber =" + FullNumber);
//DisplayCalculations();
if ("".equals(mCalculatorDisplay)) {
TestTV.append("\nentered equal\"\"");
NoRepeatNumber="";
} else {
if (NoRepeatNumber == "") {
NoRepeatNumber = String.valueOf(mCalculatorDisplay);
TestTV.append("\nNoRepeatNumber =" + NoRepeatNumber);
}
}
if(!NumberingEnded){
mCalculatorDisplay.setText(NoRepeatNumber + FullNumber);
}
if (!Started) {
Started = true;
}
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
Number[Ni] = Integer.parseInt(FullNumber);
}
}
userIsInTheMiddleOfTypingANumber = true;
} else {}}

Call mCalculatorDisplay.getText().toString() instead of String.valueOf(mCalculatorDisplay).
I guess mCalculatorDisplay is an EditText?
Update: NoRepeatNumber = String.valueOf(mCalculatorDisplay); - this is the problem part

Related

Simple Math Game?

I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});

My Toast doesn't appear

I don't know why but the toast doesn't appear when I run the program. This is my code:
class Number {
int number;
public boolean isSquare() {
double squareRoot = Math.sqrt(number);
if (squareRoot==Math.floor(squareRoot)) {
return true;
} else {
return false;
}
}
public boolean isTriangular() {
int x = 1;
int triangularNumber = 1;
while(triangularNumber<number) {
x++;
triangularNumber = triangularNumber + x;
}
if (triangularNumber == number) {
return true;
} else {
return false;
}
}
}
public void idButton (View view) {
EditText inputNumber = (EditText) findViewById(R.id.inputNumber);
Number myNumber = new Number();
myNumber.number = Integer.parseInt(inputNumber.getText().toString());
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = myNumber.number + " your number is triangular and square";
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
After compiling there's no error in the code, please guide me what should be improved on the code since I'm still beginner. Could you help me? Thanks.
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = myNumber.number + " your number is triangular and square";
}
}
In this code, you haven't write any else statement. What if the number is neither square nor triangular? In both of these scenerios you will get an empty message as you have declared message = "";
So write your code as
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = message+myNumber.number + " your number is triangular and square";
}
else
{
message = message+"No triangular";
}
}
else
{
message = message+"No square";
}

Rfid card reader value android detecting twice

I am trying to make an android app for RFID card reader (i am not using NFC), for this i connect one high frquency RFID card reader through OTG cable and i am using EditText where card number is displaying. it is working fine, but problem is sometime it detects multiple time card number.
1- Any idea how can i resolve this (i cannot put size limit condition because card number length is not fixed)?
2- One more problem when i am using ultra high frequency card reader then card is showing different value, any idea how can i make an android app which supports both frequency card readers.
Rfid continue reading tag its not one time reading so from this repetition you have to manage to your side. Check its reading data or not if yes then ignore.Below the call Where implement Rfid methods and its reading data handle.
public class ReaderListener implements RfidEventListener {
private RfidReader reader;
private ReadInventory eventForm;
//private ItemTransfer eventFormitm;
private final ToneGenerator tg = new ToneGenerator(5, 100);
private boolean isEnabled;
private Map<String, Long> scannedItemsMap = new TreeMap<String, Long>();
public ReaderListener(ReadInventory frm, String make, String macid) throws ReaderConnectionException, LicenseExpiryException, IOException, GeneralSecurityException {
Log.d("Test1", " "+make.toString().trim()+" "+ macid.toString().trim());
reader = RfidFactory.getInstance().getRfidReader(make.toString().trim(), macid.toString().trim(),
PlatformConnector.AndroidConnector.getPlatformName());
Log.d("Test2", " "+reader+" ");
//reader.removeAllListeners();
reader.registerListener(this);
setEnabled(true);
this.eventForm = frm;
}
#Override
public void handleData(String tagid, int arg1, int arg2) {
synchronized (scannedItemsMap) {
if (!scannedItemsMap.containsKey(tagid)) {
System.out.println("got data............ :" + tagid);
scannedItemsMap.put(tagid, System.currentTimeMillis());
if (eventForm != null) {
eventForm.handleData(tagid);
//this.tg.startTone(25);
Log.d("tagid", " " + tagid + " ");
}
/*if (eventFormitm != null) {
eventFormitm.handleData(tagid);
}*/
} else if (scannedItemsMap.containsKey(tagid)) {
scannedItemsMap.put(tagid, System.currentTimeMillis());
}
}
}
#Override
public void handleError(String msg) {
if (eventForm != null) {
eventForm.handleError(msg);
}
}
#Override
public boolean isEnabled() {
return isEnabled;
}
#Override
public void setEnabled(boolean arg0) {
this.isEnabled = arg0;
}
public boolean startScan(int power,int speed) throws ReaderConnectionException {
if (reader != null && !reader.isScanning()) {
reader.setSession(RfidSession.ONE);
reader.setPower(power);
reader.setScanSpeed(speed);
reader.startScan();
}
return true;
}
public void stopScan() throws ReaderConnectionException {
if (reader.isScanning())
reader.stopScan();
}
public boolean isScanning() {
return reader.isScanning();
}
public boolean isConnected() {
return reader.isConnected();
}
public void removeAll() {
scannedItemsMap.clear();
}
public void remove(String tagid) {
scannedItemsMap.remove(tagid);
}
public int getBatteryLevel(){
try {
return reader.getBatteryLevel();
}catch (Exception e){
return 0;
}
}
#Override
public void handleReaderEvent(ReaderEvent arg0) {
// TODO Auto-generated method stub
}
}
Now Handle The data in activity ....
Show in below method.
public void handleData(final String tagid) {
// TODO Auto-generated method stub
try {
final String Code_samplecode = convertHexToString(tagid);
// Log.e("Name", "Itemcode" + Code_samplecode);
if (SampleCode.contains(Code_samplecode)&& !p_SampleCode.contains(Code_samplecode)) {
// Scann items count
tgf.startTone(25);
int ind_val = SampleCode.indexOf(Code_samplecode);
if (ind_val != -1) {
final String SampleNo1 = SampleNo.get(ind_val);
final String StyleNo1 = StyleNo.get(ind_val);
final String SampleCode1 = SampleCode.get(ind_val);
final String StyleCode1 = StyleCode.get(ind_val);
//final String CartStyleCode1 = CartStyleCode.get(ind_val);
// final String CartStyleNo1 = CartStyleNo.get(ind_val);
SampleNo.remove(ind_val);
StyleNo.remove(ind_val);
SampleCode.remove(ind_val);
StyleCode.remove(ind_val);
runOnUiThread(new Runnable() {
#Override
public void run() {
// p_Code.add(Code.get(ind_val));
p_SampleNo.add(SampleNo1);
p_StyleNo.add(StyleNo1);
p_SampleCode.add(SampleCode1);
p_StyleCode.add(StyleCode1);
//Code.remove(ind_val);
// adapter3.notifyDataSetChanged();
// adapter1.notifyDataSetChanged();
total_item.setAdapter(null);
adapter3 = new Adapter_for_Inventoryitem(ReadInventory.this,
StyleNo, SampleNo);
total_item.setAdapter(adapter3);
present_item.setAdapter(null);
adapter1 = new Adapter_for_Inventoryitem(ReadInventory.this,
p_StyleNo, p_SampleNo);
present_item.setAdapter(adapter1);
textvie.setText("Total " + p_SampleNo.size() + " Found Styles");
textvi.setText("Total " + SampleNo.size() + " Available Styles");
List<Inventory> c = db.get_all_data_INVENTARY_Query("SELECT * FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
if (c.size() > 0) {
db.execute_query("INSERT INTO Inventory_p (Code, SampleNo,StyleNo,SampleCode,StyleCode,CartStyleNo,CartStyleCode) VALUES ('" + c.get(0).getCode() + "' , \"" +
c.get(0).getSampleNo() + "\" , \"" + c.get(0).getStyleNo() + "\" , '" +
c.get(0).getSampleCode() + "' , '" + c.get(0).getStyleCode() + "' , \"" +
c.get(0).getCartStyleNo() + "\" , '" + c.get(0).getCartStyleCode() + "')");
}
db.execute_query("DELETE FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
}
});
}
} else {
if (!SampleCode.contains(Code_samplecode) && !p_SampleCode.contains(Code_samplecode)
&& !not_fount_items.contains(Code_samplecode)) {
tgn.startTone(20);
scanneditems_unkown = scanneditems_unkown + 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
not_fount_items.add(Code_samplecode);
not_fount_items_txt.setText("Total " + not_fount_items.size() + " Unknown Styles");
}
});
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
scan_counts.setText("Total " + p_SampleNo.size() + " Scanned");
scan_counts_unknown.setText("Total " + scanneditems_unkown + " Unknown");
last_scanned_items.setText("Item : " + Code_samplecode);
}
});
} catch (Exception e) {
e.printStackTrace();
Message message = new Message();
message.what = READEREXCEPTION;
itemDetectedHandler.sendMessage(message);
}
}
You need to Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
//To get the characters (One By one)
event.getDisplayLabel();
}
And use Debounce (I'll recommend using RX Java) if the card numbers are of different length.
What debounce does is, it will wait for a particular amount of time after a keyevent happens, So you can concat the whole string and then use it.

R.string provides me numbers

I have this code which is not working:
public class MainActivity extends AppCompatActivity {
int quantity=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( "MainActivity", "modriodfw" + (R.string.Thankyou));
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
EditText nombre = (EditText) findViewById(R.id.nombre);
String nombre1 = nombre.getText().toString();
boolean cream = getstate();
boolean chocolate = getcState();
int price = calculatePrice(cream, chocolate);
String summary = createOrderSummary(price, cream,chocolate,nombre1);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, (R.string.OrderMail) + nombre1);
intent.putExtra(Intent.EXTRA_TEXT, summary);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(summary);
}
public void clearText(View view)
{
EditText nombre = (EditText) findViewById(R.id.nombre);
nombre.setText("");
}
private boolean getcState()
{
CheckBox state = (CheckBox) findViewById(R.id.chocolate);
boolean chocolateState = state.isChecked();
return chocolateState;
}
private boolean getstate()
{
CheckBox state = (CheckBox) findViewById(R.id.cream);
boolean creamState = state.isChecked();
return (creamState);
}
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = (R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + (R.string.name);
}
if(chocolate && cream == false){
summary += "\n" + quantity + (R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + (R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + (R.string.Thankyou);
return summary;
}
private int calculatePrice(boolean cream, boolean chocolate) {
int price = 5;
if (cream) {
price = price + 1;
}
if (chocolate) {
price = price + 2;
}
price = price * quantity;
return price;
}
public void increase(View view) {
if (quantity == 99){
Toast.makeText(this, (R.string.high), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity + 1;
display(quantity);
}
public void decrease(View view){
if (quantity == 1){
Toast.makeText(this, (R.string.less), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int numb) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + numb);
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String Summary) {
TextView summaryTextView = (TextView) findViewById(R.id.Summary_text_view);
summaryTextView.setText(Summary);
}
and all I get is this:
2131099680
Total: $10
2131099676
and it should be
Name:
summary
total $
Thank You!
im using java in android studio.
You need to do context.getString(R.string.your_string), as R.string.your_string on its own is just a reference.
You have forgotten to call getString method in four places. I update your code :
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = getString(R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + getString(R.string.SummaryChocolate);
}
if(chocolate && cream == false){
summary += "\n" + quantity + getString(R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + getString(R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + getString(R.string.Thankyou);
return summary;
}`enter code here`

why didn't refresh first item of listview and how can I fix it?

I want to hide more than 60 character of textView and show instead more... or see more...and after clicking on it show less in an item of listView adapter with following code :
if (item.explain.length() > 60) {
txtExplain.setText(Html.fromHtml("<font color='#15304e'>← " + G.currentActivity.getString(R.string.more) + "</font><br/>" + item.explain.substring(0, 40) + "..."));
isMoreThan60 = true;
seeMore = true;
} else {
txtExplain.setText(item.explain);
isMoreThan60 = false;
seeMore = false;
}
and when I want to set OnClickListener I use it in this way :
txtExplain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isMoreThan60) {
if (seeMore) {
txtExplain.setText(Html.fromHtml("<font color='#15304e'>↓ " + G.currentActivity.getString(R.string.less) + "</font><br/>" + item.explain));
seeMore = false;
} else {
txtExplain.setText(Html.fromHtml("<font color='#15304e'>← " + G.currentActivity.getString(R.string.more) + "</font><br/>" + item.explain.substring(0, 40) + "..."));
seeMore = true;
}
} else {
return;
}
}
});
except first Item I've not any problem that I should scroll listView until exit first item from screen and use from it's OnClickListener
first item or others that are shown in first time does not REFRESH
tanks

Categories

Resources