Hot questions for Using Android EditText in android studio

Question:

I've made a TextInputEditText for a PasswordField with a DrawableLeft as an icon, and then i added a PasswordToggleEnabled(true) .. this operation has deleted or hiden my DrawableLeft, Here's my code:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleContentDescription="Show Password"
        app:passwordToggleEnabled="true"
        app:hintEnabled="false"
        android:id="@+id/signupPasswordlayout"
        app:passwordToggleTint="@color/edittexttint">
        <android.support.design.widget.TextInputEditText
            android:hint="Password"
            android:id="@+id/signupPassword"
            android:drawableLeft="@drawable/ic_password"
            android:drawablePadding="10dp"
            android:inputType="textPassword"
            android:drawableTint="@color/edittexttint"
            android:textSize="15sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        </android.support.design.widget.TextInputLayout>

so , is it possible to show both ( PasswordToggle and DrawableLeft ? ) thank you!


Answer:

I'd not seen this exact behavior before, but looking at the source for TextInputLayout, it does attempt to preserve the user-set drawables when it applies the placeholder drawable for the password toggle. However, like most everything else in the support libraries to which its applicable, it handles them with relative positions - i.e., start and end - rather than absolute - left and right.

The support libraries have always been notorious for breaking anything that specifies absolute directions or positions, so it's no surprise that that's the issue here, as well.

Simply change the attribute you're setting to drawableStart, instead of drawableLeft. Keep this in mind, too, for anything else involving a choice of absolute or relative positions and directions with the support libraries.

Question:

There is an EditText, what I want is when I select it ,I should get the cursor position. The maximum length of the edittext is 13.

Also in my edittext, the first three character's type is text and the other character's type is number. If the first three characters are selected, the input type of keyboard should show text. And if any other characters are selected ,then the input type should be number. How to do this?


Answer:

I think this code can help you ❤ :

Class Code :

edittext = (EditText) findViewById(R.id.edtxt);
        edittext.setInputType(InputType.TYPE_CLASS_TEXT);
        edittext.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(final CharSequence s, int start, int before, int count) {             

                if (edittext.getText().length() < 3 ) {
                edittext.setInputType(InputType.TYPE_CLASS_TEXT);       
                }   
                else if (edittext.getText().length() == 3 ) {
                edittext.setInputType(InputType.TYPE_CLASS_NUMBER);
                }}
                @Override
                public void afterTextChanged(Editable s) {

                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }


    });}}

Xml Code :

<EditText
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:maxLength="13"
        android:id="@+id/edtxt"
        android:ems="10"/>

Question:

My application contains 3 EditText Properties

The first property takes the value of percentage from the user and second property should get the Number of what the user want to be calculate the percent for and the third property should Display the result.

I have attached the java and xml code below! Thank you.

I have a logic error. I'm expecting to get the value of a specific number with specific percentage the user had entered.

For eg. User wants 25% of 200 then in the first EditText, user will enter 25% and then in the second Edittext he will enter 200 and the value should be automatically displayed in the third Edittext i.e. 50. But here the Third Edittext is not updating its value and showing 0.0.

    <EditText
    android:id="@+id/txtbx1"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.462" />

    <EditText
    android:id="@+id/txtbx2"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.585" />

    <EditText
    android:id="@+id/txtbx3"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.708" />

    <TextView
    android:id="@+id/txtvw1"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="%"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.144"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.462" />

    <TextView
    android:id="@+id/txtvw3"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="is"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.144"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.708" />

    <TextView
    android:id="@+id/txtvw2"
    android:layout_width="33dp"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="of"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.133"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.585" />

    <TextView
    android:id="@+id/PC"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:fontFamily="@font/sansationbold"
    android:text="Percentage Calculator"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.139" />

    <TextView
    android:id="@+id/acl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="320dp"
    android:layout_marginLeft="320dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:fontFamily="@font/casanova"
    android:text="Arcis Computer Labs"
    android:textSize="10dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.988" />

    setContentView(R.layout.activity_mainscreen);
    EditText txtbx1 = (EditText)findViewById(R.id.txtbx1);
    EditText txtbx2 = (EditText)findViewById(R.id.txtbx2);
    EditText txtbx3 = (EditText)findViewById(R.id.txtbx3);
    TextView txtvw1 = (TextView)findViewById(R.id.txtvw1);
    TextView txtvw2 = (TextView)findViewById(R.id.txtvw2);
    TextView txtvw3 = (TextView)findViewById(R.id.txtvw3);

    float txt;
    try{
        txt = Float.parseFloat(txtbx1.getText().toString());
    }
    catch(NumberFormatException x){
        txt = (float) 0.0;
    }
    float txt2;
    try{
        txt2 = Float.parseFloat(txtbx2.getText().toString());
    }
    catch(NumberFormatException ex){
        txt2 = (float) 0.0;
    }
    Percent = (txt2 * txt) / 100;
    txtbx3.setText(String.valueOf(Percent));
}

