Hot questions for Using Android EditText in settext

Question:

I want to make have templates for my note app which i can import to my class where i write the notes. When I start my MainActvity from notizen_ansehen.java everything goes well but when I start my MainActvity from templates.java the method setText() just dont function

here my MainActvity

public class MainActivity extends AppCompatActivity {

    EditText etxt;
    File ordner;
    File t;
    String s;
    String b;


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




    }

    @Override
    protected void onStart() {
        super.onStart();
        etxt = (EditText) findViewById(R.id.editText);
        if (getIntent().hasExtra("editnote_text") && getIntent().hasExtra("2") && getIntent().hasExtra("3")) {

            t = (File) getIntent().getExtras().get("editnote_text");
            s = getIntent().getStringExtra("2");
            b = getIntent().getStringExtra("3");
            etxt.setText(gettextfromfile2(t), TextView.BufferType.EDITABLE);

        }







        String g = "abc"; //this String is only added for testing
        etxt.setText(g);


        ordner = new File(Environment.getExternalStorageDirectory(), "test_notizenapp");
        if (!ordner.exists()) {
            ordner.mkdir();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        File notizdat;
        if (etxt.getText().length() > 0) {

            notizdat = new File(ordner, "Notiz_" + System.currentTimeMillis() + ".txt");
            try {
                OutputStream ops = new FileOutputStream(notizdat);
                ops.write(etxt.getText().toString().getBytes());
                ops.close();
                etxt.clearComposingText();
            } catch (FileNotFoundException e) {
                e.printStackTrace();

            } catch (IOException e) {
                e.printStackTrace();
            }


        } else {
            Toast.makeText(getApplicationContext(), "kein Inhalt", Toast.LENGTH_SHORT).show();
        }

    }

    public String gettextfromfile2(File datei) {

            StringBuilder strgbuilder = new StringBuilder();


            try {
                BufferedReader buffread = new BufferedReader(new FileReader(datei));

                String zeile;

                while ((zeile = buffread.readLine()) != null) {

                    strgbuilder.append(zeile);
                    strgbuilder.append("\n");


                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return strgbuilder.toString().trim();
        }
}

My layout.xml code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.ludwig.mynote.MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="360dp"
        android:layout_height="293dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.039"
        app:layout_constraintHorizontal_bias="0.6"
        tools:layout_editor_absoluteY="16dp"
        tools:layout_editor_absoluteX="14dp" />

</android.support.constraint.ConstraintLayout>

I have really no clue what the problem could be


Answer:

Try this move your code to onCreate() and initialize View first then use etxt.setText

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    etxt = (EditText) findViewById(R.id.editText);


     if (getIntent().hasExtra("editnote_text") && getIntent().hasExtra("2") && 
 getIntent().hasExtra("3")) {

        t = (File) getIntent().getExtras().get("editnote_text");
        s = getIntent().getStringExtra("2");
        b = getIntent().getStringExtra("3");
        etxt.setText(gettextfromfile2(t), TextView.BufferType.EDITABLE);
    }

    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    String g = "abc"; //this String is only added for testing
    etxt.setText(g);
    ordner = new File(Environment.getExternalStorageDirectory(), "test_notizenapp");
    if (!ordner.exists()) {
        ordner.mkdir();
    }
}

Question:

I'm trying to display date and time in an EditText box and have made some code here. The thing is, it's working - but only on the second attempt. Meaning I select date and time.. Nothing happens and on the second try the setText(); updates the EditText to display date and time. However, as you might have guessed, I'd like it to update the EditText immediately.

@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_reservation);

    firebaseAuth = FirebaseAuth.getInstance();
    textViewUserid = findViewById(R.id.addReservation_userId_edittext);

    FirebaseUser user = firebaseAuth.getCurrentUser();
    textViewUserid.setText(user.getEmail());

    gestureDetector = new GestureDetector(this);

    mDisplayDate = findViewById(R.id.addReservation_fromTime_edittext);
    mDisplayDate2 = findViewById(R.id.addReservation_toTime_edittext);


    mDisplayDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            int minute = cal.get(Calendar.MINUTE);

            DatePickerDialog datePickerDialog = new DatePickerDialog(
                    AddReservationActivity.this,
                    android.R.style.Theme_Light,
                    mDateSetListener,
                    year,month,day);

            TimePickerDialog timePickerDialog = new TimePickerDialog(
                    AddReservationActivity.this,
                    android.R.style.Theme_Light,
                    mTimeSetListener,
                    hour,minute,true);

            timePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            timePickerDialog.show();
            datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            datePickerDialog.show();
        }
    });
    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            month = month + 1;
            final String date = dayOfMonth + "/" + month + "/" + year;

            mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    if (minute < 10) {
                        String time = "" + hourOfDay + ":" + "0"+minute;
                        mDisplayDate.getText().toString();
                        mDisplayDate.setText(date + " " + time);
                    }else {
                        String time = "" + hourOfDay + ":" + minute;
                        mDisplayDate.getText().toString();
                        mDisplayDate.setText(date + " " + time);

                    }
                }
            };
        }
    }

