Hot questions for Using Android EditText in textview

Question:

In my app, I have to switch between two layouts frequently. The error is happening in the layout posted below.

When my layout is called the first time, there isn't occurring any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it gives me the following error:

> FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My layout-code looks like this:

    tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code


private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

I know this question has been asked before, but it didn't help in my case.


Answer:

The error message says what You should do.

// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

Question:

New SO user here and fairly new to Java. Upon running this, it crashes with a java.lang.stackoverflow error. I'm fairly certain it is recursive but I can't figure out why. I've tried stepping through debugging but I get an error that it can't find the class file. Here is the code:

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

    newPrice.addTextChangedListener(tradeWatch);
    tradeIn.addTextChangedListener(tradeWatch);
    acc.addTextChangedListener(tradeWatch);
    tradeDif.addTextChangedListener(tradeWatch);

}

TextWatcher tradeWatch = new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {
        calcTrade();

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

    }

};

private void calcTrade() {
Editable eValue1 = newPrice.getText(), eValue2 = tradeIn.getText(), eValue3 = acc.getText();
Double value1 = 0.0, value2 = 0.0, value3 = 0.0, result = 0.0;

if (eValue1 != null)
    value1 = toDouble(eValue1);
if (eValue2 != null)
    value2 = toDouble(eValue2);
if (eValue3 != null)
    value3 = toDouble(eValue3);
if (value1 != null && value2 != null && value3 != null)
    result = value1 - (value2 + value3);
    tradeDif.setText(result.toString());

}
private double toDouble(final Editable editable) {
    final String content = editable.toString();
    if (content.isEmpty()) {
        return 0;
    }
    return Double.parseDouble(content);
}

public void nextPage(View v) {
    Intent i=new Intent(this, Activity2.class);
    startActivity(i);
}


}

Answer:

Problem is line:

tradeDif.setText(result.toString());

You change text and it causes to call

afterTextChanged(Editable s) 

again and again.

Simple solution
  1. Remove listener
  2. Change value
  3. Add listener

Question:

I've been using a reflection method to set my EditText's cursor colors programmatically which I found from this answer (I also tried this answer). However, after some recent updates, can't remember exactly when, that method no longer works, I assume that Android has probably changed something in the TextView class. Anyways, can someone help me with this? Are there now new field names for mCursorDrawableRes and mCursorDrawable, or is that whole method invalid and needs to be implemented another way now?

Update: I just found out that this method stopped working only on Android P, on the previous versions, it still works.

Update 2: I solved problem myself, check the answer if you are stuck as well.


Answer:

OK, after digging into the Android Pie Source Code, I found out that Google has changed mCursorDrawable to mDrawableForCursor, and also changed its type from a two element Drawable array to simply Drawable, so I made some changes based on the original reflection method, and now it works for Android P:

 public static void setEditTextCursorColor(EditText editText, int color) {
    try {
        // Get the cursor resource id
        if(Build.VERSION.SDK_INT >= 28){//set differently in Android P (API 28)
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            int drawableResId = field.getInt(editText);

            // Get the editor
            field = TextView.class.getDeclaredField("mEditor");
            field.setAccessible(true);
            Object editor = field.get(editText);

            // Get the drawable and set a color filter
            Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId);
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

            // Set the drawables
            field = editor.getClass().getDeclaredField("mDrawableForCursor");
            field.setAccessible(true);
            field.set(editor, drawable);
        }else {
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            int drawableResId = field.getInt(editText);

            // Get the editor
            field = TextView.class.getDeclaredField("mEditor");
            field.setAccessible(true);
            Object editor = field.get(editText);

            // Get the drawable and set a color filter
            Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId);
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            Drawable[] drawables = {drawable, drawable};

            // Set the drawables
            field = editor.getClass().getDeclaredField("mCursorDrawable");
            field.setAccessible(true);
            field.set(editor, drawables);
        }
        setEditTextHandleColor(editText, color);
    } catch (Exception ignored) {
    }
}

Side note, I really wish Google could just add a public method like setCursorDrawable() or something like that, that would've been much easier.

Question:

