Simple If Statement - android

I am trying to pass two variables from one screen to another. From the previous screeen you click a button, 1 or 2 and it passes that value on. It also passes the value 2 as the correct value. I know they are both working as I output each variable on the next screen. Here is the code. It always outputs wrong though.
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText == correct){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}

because you are not comparing the string. you are comparing if both are pointing to same object.
to compare string use
if(nexText.equals(correct))

if(newText == correct)
This will always be false. To compare the contents of two Strings character by character, use the .equals method:
if( newText.equals(correct) )
Using == on objects in Java means you are comparing the values of the memory address stored in these pointers/references. Since they are different String objects, they will never have the same address.

You don't compare Strings this way, rewrite code this way to get things done:
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText.equals(correct)){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}

Related

I have 4 textviews which take their values from spinner. If TextView 3 and 4 are blank then I need to copy values from position 1 & 2

I have 4 textviews which take their values from dropdown list (spinner) selected at previous screen.
There can be either 2 or 4 numbers/letters as result of this selection.
The first position will always be a number and the second position will always be a letter. The third position can be a number or blank and the fourth position can be a letter or blank.
If position 3 and position 4 are blank then I need to make them equal to positions 1 & 2 respectively.
String myGrade = intent.getStringExtra("parameter_name_grade");
// above takes value of 'myGrade' from spinner selection at previous screen
String mDisplayGradeNumberEff = (" " + myGrade.charAt(0));
TextView displayGradeNumberEff = (TextView) findViewById(R.id.gradeNumberEffTV);
displayGradeNumberEff.setText(mDisplayGradeNumberEff);
String mDisplayGradeLetterEff = (" " + myGrade.charAt(1));
TextView displayGradeLetterEff = (TextView) findViewById(R.id.gradeLetterEffTV);
displayGradeLetterEff.setText(mDisplayGradeLetterEff);
// above works correctly
// from here down only works when a character is present in both positions
// if positions 3(2) and 4(3) are empty app stops running.
String mDisplayGradeNumberDia = (" " + myGrade.charAt(2));
if (mDisplayGradeNumberDia.isEmpty()) {
mDisplayGradeNumberDia = mDisplayGradeNumberEff;
}
TextView displayGradeNumberDia = (TextView) findViewById(R.id.gradeNumberDiaTV);
displayGradeNumberDia.setText(mDisplayGradeNumberDia);
String mDisplayGradeLetterDia = (" " + myGrade.charAt(3));
if (mDisplayGradeLetterDia.isEmpty()) {
mDisplayGradeLetterDia = mDisplayGradeLetterEff;
}
TextView displayGradeLetterDia = (TextView) findViewById(R.id.gradeLetterDiaTV);
displayGradeLetterDia.setText(mDisplayGradeLetterDia);
}
I Guess you have a array out of bounds exception, please provide Logcat....
Check if "myGrade" has 3/4 Characters, if it does not you can't read them with charAt(3)...
You can check the length of the String with "myGrade.length()"
When I asked this question I was fairly new to the site and didn't understand that I should post back the solution for future reference. Solution below worked so thanks to rocket for your help and sorry for the delay!
int myGradeLength = mGrade.length();
if (myGradeLength != 4) {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(0));
mDisplayGradeLetterDia = ("" + mGrade.charAt(1));
} else {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(2));
mDisplayGradeLetterDia = ("" + mGrade.charAt(3));
}

Android basic math in textview

I am trying to add two numbers and display them in the textview using this code. The problem here is that it doesn't add the numbers, it just displays the entire string.
CharSequence fnum, snum, symbol;
final TextView CalTextBox = (TextView) findViewById(R.id.MainTextview);
symbol = "+"; // addition selected
fnum = CalTextBox.getText(); // store number into fnum
snum = CalTextBox.getText(); //new number will be added in the code and be stored into snum
CalTextBox.setText(""); // delete whats in the text box
CalTextBox.setText(snum + "" + symbol + "" + fnum); // add two numbers
Well, the '+' operator performs concatenation if used on strings (like in this case). To perform a math operation, you have to convert them to numbers first. I think you can use this:
// Convert the 2 String to integer values
int first = Integer.valueOf(fnum);
int second = Integer.valueOf(snum);
// Compute the sum
int sum = first + second;
// Create the String you can use to display in the TextView
String textToDisplay = String.valueOf(sum);
snum = "2";
fnum = "3";
symbol = "+";
snum + "" + symbol + "" + fnum = "2+3"
Instead you should convert String into integer or double and make appropriate controls such as null or empty, or non-numeric then,
int result = Integer.parseInt(snum) + Integer.parseInt(fnum);
CalTextBox.setText("" + result);
For mathematical operations is best to use int, long or double variable types. Instead of CharSequence use for example int.
to get integer (int) from String (text) use:
int fnum, snum, symbol;
int fnum = Integer.parseInt("10"); or
fnum = Integer.parseInt(CalTextBox.getText());
CalTextBox.setText("" + (snum + symbol + fnum));

Delete characters in string until /r/n