Answer:

In your code, the text of the EditText won't be updated since onCreate method will be called only when the application is launched. So need to add change listener on the EditText. Try the below code:

float txt1 = 0, txt2 = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText txtbx1 = (EditText) findViewById(R.id.txtbx1);
    EditText txtbx2 = (EditText) findViewById(R.id.txtbx2);
    final EditText txtbx3 = (EditText) findViewById(R.id.txtbx3);
    TextView txtvw1 = (TextView) findViewById(R.id.txtvw1);
    TextView txtvw2 = (TextView) findViewById(R.id.txtvw2);
    TextView txtvw3 = (TextView) findViewById(R.id.txtvw3);


    txtbx1.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) {
            if (s.length() != 0)
                txt1 = Float.parseFloat(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            changeValue(txt1, txt2, txtbx3);
        }
    });

    txtbx2.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) {
            if (s.length() != 0)
                txt2 = Float.parseFloat(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            changeValue(txt1, txt2, txtbx3);
        }
    });


}

private void changeValue(float txt1, float txt2, EditText txtbx3) {
    float Percent = (txt2 * txt1) / 100;
    txtbx3.setText(String.valueOf(Percent));
}

Question:

For Android Studio: I would like to check if words are typed in 'edit text'. If so, then I will return a 'text view'.

I am having trouble figuring out the exact code to type.

For example, this is what I have:

 for (int i = 0; i < suiWords.length; i++) {
    if (editPost.contains(suiWords[i])) {
       msgHotline.setVisibility(View.VISIBLE);
       break;
       }
    }

"contains" is giving me an error message, so I know that is not the right code to use.

Does anyone know what command I need to use to check whether or not a certain word is typed?

Thanks for your help in advance!

Notes:

  • I already tried searching Google + Stack Overflow for an answer and no luck. If you found the link, please kindly post it here.

  • I am still a student.


Answer:

Try this: editPost.getText().toString().equals(suiWords[i])

Question:

So each time I run the app, type in an ID and hit submit; the end result come outs with null as the ID.

For example: I want to type in 12345 it should go to http://www.hiddenlink.com/12345 but instead it goes to http://www.hiddenlink.com/null

Here's my code:

public class SearchActivity extends Activity {
Button btnSearchStudent;
String studentID;
private String url = "http://www.hiddenlink.com/" + studentID; // This is test SID just to confirm connection
private static final String TAG_ALLRECORDS = "Objects";
private static final String TAG_ENAME = "emer_name1";
private static final String TAG_EPHONE1 = "emer_Phone1";
private static final String TAG_EPHONE2 = "emer_Phone2";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    EditText txtStudentID = (EditText) findViewById(R.id.txtStudentID);
    studentID = txtStudentID.getText().toString();
    btnSearchStudent = (Button) findViewById(R.id.btnSearchSID);
    btnSearchStudent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SearchActivity.this, SearchResults.class);
            startActivity(intent);
            new JSONParse().execute();
        }

    });
}