I have some troubles trying to put an id to a dynamic edittext and texview in Android Studio, i want to use this id to get the id's in another functions. Note: Im not setting any id in the onCreate function.

This is my code:

            for (Map.Entry<String,String> entry : getMap(newContact).entrySet()) {
            total++;
            TextView ProgrammaticallyTextView = new TextView(this.getActivity());
            EditText ProgrammaticallyEditText = new EditText(this.getActivity());
            ProgrammaticallyTextView.setId(total);
            ProgrammaticallyEditText.setId(total+1);
            ProgrammaticallyTextView.setText(entry.getKey());
            ProgrammaticallyEditText.setText(entry.getValue());

            linearLayout.addView(ProgrammaticallyTextView);
            linearLayout.addView(ProgrammaticallyEditText);

            total++;
        }

This is the function that i use the edittext and textview id's

    public void onClick(View v) {
    switch (v.getId()) {

        case R.id.btn_create:

            String test = "";

            for(int i=0; i < (this.total); i+=2){
                TextView tv = (TextView) v.findViewById(i++);
                EditText et = (EditText) v.findViewById(i+2);
                if ((i+2) >= this.total){
                    test += tv.getText()+"="+et.getText();
                }else
                {
                    test += tv.getText()+"="+et.getText()+",";
                }

            }

            mContact = getMap(test);
            newContactRequest();
            break;

    }
}

I appreciate any help!


Answer:

You need to explicitly change the data type to string. Just writing i++ tries to assign that value as an integer. I think if you change your lines to these it should work.

TextView tv = (TextView) v.findViewById(String.valueOf(i++));
EditText et = (EditText) v.findViewById(String.valueOf(i+2));

Question:

Here is my EditText. Why isn't allowing multiple lines?

<EditText
    android:id="@+id/edtextDesigner"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toggleText"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:alpha="0.5"
    android:background="@drawable/rounded_corner"
    android:ems="10"
    android:lines="2"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:fontFamily="sans-serif-light"
    android:inputType="textMultiLine"
    android:padding="10dp"
    android:scrollHorizontally="false"
    android:textColor="#000000"
    android:textSize="16sp"
    android:typeface="sans"
    android:text=" "
    android:visibility="invisible" />

I've also set it programmatically.

        edit_View.setSingleLine(false);
        edit_View.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
        edit_View.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);

I'm at a complete loss as to why this isn't working.


Answer:

I had this issue very recently. I found that setting the inputType programmaticly resets most options so you will have to set them after. I think changing your code to this may work:

edit_View.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
edit_View.setSingleLine(false);
edit_View.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);

Question:

This is my problem right now, guys.

I have the next TextView and EditText

activity_profile.xml
<TextView
            android:layout_marginEnd="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/done"
            android:id="@+id/done_profile_btn"
            android:textColor="@color/white"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:id="@+id/input_profile_swift"
            android:hint="@string/swift"
            android:inputType="textCapCharacters"
            android:textColor="@color/colorPrimaryDark"
            android:layout_marginBottom="22dp"
            android:maxLines="1"
            android:imeOptions="actionDone"/>

And I would like to change the action that press the 'Done' button on the keyboard does for the EditText in order to do the same as the TextView, which does the next:

ProfileActivity.java
done_btn = (TextView) findViewById(R.id.done_profile_btn);
swift = (EditText)findViewById(R.id.input_profile_swift);
done_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //saveChanges();
                //finish();
                Toast.makeText(getApplicationContext(), "Your changes have been saved", Toast.LENGTH_SHORT).show();
            }
        });
...

So... I want that both (press 'Done' on my keyboard and press the TextView) do the same.

Any idea of how to do that? Thank you very much.


Answer:

You can use this one also (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:

swift.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
              //saveChanges();
              //finish();
              Toast.makeText(getApplicationContext(), "Your changes have been saved", Toast.LENGTH_SHORT).show();
            }    
            return false;
        }
    });

Hope it will help !

Question:

I'm creating an nfc reader. I followed the tutorial and it work well. The result will show the value in the nfc tag eg; 123456 in a Textview. How can I change the result to put in the Editview? I already try but still, not luck. MainActivity.java

package net.vrallev.android.nfc.demo;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