I have long string that at some part has
some text + "PHOTO;ENCODING=BASE64;TYPE=JPEG:" + some characters that generate randomly + /r/n...
I am wondering how can I delete part from
"PHOTO;ENCODING=BASE64;TYPE=JPEG:" untill /r/n
so I will be left only with
some text + /r/n ?
my code so far:
if (string.contains("PHOTO;ENCODING=BASE64;TYPE=JPEG:") {
string = string.replace("PHOTO;ENCODING=BASE64;TYPE=JPEG:", "");
}
but this obviously would not replace my random generated chars, only "PHOTO;ENCODING=BASE64;TYPE=JPEG:".
How do I "loop through" string from "PHOTO;ENCODING=BASE64;TYPE=JPEG:" untill /r/n ?
final String input = "some text + PHOTO;ENCODING=BASE64;TYPE=JPEG: + some characters that generate randomly + /r/n"
final int index = input.indexOf("PHOTO;ENCODING=BASE64;TYPE=JPEG:");
if (index != -1)
{
final String result = input.subString(0, index) + System.getProperty("line.separator")
}
why dont you try following
1) Get the index of "PHOTO;ENCODING=BASE64;TYPE=JPEG:". and call it idx
2)If idx != -1 then take substring of original string using str.subString(0,idx) and call it newStr
3)return newStr+(str.endsWith("\r\n")?"\r\n":"")

How can I display a previous EditText user input, as well as a recent EditText user input?

I have a SharedPreferences that saves EditText input from one activity and displays the String value in another activity.
When I enter an input into the EditText fields and press (a button I created) "Save" (which commits the EditText to editor), the file is stored and displayed successfully.
However, I want it so that everytime the user adds another entry in the EditText, it displays underneath the previously added EditText input. Like a list. I understand that both are reading from the SharedPreferences file. How would I go about doing this?
CustomStoreEditActivity - Just storing the user inputs (EditText entries):
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (saveButton.isClickable()) {
SharedPreferences prefs = getSharedPreferences(
"customtime", 0);
// prefs.registerOnSharedPreferenceChangeListener(this);
final SharedPreferences.Editor edit = prefs.edit();
EditText shopName = (EditText) findViewById(R.id.shopName);
EditText open1 = (EditText) findViewById(R.id.open1);
EditText close1 = (EditText) findViewById(R.id.close1);
EditText open2 = (EditText) findViewById(R.id.open2);
EditText close2 = (EditText) findViewById(R.id.close2);
EditText open3 = (EditText) findViewById(R.id.open3);
EditText close3 = (EditText) findViewById(R.id.close3);
EditText open4 = (EditText) findViewById(R.id.open4);
EditText close4 = (EditText) findViewById(R.id.close4);
EditText open5 = (EditText) findViewById(R.id.open5);
EditText close5 = (EditText) findViewById(R.id.close5);
EditText open6 = (EditText) findViewById(R.id.open6);
EditText close6 = (EditText) findViewById(R.id.close6);
EditText open7 = (EditText) findViewById(R.id.open7);
EditText close7 = (EditText) findViewById(R.id.close7);
EditText comments = (EditText) findViewById(R.id.comments);
edit.putString("shopName", shopName.getText().toString());
edit.putString("Monday1", open1.getText().toString());
edit.putString("Monday2", close1.getText().toString());
edit.putString("Tuesday1", open2.getText().toString());
edit.putString("Tuesday2", close2.getText().toString());
edit.putString("Wednesday1", open3.getText().toString());
edit.putString("Wednesday2", close3.getText().toString());
edit.putString("Thursday1", open4.getText().toString());
edit.putString("Thursday2", close4.getText().toString());
edit.putString("Friday1", open5.getText().toString());
edit.putString("Friday2", close5.getText().toString());
edit.putString("Saturday1", open6.getText().toString());
edit.putString("Saturday2", close6.getText().toString());
edit.putString("Sunday1", open7.getText().toString());
edit.putString("Sunday2", close7.getText().toString());
edit.putString("comments", comments.getText().toString());
edit.commit();
Intent myIntent = new Intent(getBaseContext(),
CustomStoreActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
Toast.makeText(getBaseContext(), "Opening Hours Saved!",
Toast.LENGTH_SHORT).show();
}
}
});
}
CustomStoreActivity - where I retrieve the data and display:
public void onResume() {
SharedPreferences prefs = getSharedPreferences("customtime", 0);
String shopName = prefs.getString("shopName", "Empty");
String shopTimeM1 = prefs.getString("Monday1", " ");
String shopTimeM2 = prefs.getString("Monday2", " ");
String shopTimeT1 = prefs.getString("Monday1", " ");
String shopTimeT2 = prefs.getString("Monday2", " ");
String shopTimeW1 = prefs.getString("Monday1", " ");
String shopTimeW2 = prefs.getString("Monday2", " ");
String shopTimeTH1 = prefs.getString("Monday1", " ");
String shopTimeTH2 = prefs.getString("Monday2", " ");
String shopTimeF1 = prefs.getString("Monday1", " ");
String shopTimeF2 = prefs.getString("Monday2", " ");
String shopTimeS1 = prefs.getString("Monday1", " ");
String shopTimeS2 = prefs.getString("Monday2", " ");
String shopTimeSU1 = prefs.getString("Monday1", " ");
String shopTimeSU2 = prefs.getString("Monday2", " ");
String shopComments = prefs.getString("comments", "");
TextView displayPrefs = (TextView) findViewById(R.id.displayPrefs);
displayPrefs.setText(
"------------------------------------------------------------" +
"\n\nSHOP NAME: " + shopName +
"\n\nTIMINGS: " + "\n\n Monday: " + shopTimeM1 + " - " + shopTimeM2 +
"\n Tuesday: " + shopTimeT1 + " - " + shopTimeT2 + "\n Wednesday: "
+ shopTimeW1 + " - " + shopTimeW2 + "\n Thursday: " + shopTimeTH1
+ " - " + shopTimeTH2 + "\n Friday: " + shopTimeF1 + " - " + shopTimeF2 +
"\n Saturday: " + shopTimeS1 + " - " + shopTimeS2 + "\n Sunday: " +
shopTimeSU1 + " - " + shopTimeSU2 +
"\n\nCOMMENTS: " + shopComments +
"\n\n------------------------------------------------------------");
super.onResume();
}
Thank you for your humble time.
It sounds to me like you are trying to build a list. Pardon my initially nebulous answer but I promise it will eventually focus in on a point.
What I would recommend for the overall framework is this:
You have an Activity (presumably your CustomStoreActivity) which displays a list of saved Store objects. Store will need to implement Parcelable or Serializable (preferably the former).
On this Activity there is a New Store button (if you are following Android design convention, this is likely as a "+" button in the Action Bar).
On pressing the New Store button, your CustomStoreActivity calls startActivityForResult(CustomStoreEditActivity.class).
Your CustomStoreActivity implements onActivityResult as per the answer on the last question you asked. Here, you will get a result code and an Intent which contains Extras (to be retrieved by intent.getExtras()).
Your CustomStoreEditActivity takes user input, as above, and instead of writing it to SharedPreferences it uses the information to create a new Store object which contains all of the information, and uses setResult(RESULT_OK,intent) where intent is the Intent to which you have added the Store extra (as a Parcelable).
This means that when CustomStoreEditActivity calls finish() (which you will do instead of using an intent to re-launch your CustomStoreActivity because the CustomStoreActivity is already just behind it) you'll get your call to onActivityResult and can pull the Store object out of the Extras from the Intent you just passed back.
And now to the point:
You can use a ListView in your CustomStoreActivity, and use a StoreAdapter that extends ArrayAdapter<Store>, and for each item in the list of Stores adds a view to the list containing that Store's name. Then you'll just add your new Store object to the array you passed into your StoreAdapter, and call adapter.notifyDataSetChanged() in onActivityResult and that should take care of it.
If ultimately you need to persist this data between application sessions, you should handle writing the Store objects to the SharedPreferences in the onPause method of CustomStoreActivity (it being the keeper of the list) rather than touching your shared preferences from every direction. You can then read in the list again in onCreate should you need to.
I know it's a lot to parse through/digest, but it's a pretty standard mechanism for passing data between Activity constructs in Android and for persisting data.
Let me know if you have any questions on the implementation and I'll see what I can do! :)
Take a look at my answer here: Show a drop down list of recently entered text when clicks on an android edit box
All you would really need to do is change the preference mode to public, not private.

