checking number with regex if it is match or not - java

EditText view
<EditText
android:id="#+id/inputField"
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="#string/input_placeholder"
android:textColorHint="#color/colorAccent"
android:inputType="number"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:textSize="25sp"
android:padding="10dp"
android:layout_marginTop="100dp"
android:gravity="center"/>
class for hold number
package com.example.kassammustapha.samplecode;
public class regexHolder{
String patten_one()
{
return "[2550]{1}[7]{1}[1]{1}[2-9]{1}\\d{6}";
}}
mainActivity
the problem is when user enter the number from editText from the view, i receive the number and convert it into string then i test with regular expression but it won't work i dont what is the problems.
regexHolder operatorPatterns = new regexHolder();
final Pattern tigoOne = Pattern.compile(operatorPatterns.patten_one());
Button mBtn =findViewById(R.id.loginBtn);
mBtn.setOnClickListener(
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
public void onClick(View view)
{
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}
);

First you need to fix your regex. From your attempted regex and your comments, I am guessing that you want this:
(?:255|0)71[2-9]\\d{6}
Start with either 255 or 0, followed by 71, followed by a digit that is in the range 2-9, followed by 6 other digits.
Secondly, fix your on click listener.
These two lines:
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
Will be run the instant you create the listener, at which point the text edit is empty. You need to move these lines to the onClick method:
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
public void onClick(View view)
{
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}

Related

Open Hyperlinks of Textview in WebView Android

The following is the text that I have to set in text view. I wanted to open webview on click of hyperlink. Rest of the text should not be clickable.
String value = "Check on this link: Go to Google";
binding.text.setText(value);
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:autoLink="web"
android:textColorLink="#color/g_turquoise_blue" />
Thanks in advance.
This will help you if i got you correct
yourTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://google.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
UPDATE:
Try this
/**
* Returns a list with all links contained in the input
*/
public static List<String> extractUrls(String text)
{
List<String> containedUrls = new ArrayList<String>();
String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher urlMatcher = pattern.matcher(text);
while (urlMatcher.find())
{
containedUrls.add(text.substring(urlMatcher.start(0),
urlMatcher.end(0)));
}
return containedUrls;
}
Example:
List<String> extractedUrls = extractUrls("Welcome to https://stackoverflow.com/ and here is another link http://www.google.com/ \n which is a great search engine");
for (String url : extractedUrls)
{
System.out.println(url);
}
Prints:
https://stackoverflow.com/
http://www.google.com/
source: Detect and extract url from a string?

Calling phone number cuts first zero

Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private long sTime = 0L;
private Handler myHandler = new Handler();
private long wait2 = 1000000000;
private int telnum2;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button butt = (Button) findViewById(R.id.butt);
Button buttstop = (Button) findViewById(R.id.buttstop);
if (butt != null) {
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText wait = (EditText) findViewById(R.id.editText2);
wait2 = Integer.parseInt(wait.getText().toString()) * 1000;
EditText telnum = (EditText) findViewById(R.id.editText);
telnum2 = Integer.parseInt(telnum.getText().toString());
sTime = SystemClock.uptimeMillis();
myHandler.removeCallbacks(AutoCaller);
myHandler.postDelayed(AutoCaller, wait2);
}
});
}
buttstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myHandler.removeCallbacks(AutoCaller);
}
});
}
private Runnable AutoCaller = new Runnable() {
#Override
public void run() {
final long start = sTime;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telnum2)));
myHandler.postDelayed(this, wait2);
}
};
#Override
protected void onPause() {
myHandler.removeCallbacks(AutoCaller);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
myHandler.postDelayed(AutoCaller, wait2);
}}
layout_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
It creates 2 EditText and 2 Buttons.
I type number (0111) in first and (1) in second.
I click 1st button (id:butt) and it calls number 111 (i typed 0111).
Thanks!
Thats logic: You parse the String "0111" to an Integer, but numbers never start with zero if it isnt zero itself or a float/double value. So Java removes the zero when parsing, because the zero is useless for a number, because it doesnt change the value of the number.
The problem is, you are parsing the number as an Integer
telnum2 = Integer.parseInt(telnum.getText().toString());
Leading Zeros in Numbers are stripped (0100 is the same number as 100 for example). You have to keep the number as String to preserve the leading zero.
Change the Variable type to String and Dont parse it to Integer.
"Phone numbers" are not actually numbers, they are sequences of digits. They have no numeric magnitude ("my phone number is higher than yours!"), and in particular, leading zeros are significant, which is not the case for numbers. So you should always treat them as strings, not as numbers.

Getting a decimal number from EditText on Android Studio