/**
* Activity for reading data from an NDEF Tag.
* 
* @author Ralf Wondratschek
*
*/
public class MainActivity extends Activity {

public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcDemo";

private TextView mTextView;
private NfcAdapter mNfcAdapter;

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

    mTextView = (TextView) findViewById(R.id.textView_explanation);

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (mNfcAdapter == null) {
        // Stop here, we definitely need NFC
        Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
        finish();
        return;

    }

    if (!mNfcAdapter.isEnabled()) {
        mTextView.setText("NFC is disabled.");
    } else {
        mTextView.setText(R.string.explanation);
    }

    handleIntent(getIntent());
}

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

    /*
     * It's important, that the activity is in the foreground (resumed). Otherwise
     * an IllegalStateException is thrown. 
     */
    setupForegroundDispatch(this, mNfcAdapter);
}

@Override
protected void onPause() {
    /*
     * Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
     */
    stopForegroundDispatch(this, mNfcAdapter);

    super.onPause();
}

@Override
protected void onNewIntent(Intent intent) {
    /*
     * This method gets called, when a new Intent gets associated with the current activity     instance.
     * Instead of creating a new activity, onNewIntent will be called. For more information have   a look
     * at the documentation.
     * 
     * In our case this method gets called, when the user attaches a Tag to the device.
     */
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

        String type = intent.getType();
        if (MIME_TEXT_PLAIN.equals(type)) {

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            new NdefReaderTask().execute(tag);

        } else {
            Log.d(TAG, "Wrong mime type: " + type);
        }
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {

        // In case we would still use the Tech Discovered Intent
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String[] techList = tag.getTechList();
        String searchedTech = Ndef.class.getName();

        for (String tech : techList) {
            if (searchedTech.equals(tech)) {
                new NdefReaderTask().execute(tag);
                break;
            }
        }
    }
}

/**
 * @param activity The corresponding {@link Activity} requesting the foreground dispatch.
 * @param adapter The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);

    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][]{};

    // Notice that this is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    try {
        filters[0].addDataType(MIME_TEXT_PLAIN);
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("Check your mime type.");
    }

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}

/**
 * @param activity The corresponding {@link BaseActivity} requesting to stop the foreground dispatch.
 * @param adapter The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    adapter.disableForegroundDispatch(activity);
}

/**
 * Background task for reading the data. Do not block the UI thread while reading. 
 * 
 * @author Ralf Wondratschek
 *
 */
private class NdefReaderTask extends AsyncTask<Tag, Void, String> {

    @Override
    protected String doInBackground(Tag... params) {
        Tag tag = params[0];

        Ndef ndef = Ndef.get(tag);
        if (ndef == null) {
            // NDEF is not supported by this Tag. 
            return null;
        }

        NdefMessage ndefMessage = ndef.getCachedNdefMessage();

        NdefRecord[] records = ndefMessage.getRecords();
        for (NdefRecord ndefRecord : records) {
            if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                try {
                    return readText(ndefRecord);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "Unsupported Encoding", e);
                }
            }
        }

        return null;
    }

    private String readText(NdefRecord record) throws UnsupportedEncodingException {
        /*
         * See NFC forum specification for "Text Record Type Definition" at 3.2.1 
         * 
         * http://www.nfc-forum.org/specs/
         * 
         * bit_7 defines encoding
         * bit_6 reserved for future use, must be 0
         * bit_5..0 length of IANA language code
         */

        byte[] payload = record.getPayload();

        // Get the Text Encoding
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";

        // Get the Language Code
        int languageCodeLength = payload[0] & 0063;

        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
        // e.g. "en"

        // Get the Text
        return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            mTextView.setText("Read content: " + result);
        }
    }
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView_explanation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/explanation" />

</RelativeLayout>

androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.vrallev.android.nfc.demo"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.NFC" />

<uses-feature
    android:name="android.hardware.nfc"
    android:required="true" />

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="net.vrallev.android.nfc.demo.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>
</application>

</manifest>

Answer:

Add an EditText to your layout:

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

And now add this code to MainActivity class:

...

public class MainActivity extends Activity {

public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcDemo";

private TextView mTextView;
private NfcAdapter mNfcAdapter;
private EditText mEditText;

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