How can I write a regular expression for this in android?

I am having a string(number) with special characters. I want to search for a sub-string(comprising of digits only) & also I want to detect the starting index & ending index of matching sub-string in the string.
For example: main string: (+91)-1231212 1231
Sub-string to search: 1212
Currently I am using the following code to do this but in place of 1212,it searched for 12312. For other cases, it works fine.
String sss0 = "1212";
String sss1 = "(+91)-1231212 1231";
sss0 = sss0.replaceAll("[^\\d]","");
System.out.println("*************************"+sss0);
String ptn = "" + sss0.charAt(0);
for(int jj=0; jj<sss0.length()-1; jj++){
ptn += "[^" + sss0.charAt(jj) + sss0.charAt(jj+1) + "]*?" + sss0.charAt(jj+1);
}
System.out.println("ptn: " + ptn);
Pattern p300 = Pattern.compile(ptn);
Matcher m300 = p300.matcher(sss1);
if(m300.find()){
System.out.println("start, stop: " + m300.start() + "," + (m300.end()-1 ));
System.out.println("substring: " + sss1.substring(m300.start(), m300.end()));
}
Please help me. Thanks in advance.
Try this :
int start = sss1.indexOf(sss0);
if(start != -1) {
System.out.println("Start : " + start);
System.out.println("End : " + start.length()); //maybe add +1 here depending on what you mean by end index.
}
You can also put this in a loop to find all occurences of the substring.
pseudocode:
pattern = ""
foreach char c in sss0:
pattern += c + "[^0-9]*"
found_substring = match(pattern, sss1)
the idea being to intersperse the literal characters you're looking for with the pattern that you're willing to skip over.

Categories

Resources