I've been trying for some hours now to fix this, looking all over Stackoverflow and numerous other sites. This is mildly frustrating and I really hope someone has an input on what I'm doing wrong.

Apologies if there's somehow already a solution on the site I've missed. Thanks a lot in advance.


Answer:

I found the solution, appending the EditText - as suggested in a comment. So instead of trying to set the text of the EditText with both the date and time string simultaneously. I seperated them and made a setText(date); and append with time:

  mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            month = month + 1;
            final String date = dayOfMonth + "/" + month + "/" + year;
            mDisplayDate.setText(date);
        }
    };
    mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            if (minute < 10) {
                String time = " " + hourOfDay + ":" + "0" + minute;
                mDisplayDate.append(time);
            } else {
                String time = " " + hourOfDay + ":" + minute;
                mDisplayDate.append(time);

            }
        }
    };

Question:

I am using setTextValidation on EditText with regex pattern but it's not working properly. I only need alphabets & space for the field but when I press numbers it copies the other alphabets which is typed previously.

        ValidationUtil.setTextValidation(etClientMiddleName, "[a-zA-Z ]+", 50);

This is setTextValidation method

 public static void setTextValidation(EditText mEdtField, final String mRegExp, int length) {
    try {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String data = source.toString().substring(start, end);
                String retData = null;
                boolean isValid = false;
                isValid = data.matches(mRegExp);
                if (!isValid) {
                    if (source instanceof SpannableStringBuilder) {
                        retData = data.replaceAll("[\\d]", "");
                    } else {
                        retData = "";
                    }
                }
                return retData;
            }
        };

        mEdtField.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(length)});
    } catch (Exception e) {
        Log.e("Text Validation", "" + e);
    }
}

Answer:

You can try filtering disallowed characters like this.

ValidationUtil.setTextValidation(etClientMiddleName, "[^a-zA-Z ]", 50);

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    String data = source.toString().substring(start, end);
    return data.replaceAll(mRegExp,"");
}

Question:

I'm experiencing issues trying to use a custom type that implements Editable as the basis for an EditText. Here is my code:

// This is a custom type that implements Editable.
// It's just a wrapper over a SpannableStringBuilder, with some
// irrelevant added functionality.
public class ColoredText implements Editable {
    private final SpannableStringBuilder builder;

    public ColoredText(String text) {
        this.builder = new SpannableStringBuilder(text);
    }

    // All Editable methods are implemented through this.builder.
    @Override
    public Editable replace(int i, int i1, CharSequence charSequence, int i2, int i3) {
        this.builder.replace(i, i1, charSequence, i2, i3);
        return this;
    }

    ...
}

public class NoCopyEditableFactory extends Editable.Factory {
    @Override
    public Editable newEditable(CharSequence source) {
        return (Editable) source;
    }
}

// In MainActivity.java
@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    setContentView(R.layout.main);

    String line = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE";
    String text = TextUtils.join("\n", Collections.nCopies(100, line));
    Editable e = new ColoredText(text);

    EditText et = (EditText) findViewById(R.id.editText);
    et.setEditableFactory(new NoCopyEditableFactory()); // This line is causing trouble.
    et.setText(e, TextView.BufferType.EDITABLE);
}

// In the MainActivity layout file
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

For some reason, when I comment out the NoCopyEditableFactory, the cursor updates just fine. However, when I uncomment the line forcing the EditText not to copy the ColoredText into a new SpannableStringBuilder, the cursor does not update when I click on new places in the text. Why is this?


Answer:

The problem turned out to be with my Editable implementation. It works fine after I deleted some misbehaving code.

Question:

I am creating an update profile page and after getting data from the database, i want to set the values in edittexts so i can edit them. when i tried it it gave me errors. Please advice me on what to do. Thanks!

This is my ProfileActivity.java Class