    mTextView = (TextView) findViewById(R.id.textView_explanation);
    mEditText = (EditText) findViewById(R.id.editText1);

    //Set Text View value in Edit Text
    mEditText.setText(mTextView.getText().toString());

    ...
}


...

Question:

I have an EditText field for name field and a button. When I type a name in the field and press the button. It should show "Hi, " + value of EditText field.

My solution is to getText().toString() on the EditText object and passed it to a string variable. But it returns "" whenever I use it to setText().

I used this instead and it works but i'm confused what's the difference ? nametext.setText("Hi,nametext.getText().toString());

Button btn_show;
EditText nametext;
String input_msg;

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

    nametext = findViewById(R.id.name_text);
    input_msg = nametext.getText().toString();

    btn_show = findViewById(R.id.hi);

    btn_show.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nametext.setText("Hi, " + input_msg);  // this returns ""

        /* when i use nametext.getText().toString() in place of input_msg
        /* it returns the string I typed in the edittext. What's the 
        /* difference?
        /* nametext.setText("Hi,nametext.getText().toString()); // returns the actual string I typed in the edittext field

        }
    });
}

nametext.setText("Hi,nametext.getText().toString()); // returns the actual string typed in the field

nametext.setText("Hi, " + input_msg); // returns ""


Answer:

Hello there you are doing it in a right way just a little mistake that you are calling getText() before Click.

btn_show.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        input_msg = nametext.getText().toString();
        nametext.setText("Hi, " + input_msg); 
  }
 });

Question:

Hello I just wanna ask about this code, the problem is I just want to show the getData in an EditTextview. But it only shows in a toast what do you think will be thre revisions needed for my code to call the data in getData into a EditText thank you so much for the help.

package com.example.serviceapplication;


    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;


    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.app.AppCompatActivity;

    public class Timeinsms extends AppCompatActivity {

    DatabaseHelper myDb;
    EditText editTextId,editTextsmsi;
    Button btngetData,btnView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeinsms);
        myDb = new DatabaseHelper(this);
        editTextId = (EditText) findViewById(R.id.editText_idin);
        btngetData = (Button) findViewById(R.id.button_view);
        btnView = (Button) findViewById(R.id.button_viewALL);
        getData();
        viewAll();

    }



    public void getData() {
        btngetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = editTextId.getText().toString();

                if (id.equals(String.valueOf(""))) {
                    editTextId.setError("Enter id to get data");
                    return;
                }
                Cursor res = myDb.getData(id);
                String data = null;
                if (res.moveToFirst()) {

                    data =

                                    "Id:" + res.getString(0) + "\n\n" +
                                    "Time In :" + res.getString(1) + "\n\n" +
                                    "Customer :" + res.getString(2) + "\n\n"+
                                    "Branch :" + res.getString(3) + "\n\n"+
                                    "Machine :" + res.getString(4) + "\n\n";

                }
                showMessage("TIME OUT FORM"+"\n\n", data);
            }
        });
    }


    public void viewAll(){
        btnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor res=myDb.getAllData();
                if(res.getCount() == 0) {
                    showMessage("Error","Nothing found");
                    return;
                }
                StringBuffer buffer=new StringBuffer();
                while(res.moveToNext()){
                    buffer.append("Id:"+res.getString(0)+"\n\n");
                    buffer.append("Time :"+ res.getString(1)+"\n\n");
                    buffer.append("Customer :"+ res.getString(2)+"\n\n");
                    buffer.append("Branch :"+ res.getString(3)+"\n\n");
                    buffer.append("Machine :"+ res.getString(4)+"\n\n\n");
                }
                showMessage("Time In History",buffer.toString());
            }
        });
    }




    private void showMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.create();
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();

    }

}

Answer:

You are not showing it in a Toast, you are using an Alertdialog to Show your Message. This would be a Toast

Toast.makeText(this,"MESSAGE TO SHOW",Toast.LENGTH_LONG).show();

At this Position

data =                      "Id:" + res.getString(0) + "\n\n" +
                            "Time In :" + res.getString(1) + "\n\n" +
                            "Customer :" + res.getString(2) + "\n\n"+
                            "Branch :" + res.getString(3) + "\n\n"+
                            "Machine :" + res.getString(4) + "\n\n";

you are already creating a String which contains all your data, you only have to set your Edittext with this String.

editTextId.setText("TIME OUT FORM"+"\n\n"+data);

This must be placed inside the OnClick method, as data is a local variable at this method.

Question:

Why the name and date are not shown on the editText? The flow of activity is WorkDetailsTable>>DisplayData>>UpdatePage

I had implemented a tableListener in DisplayData. When the row is pressed, it will goes to Update.java

WorkDetailsTable.java

 Button btn1 = (Button) findViewById(R.id.button2);
        btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
        AlertDialog.Builder builder = new AlertDialog.Builder(WorkDetailsTable.this);
                builder.setTitle("Data Saved");
                builder.setMessage("Are you sure you want to save?");
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int ii) {
                   if ((i != null && i.trim().length() > 0)) {
                    long ab = ts.insertTimeSheet(name, weather, date, status,b,i);
                    long cf= WF.insertWorkForce(subContractors, noPeople, noHours, ab);
                     WD.insertWorkDetails(a1, W1, P1, b, c,cf);
                     WD.insertWorkDetails(a2, W2, P2, d, e1,cf);
                     WD.insertWorkDetails(a3, W3, P3, f, g,cf);
                     WD.insertWorkDetails(a4, W4, P4, h, i,cf);
                     WF.insertWorkForce(subContractors, noPeople, noHours,cf);
                     Toast.makeText(getApplicationContext(), "4 Row has value", Toast.LENGTH_LONG).show();
                      Intent intent=new 

                     Intent(WorkDetailsTable.this,DisplayData.class);
                     intent.putExtra("name", name);
                     intent.putExtra("date",date);
                     startActivity(intent);
}
}

DisplayData.java

public class DisplayData extends AppCompatActivity {

    TableLayout table_layout;
    InfoAPI sqlcon;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaydata);
        MyDatabaseHelper db = new MyDatabaseHelper(this);
        InfoAPI I1 = new InfoAPI(this);
        sqlcon = new InfoAPI(this);


        //Table table=(TableLayout)findViewById(R.id.table)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        table_layout = (TableLayout) findViewById(R.id.tableLayout1);
        final String name1 = getIntent().getExtras().getString("name");
        final String date=getIntent().getExtras().getString("date");
          BuildTable(name1,date);


    }


    private void BuildTable(String name,String date1)
    {
        final String name2 = name;
        final String date2=date1;
        sqlcon.open();
        Cursor c = sqlcon.readEntry(name2);

        int rows = c.getCount();
        int cols = c.getColumnCount();

        c.moveToFirst();

        TableRow rowDayLabels=new TableRow(this);
        TextView weather=new TextView(this);
        weather.setText("Weather");
        weather.setTypeface(Typeface.SERIF, Typeface.BOLD);

        TextView date=new TextView(this);
        date.setText("Date");
        date.setTypeface(Typeface.SERIF, Typeface.BOLD);

        TextView status=new TextView(this);
        status.setText("Status");
        status.setTypeface(Typeface.SERIF, Typeface.BOLD);

        TextView timeIn=new TextView(this);
        timeIn.setText("Time In");
        timeIn.setTypeface(Typeface.SERIF, Typeface.BOLD);

        TextView timeOut=new TextView(this);
        timeOut.setText("Time Out");
        timeOut.setTypeface(Typeface.SERIF, Typeface.BOLD);

        rowDayLabels.addView(weather);
        rowDayLabels.addView(date);
        rowDayLabels.addView(status);
        rowDayLabels.addView(timeIn);
        rowDayLabels.addView(timeOut);
        table_layout.addView(rowDayLabels);


        // outer for loop
        for (int i = 0; i < rows; i++) {

            TableRow row = new TableRow(this);
            row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));

            // inner for loop
            for (int j = 0; j < cols; j++) {

                TextView tv = new TextView(this);
                tv.setLayoutParams(new TableRow.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                ));
               // tv.setBackgroundResource(R.drawable.cell_shape);
                tv.setGravity(Gravity.CENTER);
                tv.setTextSize(18);
                tv.setPadding(0, 5, 0, 5);

                tv.setText(c.getString(j));

                row.addView(tv);
                row.setBackgroundResource(R.drawable.color);

                row.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        Intent intent = new Intent(DisplayData.this, UpdatePage.class);
                        intent.putExtra("name", name2);
                        intent.putExtra("date",date2);
                        startActivity(intent);
                    }
                });

            }

            c.moveToNext();

            table_layout.addView(row);


        }
        sqlcon.close();
    }

        }

UpdatePage.java

public class UpdatePage extends AppCompatActivity {
    InfoAPI sqlcon;
    private SQLiteDatabase database;
    private MyDatabaseHelper dbHelper;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHelper = new MyDatabaseHelper(this);
        setContentView(R.layout.updatepage);
        final String name1 = getIntent().getExtras().getString("name2");
        final String date = getIntent().getExtras().getString("date2");
        RetrievePage(name1, date);
    }


    public void RetrievePage(String name, String date) {
        final String name2 = name;
        final String date2 = date;
        database = dbHelper.getWritableDatabase();
        final EditText name3 = (EditText) findViewById(R.id.editText9);
        final EditText date3 = (EditText) findViewById(R.id.editText12);
        name3.setText(name2);
        date3.setText(date2);
}
}

Answer:

While sending name and date from WorkDetailsTable>>DisplayData you are using key "name" and "date" properly that is for saving and retrieving same key.

But while sending name and date from DisplayData >>UpdatePage you are not using same key for saving and retrieval snippet of your codeIn DisplayData

 row.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        Intent intent = new Intent(DisplayData.this, UpdatePage.class);
                        intent.putExtra("name", name2);
                        intent.putExtra("date",date2);
                        startActivity(intent);
                    }
                });

While in UpdatePage inside onCreate

    final String name1 = getIntent().getExtras().getString("name2");
    final String date = getIntent().getExtras().getString("date2");

look at the keys..example it is "name" and "name2" so make use of same key change the code to

    final String name1 = getIntent().getExtras().getString("name");
    final String date = getIntent().getExtras().getString("date");

and then check whether you are getting data or not

Question:

I'm just a beginner in Android development.I'm working on an application where I have to retrieve a textview that consists of characters and integers. I want to retrieve only Integers in my Edittext from that textview.

Text that I want to retrieve for Edittext

               <TextView
                android:id="@+id/txt"
                android:layout_width="118dp"
                android:layout_height="38dp"
                android:layout_marginLeft="38dp"
                android:text="Sun Glasses \n    Rs.729"
                android:textColor="@color/colorAccent"
                android:textSize="15sp" />

Edittext is here:

        <EditText
        android:id="@+id/editTextAmount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center" />

My attempt to achieve that:

private EditText editTextAmount;
private String paymentAmount;

private String paymentAmount;

editTextAmount = (EditText) findViewById(R.id.editTextAmount);
amount=(TextView)findViewById(R.id.txt);

editTextAmount.setText(amount.getText().toString());
paymentAmount = editTextAmount.getText().toString();

I tried everything and also followed many tutorials but not getting my desired result. Hope I'll get help from you guys and I will appreciate your help.


Answer:

try this Way

    String amount = amount.getText().toString();
String getNum = ExtractNumberFromString(amount);
paymentAmount.setText(getNum);

    public static String ExtractNumberFromString(String cnvrtdDate){
        String [] dateArray = cnvrtdDate.split("|");

        StringBuilder sb = new StringBuilder();
           StringBuilder sb1 = new StringBuilder();
        for(int i=0;i<dateArray.length;i++)
        {
            boolean ItIs = isNumeric(dateArray[i]);
            if(ItIs)
            {

                sb.append(dateArray[i]);
            }
            else
            {
                sb1.append(dateArray[i]);
            }
        }

    System.out.println("Numbers="+sb);
    System.out.println("Characters="+sb1);
        return  sb.toString();
    }


        public static boolean isNumeric(String str)
        {
            try
            {
                int d = Integer.parseInt(str);
            }
            catch(Exception nfe)
            {
                return false;
            }
            return true;
        }