private class JSONParse extends AsyncTask<Void, Void, Void> {
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(SearchActivity.this);
        pDialog.setMessage("Connection Test: Logging into Student Database...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    // Login to APIs
    @Override
    protected Void doInBackground(Void... args) {

        String _username = "hidden";
        String _password = "hidden123";
        String content = MyHttpURLConnection.getData(url, _username, _password);
        try {
// Getting JSON Object from URL Content
            JSONObject json = new JSONObject(content);
            JSONArray jsonArray = json.getJSONArray(TAG_ALLRECORDS);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject c = jsonArray.getJSONObject(i);
// Storing JSON item in a Variable
                String emer_name1 = c.getString(TAG_ENAME);
                String emer_Phone1 = c.getString(TAG_EPHONE1);
                String emer_Phone2 = c.getString(TAG_EPHONE2);
// Adding value HashMap key => value
                HashMap<String, String> add = new HashMap<String, String>();
                add.put(TAG_EPHONE1, emer_Phone1);
                add.put(TAG_ENAME, emer_name1);
                add.put(TAG_EPHONE2, emer_Phone2);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

Answer:

String studentID;
private String url = "http://www.hiddenlink.com/" + studentID;

studentID hasn't been initialized here yet, and so its value is null. Remove the + studentID part and add the studentID when you have set it a value.

Question:

I have a multi-edit text field in a card view I want to get a string from and show in a toast before moving on to another activity. I can fill in text just fine when running the activity, but when I click the submit button nothing happens. What am I doing wrong or what am I missing in the code?

Here is my XML file:

        <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        card_view:cardCornerRadius="4dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="0dp">

        <EditText
            android:id="@+id/value1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/choice_hint1c"
            android:inputType="textMultiLine" />

    </android.support.v7.widget.CardView>

    <Button
        android:id="@+id/choiceButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/round_btn_shape"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_marginStart="125dp"
        android:text="@string/submit"
        android:textColor="#FFFFFF" />

Class file:

   import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Choice extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice);
addListenerOnButton();


    }

    public void addListenerOnButton() {

        Button submitButton = (Button) findViewById(R.id.choiceButton);
        final EditText editTextV1 = (EditText) findViewById(R.id.value1);
        final String valueOne = editTextV1.getText().toString();


        submitButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (valueOne.equals("")) {
                    //happens if first field is empty
                    Toast.makeText(
                            getApplicationContext(),
                            "First field is empty",
                            Toast.LENGTH_SHORT).show();

                } else {

                    //save selection

                    Toast.makeText(
                            getApplicationContext(),
                            valueOne,
                            Toast.LENGTH_SHORT).show();

                    //save response to SQLite

                    Intent intentSurvey = new Intent(Choice.this, MainActivity.class);
                    startActivity(intentSurvey);

                }

            }

        });


}
}

Answer:

  1. You miss to add addListenerOnButton() inside onCreate method.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choice);
    addListenerOnButton(); // add this
    }
    
  2. To check whether EditText is empty

     if(TextUtils.isEmpty(valueOne)) 
    
  3. Move String valueOne = editTextV1.getText().toString(); inside onClick

Question:

Is possible to determine if user selected some text in EditText? If yes, is possible to determine which text? How?

I am programming something like text editor and i need set some text as header when user select it and click on button which is under edit text

thx for help


Answer:

Try this:

int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();
String selectedText = et.getText().substring(startSelection, endSelection);

See this question: Android - get selection of text from EditText

Question:

I'm trying to make an web browser but I'm facing an problem that is i can't show current url in EditText..Showing currrent url from Webview. How can i do this. please tell me where should i put code and what code i need to put. please help me.

Here my code:

public class MainActivity extends AppCompatActivity {

    WebView browser;
    EditText urlbox;
    Button go,forward,backward,refresh,clear;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        browser= (WebView)findViewById(R.id.browser);
        urlbox = (EditText)findViewById(R.id.urlbox);
        go = (Button)findViewById(R.id.go);
        forward = (Button)findViewById(R.id.f);
        backward = (Button)findViewById(R.id.b);
        refresh = (Button)findViewById(R.id.r);
        clear = (Button)findViewById(R.id.c);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        browser.setWebViewClient(new ourviewclient());