package com.example.fproject;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ProfileActivity extends Activity {

EditText firstnameBox, lastnameBox, departmentBox, officeBox, emailBox, phonenoBox, passwordBox, statusBox, confirm_passwordBox;
private Button register;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private ProgressDialog pDialog;
String user;
SessionManagement session;
GetIPAddress getIPaddress = new GetIPAddress();
private static String url_get_user_data;    // products JSONArray
JSONArray data = null;


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

    session = new SessionManagement(getApplicationContext()); 
    SharedPreferences sp = getSharedPreferences("login_pref", 0);
    user = sp.getString(session.KEY_EMAIL, null);

    url_get_user_data = getIPaddress.getIP()+"get_user_data_for_profile.php";

    firstnameBox = (EditText)findViewById(R.id.update_firstname);
    lastnameBox = (EditText)findViewById(R.id.update_lastname);
    departmentBox = (EditText)findViewById(R.id.update_department);
    officeBox = (EditText)findViewById(R.id.update_office);
    emailBox = (EditText)findViewById(R.id.update_email);
    phonenoBox = (EditText)findViewById(R.id.update_phoneno);
    passwordBox = (EditText)findViewById(R.id.update_password);
    confirm_passwordBox = (EditText)findViewById(R.id.update_confirm_password);
    new GetUserData().execute();
    register = (Button)findViewById(R.id.update_register); 
    register.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }

    });

   }

class GetUserData extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... arg0) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", user));
        // getting JSON string from URL
        JSONObject json = jsonParser.makeHttpRequest(url_get_user_data, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("User Data: ", json.toString());

        try {
            // Checking for SUCCESS TAGh
            int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully received product details
                    JSONArray userObj = json
                            .getJSONArray("data"); // JSON Array

                    // get first product object from JSON Array
                    JSONObject user = userObj.getJSONObject(0);             


                    //firstnameBox.setText(user.getString("firstname"));
                    firstnameBox.setText("lsdf;skdjf", TextView.BufferType.EDITABLE);
                    /*lastnameBox.setText(user.getString("lastname"));
                    departmentBox.setText(user.getString("department"));
                    officeBox.setText(user.getString("office"));
                    emailBox.setText(user.getString("email"));
                    phonenoBox.setText(user.getString("phoneno"));
                    passwordBox.setText(user.getString("password"));
                    statusBox.setText(user.getString("status"));
*/

            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        AdminHomeActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.profile, menu);
    return true;
}

}

This is the Logcat Error

 04-06 22:31:25.725: E/AndroidRuntime(644): FATAL EXCEPTION: AsyncTask #1
 04-06 22:31:25.725: E/AndroidRuntime(644): java.lang.RuntimeException: An error occured while executing doInBackground()
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.os.AsyncTask$3.done(AsyncTask.java:266)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.lang.Thread.run(Thread.java:1020)
 04-06 22:31:25.725: E/AndroidRuntime(644): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.checkThread(ViewRoot.java:3392)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.invalidateChild(ViewRoot.java:597)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:645)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:3691)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.View.invalidate(View.java:7141)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.invalidateCursor(TextView.java:3866)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.spanChange(TextView.java:6932)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:7058)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:918)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:615)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:518)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.Selection.setSelection(Selection.java:74)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.Selection.setSelection(Selection.java:85)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:288)  
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.setText(TextView.java:2814)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.setText(TextView.java:2691)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.EditText.setText(EditText.java:78)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at com.example.fproject.ProfileActivity$GetUserData.doInBackground(ProfileActivity.java:100)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at com.example.fproject.ProfileActivity$GetUserData.doInBackground(ProfileActivity.java:1)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.os.AsyncTask$2.call(AsyncTask.java:252)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 04-06 22:31:25.725: E/AndroidRuntime(644):     ... 4 more

Thanks!..Please advice me on what to do


Answer:

You are trying to change your UI from the AsyncTask's doInBackground(), but runs on a background thread, not the main thread (or UI thread). That's what onPostExecute() is for, since AsyncTask makes it run on the UI thread right after doInBackground finishes.