EDIT:Solved!
I know this has been posted before, but the answers I've seen from those are not working for me.
I'm trying to get the input from one textfield (which i've specified as a decimal input) but can't think of any other way to get the value of it other than to toString it.
What I have below crashes and the error logs say
java.lang.IllegalStateException: Could not execute method of the activity
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(mField.length() > 0){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
java.lang.IllegalStateException: Could not execute method of the
activity
Possible reason that this issue occur is kmField.getText().toString() return null. So please put some validation over here for kmField
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(kmField.getText().toString().isEmpty()){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
xml file:
<EditText
android:id="#+id/editS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/S0"
android:inputType="numberDecimal" />
<Button
android:id="#+id/getS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/setS0" />
in your java file:
EditText textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);
btn_S0.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
double S0 = Double.parseDouble(textS0.getText().toString());
}
});

Android sent string from one activity to another not working

I want to ask something that maybe simple, but I still can't find the problem.
I sent a string from one activity to another activity, but its show nothing.
I already checked it several times, and I think there's nothing wrong with my code.
Here's My first java code ( FoodFilter.class)
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.filter_type))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.item_list))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.category_name))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
FoodFilterDetail.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
This is the FoodFilterDetail.class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.foods_filterdetail);
TextView txtProduct = (TextView) findViewById(R.id.filterItemList);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("TAG_NAME");
// displaying selected product name
txtProduct.setText(product);
}
Here's my xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:layout_marginLeft="7dip"
android:layout_marginRight="7dip" >
<TextView
android:id="#+id/filterItemList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="15dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:text="Sort By"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
I get the data on FoodFilter.class from json parse and it works fine. I can show all the data on ListView, but when I send the string to FoodFilterDetail.class it show nothing and there's no error or warning in my code.
Is there anyone can help me to fix this? I've been searching the problem for whole day.
Thanks Before
use i.getStringExtra(TAG_NAME); instead of i.getStringExtra("TAG_NAME");
create one variable in FoodFilter.java
public static final String TAG_NAME = "name";
use this
in FoodFilter.java
in.putExtra(TAG_NAME, name);
and in FoodFilterDetail.java
String product = i.getStringExtra(FoodFilter.TAG_NAME);
Do the same for all other variable
I am assuming that you are defining TAG_NAME like this in the first activity:
public static final String TAG_NAME = "some_random_key";
Then you are setting it as the key for Intent like this:
in.putExtra(TAG_NAME, name);
And in the second activity you are trying to access it like this:
String product = i.getStringExtra("TAG_NAME");
Which will not work since the key is not "TAG_NAME" but "some_random_key". So to access it in the second activity you need to define TAG_NAME in the second activity as well just like you did in the first activity:
public static final String TAG_NAME = "some_random_key";
And then access the string like:
String product = i.getStringExtra(TAG_NAME);

EditText never has value

I have a pretty basic EditText that I pull data from as a double via a button.
It's value does not appear to change - if I use android:text="2", and pull the value, it comes up as 2. But if I leave it blank, type in it, and try to pull the value, it comes up blank or null.
The Problem: (since I suppose it hasn't been clear enough) when I launch my app, type "3" into the EditText, and press my button that calls String b = input.getText().toString(); and outputs b in a Toast and mathematical equation, it is blank and the equation calls an invalid input (my try/catch). The EditText supposedly never has a value.
<EditText
android:id="#+id/input"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".3"
android:hint="-->"
android:inputType="number"
android:maxLines="1"
android:textColor="#ffffff" />
...
Spinner spinner1, spinner2; //class space
EditText res, input;
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.fragment_math);
spinner1 = (Spinner)findViewById(R.id.unit_a);
spinner2 = (Spinner) findViewById(R.id.unit_b);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
res = (EditText) findViewById(R.id.result);
input = (EditText) findViewById(R.id.input);
...
public void convert(View view) {
int operation = 0;
double cm = 0;
String a;
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
if(operation == 0) {
//CM TO IN
try {
cm = Double.parseDouble(MainActivity.this.input.getEditableText().toString());
}catch(NumberFormatException nfe) {
Toast.makeText(MainActivity.this, "Invalid input! (" + MainActivity.this.input.getText().toString() + ")", Toast.LENGTH_LONG).show();
}
a = Double.toString(cmToIn(cm));
res.setText(a + "dfsdf", TextView.BufferType.EDITABLE); //same as below
}else if(operation == 1) {
//etc.
}else {
res.setText("Something went wrong! :("); //temp, completely dysfunctional
}
}
Edit: I apologize, the Toast I had for a while was incorrect because I managed to Ctrl + Z back to a dumb mistake before copying. Sorry. Fixed. Problem still occuring though.
You must be calling method Convert (which is responsible for retrieving edittext text as I could see from code) in onClick of a button. (And not in onCreate)
Then this should work fine.
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
Hope it helps.
input.getEditableText() returns an Editable object.
Use input.getText().toString() to return a String for the Toast to display.
More info: https://developer.android.com/reference/android/widget/EditText.html

Categories