        browser.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if(newProgress == 100){
                    progressBar.setVisibility(view.GONE);
                }else {
                    progressBar.setVisibility(view.VISIBLE);
                }
            }
        });

        WebSettings javascript = browser.getSettings();
        browser.getSettings().setJavaScriptEnabled(true);



        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               String editextvalue = urlbox.getText().toString();

               if(!editextvalue.startsWith("http://"))
                   editextvalue = "http://" + editextvalue;

               String url = editextvalue;

               browser.loadUrl(url);

               //for keyboard hide
                InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.hideSoftInputFromWindow(urlbox.getWindowToken(),0);
            }
        });

        forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoForward())
                    browser.goForward();
            }
        });

        backward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoBack())
                    browser.goBack();
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.reload();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.clearHistory();
            }
        });

    }
}

Answer:

Try this

browser.setWebViewClient(new WebViewClient() {    
      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
           super.onPageStarted(view, url, favicon);

           // set here your URL in Your EditText
            urlbox.setText(url);    

       }    

       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
           view.loadUrl(url);
           return true;
       }

       @Override
       public void onPageFinished(WebView view, String url) {

       }
  });

Question:

I'm trying to use EditText from Material Design ( https://material.io/develop/android/components/text-fields/ ) and I'm getting runtime exception.

I want to solve this problem

EditText Problem : When i try to open app with a regular EditText in a monitor and the app Crash [closed]

This's part of run log:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fares.orderfood/com.fares.orderfood.SignInActivity}: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText

    at com.fares.orderfood.SignInActivity.onCreate(SignInActivity.java:33)

/full

    E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fares.orderfood, PID: 5512
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fares.orderfood/com.fares.orderfood.SignInActivity}: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
    at com.fares.orderfood.SignInActivity.onCreate(SignInActivity.java:34)
    at android.app.Activity.performCreate(Activity.java:7009)

my java line 33

edtName =(EditText)findViewById(R.id.edtName);

My java file full:

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fares.orderfood.model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public
class SignInActivity extends AppCompatActivity {

EditText edtName, edtphone,edtpassword;
Button signinbtn1,cancel1;

@Override
protected
void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);

////////////////Text Input///////////////////
    edtName =(EditText)findViewById(R.id.edtName);     /// this line (33)

    edtpassword = (EditText)findViewById(R.id.edtpassword);
    edtphone = (EditText)findViewById(R.id.edtphone);

my style file

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

<item name="colorControlActivated">@color/colorPrimary</item>

             <item name="textAppearanceHeadline1">@style/TextAppearance.MaterialComponents.Headline1</item>
             <item name="textAppearanceHeadline2">@style/TextAppearance.MaterialComponents.Headline2</item>
             <item name="textAppearanceHeadline3">@style/TextAppearance.MaterialComponents.Headline3</item>
             <item name="textAppearanceHeadline4">@style/TextAppearance.MaterialComponents.Headline4</item>
             <item name="textAppearanceHeadline5">@style/TextAppearance.MaterialComponents.Headline5</item>
             <item name="textAppearanceHeadline6">@style/TextAppearance.MaterialComponents.Headline6</item>
             <item name="textAppearanceSubtitle1">@style/TextAppearance.MaterialComponents.Subtitle1</item>
             <item name="textAppearanceSubtitle2">@style/TextAppearance.MaterialComponents.Subtitle2</item>
             <item name="textAppearanceBody1">@style/TextAppearance.MaterialComponents.Body1</item>
             <item name="textAppearanceBody2">@style/TextAppearance.MaterialComponents.Body2</item>
             <item name="textAppearanceCaption">@style/TextAppearance.MaterialComponents.Caption</item>
             <item name="textAppearanceButton">@style/TextAppearance.MaterialComponents.Button</item>
             <item name="textAppearanceOverline">@style/TextAppearance.MaterialComponents.Overline</item>
         <!--  // Librarty material.io/design // -->

    </style>