My suggestion:

  1. Change the result type of your AsyncTask class to JSONObject:

    class GetUserData extends AsyncTask<String, String, JSONObject> {

  2. Change the return type of doInBackground() to JSONObject:

    protected JSONObject doInBackground(String... arg0) {

  3. Return the JSONObject object user, and remove all the UI-related code you commented out and also line 100

    JSONObject user = userObj.getJSONObject(0); return user;

  4. Put the UI-related code in a new method onPostExecute()

`@Override protected void onPostExecute (JSONObject user) { if (user == null) { return; // nothing to be done }

try {
    firstnameBox.setText(user.getString("firstname"));
    lastnameBox.setText(user.getString("lastname"));
    departmentBox.setText(user.getString("department"));
    officeBox.setText(user.getString("office"));
    emailBox.setText(user.getString("email"));
    phonenoBox.setText(user.getString("phoneno"));
    passwordBox.setText(user.getString("password"));
    statusBox.setText(user.getString("status"));
} catch(JSONException e) {
  // process your exception
}

} `

Question:

I'm making a simple app on android studio. MainActivity has a ListView which have items from string-array, and if I click an item, a AlterDialog is shown. The dialog has an EdixText. I write text on it, and if I click the positive button, the TextView of item I clicked is changed to what I just write. Sorry for my bad English... Anyway, here is my source code for MainActivity.

package com.softdept.sangkyu.swex01;

import ...

public class SWEX01 extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swex01);
    ListAdapter myAdapter = new MyAdapter(this, getResources().getStringArray(R.array.tvshow));
    ListView tvShowList = (ListView)findViewById(R.id.listView);
    tvShowList.setAdapter(myAdapter);
    tvShowList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
            final TextView textView = (TextView)view.findViewById(R.id.textView);
            String showName = textView.getText().toString();
            Toast.makeText(parent.getContext(), showName, Toast.LENGTH_SHORT).show();
            AlertDialog.Builder dialog = new AlertDialog.Builder(parent.getContext());
            dialog.setTitle("Modify TV show");
            dialog.setMessage(showName);
            final EditText editText = new EditText(getApplicationContext());
            dialog.setView(editText);
            dialog.setNegativeButton("Cancel", null);
            dialog.setPositiveButton("Modify", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String editShowName = editText.getText().toString();
                    textView.setText(editShowName);
                    Toast.makeText(parent.getContext(), "Modified!", Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show();
        }
    });
}
}

I ran this app and on emulator with my keyboard input worked well. However, I also ran on my android device and when I clicked the button, the text is unchanged... What's wrong with my code??


Answer:

This is how it is worked for me after changing few lines of code.

final String[] items=getResources().getStringArray(R.array.tvshow);

//you can carry on with ListAdapter.

final ArrayAdapter myAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,items);

//Inside onClick method of PositiveButton

items[position]=editShowName; myAdapter.notifyDataSetChanged();

You need to call Adapter.notifyDataSetChanged() whenever the adapter's data changes.

Question:

I'm making an app where multiple people are able to edit the same document in realtime and I'm doing this via syncing a noSql database against the editext view in the the app, but I have a problem doing this as when I try to use setText to sync the database it moves the text cursor, so, is there anyway to not make this happen?

Thanks in advance!


Answer:

  • Read cursor position
  • Set new text
  • set cursor position to what it was previously

Question:

Hello i have a question that is the one which i put in title. I have this example that i extract from my code

String text = "Test";
EditText editText = (EditText) findViewById(R.id.idField);
editText.setText(text);

And I can't convert int o charSequence My objective is put a string into the editText.setText();

Here is my onCreate:

    protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    try {
        fileExist();
        sessionTimeOut();
        passwordValidation(getLocalPassword());
    } catch (FileNotExistException e) {
        setLoginActivity();
    } catch (SessionTimeOutException e) {
        String text="Sometext";
        EditText editText = (EditText) findViewById(R.id.usernameField);
        setLoginActivity(R.string.sessionOut);
               editText.setText(text);


    } catch (PasswordInvalidException e) {
        setLoginActivity(R.string.criterios);
    }
    setWelcomeBackLayout();
}

The error is located where editText.setText(text); is located

There is my error:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: pt.edu.es_loule, PID: 3498
              java.lang.RuntimeException: Unable to start activity ComponentInfo{pt.edu.es_loule/pt.edu.es_loule.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
                  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.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
                  at pt.edu.es_loule.LoginActivity.onCreate(LoginActivity.java:46)
                  at android.app.Activity.performCreate(Activity.java:6999)
                  at android.app.Activity.performCreate(Activity.java:6990)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                  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) 

Answer:

Check your layout xml file, you editText variable is null because your reference "idField" is incorrect.

Don't forget to call setContentView(R.layout.yourlayout) before you get the reference of your view.


UPDATE

You forgot to call to setContentView method

 protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout_file);
  ...

Question:

I'm beginner in android development and i'm trying to build an app with multiple equations and i need the result to be viewed in one text and in vertical lines every result for equation viewed in line, i know how to show them together but it will show them either for the same line or in un-arranged manner like this code:

Result.setText("MDRD=" + Double.toString(m) + " MDRD.abbv" + Double.toString(b));

,, So what i have to do to show them like this????

MDRD= 9999 // any number

MDRD.abbv =8888 // any number

,, in another way :

if i have an equation and i want show the result in text, i'll use "Result.setText", also if i want to show more than one equation's result in the same text "Result", i can use "+", but what i want to show more than one equation's result in the same text "Result" but every equation's result appear in one line


Answer:

If I understood your question right you are trying to add a line break to textview (Result)?! This can be easily achieved by adding a newline \n to your String:

Result.setText("MDRD=" + Double.toString(m) + "\nMDRD.abbv" + Double.toString(b));