add new my xml this my xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:background="@color/loginPageBackgroundColor"
    tools:context=".SignInActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipChildren="false"
        android:clipToPadding="false"
        android:orientation="vertical"
        android:padding="24dp"
        android:paddingTop="16dp">

        <ImageView
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="48dp"
            android:layout_marginBottom="16dp"
            app:srcCompat="@drawable/store"
            tools:ignore="VectorDrawableCompat" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="122dp"
            android:text="@string/signin"
            android:textSize="50sp"
            android:textStyle="bold" />

    <!-- input Username  -->
        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/edtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_name">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1"
                    android:text="fares"/>
        </com.google.android.material.textfield.TextInputLayout>
        <!-- input Username  -->
        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/edtphone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_phone">
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:maxLines="1"
                android:text="0988123344"/>
        </com.google.android.material.textfield.TextInputLayout>

    <!-- input Password  -->
        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/edtpassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            app:errorEnabled="true"
            app:endIconMode="password_toggle">
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:text="1234"/>
        </com.google.android.material.textfield.TextInputLayout>


    <!-- input Button  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- input Button signin -->
        <com.google.android.material.button.MaterialButton
            android:id="@+id/signbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="@string/signin"
            app:backgroundTint="#A8A8A8"/>

        <!-- input Button cancel -->
        <com.google.android.material.button.MaterialButton
        android:id="@+id/cancel_button"
        style="@style/Widget.MaterialComponents.Button.TextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="12dp"
        android:layout_marginRight="12dp"

        android:layout_toStartOf="@+id/signbtn"
        android:layout_toLeftOf="@+id/signbtn"
        android:text="@string/text_cancel" />
    </RelativeLayout>



    </LinearLayout>

</ScrollView>

Please, I need help


Answer:

Also the same error

You are casting TextInputLayout into EditText which is not possible, instead of this please try to cast TextInputEditText into EditText it will resolve your problem.

my java code

public
class SignInActivity extends AppCompatActivity {

    TextInputEditText edtName, edtphone,edtpassword;
    Button signinbtn1,cancel1;

    @Override
    protected
    void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

    ////////////////Text Input///////////////////
        edtName =(TextInputEditText)findViewById(R.id.edtName);

        edtpassword = (TextInputEditText)findViewById(R.id.edtpassword);
        edtphone = (TextInputEditText)findViewById(R.id.edtphone);

You have to give the id to TextInputEditText like this instead of TextInputLayout. It will resolve your problem:

XML layout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:background="@color/loginPageBackgroundColor"
    tools:context=".SignInActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipChildren="false"
        android:clipToPadding="false"
        android:orientation="vertical"
        android:padding="24dp"
        android:paddingTop="16dp">

        <ImageView
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="48dp"
            android:layout_marginBottom="16dp"
            app:srcCompat="@drawable/store"
            tools:ignore="VectorDrawableCompat" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="122dp"
            android:text="@string/signin"
            android:textSize="50sp"
            android:textStyle="bold" />

    <!-- input Username  -->
        <com.google.android.material.textfield.TextInputLayout

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_name">
                <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edtName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1"
                    android:text="fares"/>
        </com.google.android.material.textfield.TextInputLayout>
        <!-- input Username  -->
        <com.google.android.material.textfield.TextInputLayout

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_phone">
            <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edtphone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:maxLines="1"
                android:text="0988123344"/>
        </com.google.android.material.textfield.TextInputLayout>

    <!-- input Password  -->
        <com.google.android.material.textfield.TextInputLayout

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            app:errorEnabled="true"
            app:endIconMode="password_toggle">
            <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edtpassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:text="1234"/>
        </com.google.android.material.textfield.TextInputLayout>


    <!-- input Button  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- input Button signin -->
        <com.google.android.material.button.MaterialButton
            android:id="@+id/signbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="@string/signin"
            app:backgroundTint="#A8A8A8"/>

        <!-- input Button cancel -->
        <com.google.android.material.button.MaterialButton
        android:id="@+id/cancel_button"
        style="@style/Widget.MaterialComponents.Button.TextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="12dp"
        android:layout_marginRight="12dp"

        android:layout_toStartOf="@+id/signbtn"
        android:layout_toLeftOf="@+id/signbtn"
        android:text="@string/text_cancel" />
    </RelativeLayout>



    </LinearLayout>

</ScrollView>

Question:

I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class. Something like this:

 new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("New player")
                .setMessage("Input new player's name")
                .setView(input)
                .setPositiveButton("Register", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        name = input.getText().toString(); //<---HERE !want to use this variable
                    }
                })
                .setNegativeButton("Cancel", null)
                .show();

This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?


Answer:

Do it this way:

final String[] name = new String[1];
final EditText input = new EditText(this);

 new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("New player")
        .setMessage("Input new player's name")
        .setView(input)
        .setPositiveButton("Register", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               name[0] = input.getText().toString(); <---HERE! want to use this variable 
            }
        })
        .setNegativeButton("Cancel", null)
         .show();

Access it using name[0]

Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.

Question:

Okay so I am trying to extend the EditText view by creating my own, but whenever I instantiate it inside my MainActivity class it doesn't let me use the new methods I created! Any help is appreciated! Below is my code:

//Sticky.java

public class Sticky extends EditText {

  private CharSequence title = "";

  public Sticky(Context context) {
     super(context);
     Log.d("STICKY CONSTRUCTOR","Created new sticky!");
  }

  public Sticky(Context context, AttributeSet attrs) {
     super(context, attrs);
  }

  public Sticky(Context context, AttributeSet attrs, int defStyle) {
     super(context, attrs, defStyle);
  }

  public void setTitle(CharSequence text) {
     this.title = text;
  }

  public CharSequence getTitle() {
     return this.title;
  }

}

I tried using inner classes first, but that didn't work so I thought about moving it into it's own separate file. Sadly, that didn't work either.

//MainActivity.java

public class MainActivity extends ActionBarActivity {

    static final int STICKY_NOTE_HEIGHT = 180, STICKY_NOTE_WIDTH = 180;
    EditText mEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      mEdit = new Sticky(this); 

      mEdit.setId(1);

      mEdit.setTextColor(Color.BLACK);
      mEdit.setTextSize(24);
      mEdit.setHeight(STICKY_NOTE_HEIGHT);
      mEdit.setWidth(STICKY_NOTE_WIDTH);

      mEdit.setTitle("Sticky " + mEdit2.getId());//ERROR

      FrameLayout.LayoutParams params  = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);

      params.setMargins(stickyNoteLeftMargin, stickyNoteTopMargin, 0, 0);
      frameLayout.addView(mEdit2,params); //add a new view and make it use the new layout rules
}

When I run the app with the mEdit.setTitle(); commented out, it works perfectly fine. The only problem is when I uncomment it and try to use the custom method I created in the Sticky.java file. The error Android Studio gives me is Error:(93, 23) error: cannot find symbol method setTitle(String). I looked all over for answers but to no avail. Can someone please tell me what I am doing wrong? It's probably something really simple and I am just over looking it :(


Answer:

Instead :

mEdit.setTitle();//ERROR

try :

mEdit.setTitle("A random Title");

Question:

hi I'm trying to save the EditText widget values in the internal memory of the phone/tablet so that they can be retrieved automatically by the app when it closes or the activity stops. All off this will work using a save button.(The values of the widget are inputed by the user).


Answer:

You should use the shared preference ,shared preference is used to store the data in locally app whenever need you can access it . use this link https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

to use it. after on button click you can get the value . its help me

Question:

I am trying to do an application with a "feed" kind of method, where you type your message and the text message would appear on the top of the screen. Just like a messenger application, it sends the text but without database. This is a local application without internet connection.

So I just want to pop up "EditText"'s message to the top of the view, and whenever I write another message, the uppest message would go down by "1 step" and the newest message would be at top.

I know that there might be tutorial for this / been asked before, but I do not really know how to find it by name, because my google results only return me a method to message a real text message by some SMS method.


Answer:

Please look at this library: pusher

I think it's just what you need, plus there are some examples in the documentation

Question:

I have to create a carparking calculator in Android Studio which will multiply the number of minutes by 3 cents. It has to contain 1 edit text, textview and button.


Answer:

public class MainActivity extends AppCompatActivity {
    private Button b;
    private EditText cells;
    private TextView ans;
    String s = "Answer";
    double c = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.button);
        cells = (EditText) findViewById(R.id.editText_cells);
        ans = (TextView) findViewById(R.id.textView3);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    c = Double.parseDouble(cels.getText().toString());
                    s = Double.toString(c+((c*3)/100));
                    char ch[] = s.toCharArray();
                    ans.setText(ch, 0, ch.length)
            }
        });
   }

I hope you will manage main.xml.