How to pass get text from userinput (edittext) and

2019-09-04 14:13发布

问题:

    I would like to take user input entered in the EditTextField(in the EnterNewFile class) and put it into the TextField (in the NoteEdit class). Please help! Thanks! FYI- I use XML files for the layouts of these two classes.


               ***********EnterNewFile.class*********

                package com.example.note;

                import android.app.Activity;
                import android.content.Intent;
                import android.os.Bundle;
                import android.util.Log;
                import android.view.View;
                import android.widget.Button;
                import android.widget.EditText;

                public class EnterNewFile extends Activity {
                    public EditText mText;
                    public Button mButton;

                    public final static String EXTRA_MESSAGE = "com.example.note.MESSAGE";


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.new_file_start);

                        mText = (EditText)findViewById(R.id.file_name_edittext);
                        mButton = (Button)findViewById(R.id.next_button);

                    }


                    public void nextButton(View view)
                    {      
                        /** Called when the user clicks the Next button */
                        Log.d("EditText", mText.getText().toString());

                        mText.getText().toString();

                        Intent intent = new Intent(this, NoteEdit.class);
                        EditText editText = (EditText) findViewById(R.id.file_name_edittext);
                        String message = editText.getText().toString();
                        intent.putExtra(EXTRA_MESSAGE, message);
                        startActivity(intent);



                        //

                    }
                    }
            ******************************************
            ********NoteEdit.class************
            package com.example.note;

            import java.text.SimpleDateFormat;
            import java.util.Date;

            import android.app.Activity;
            import android.app.AlertDialog;
            import android.content.Context;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.graphics.Canvas;
            import android.graphics.Color;
            import android.graphics.Paint;
            import android.graphics.Rect;
            import android.os.Bundle;
            import android.util.AttributeSet;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.EditText;
            import android.widget.TextView;

            public class NoteEdit extends Activity{

                public static int numTitle = 1; 
                public static String curDate = "";
                public static String curText = "";  
                private TextView mTitleText;
                private EditText mBodyText;
                private TextView mDateText;
                private Long mRowId;


                private Cursor note;

                private NotesDbAdapter mDbHelper;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);


                    mDbHelper = new NotesDbAdapter(this);
                    mDbHelper.open();        

                    setContentView(R.layout.note_edit_add);
                    setTitle(R.string.app_name);


                    mTitleText = (TextView) findViewById(R.id.title);
                    mBodyText = (EditText) findViewById(R.id.body);
                    mDateText = (TextView) findViewById(R.id.notelist_date);

                    long msTime = System.currentTimeMillis();  
                    Date curDateTime = new Date(msTime);

                    SimpleDateFormat formatter = new SimpleDateFormat("M'/'d'/'y");  
                    curDate = formatter.format(curDateTime);        

                    mDateText.setText(""+curDate);

                    // Get the message from the intent
                    Intent intent = getIntent();
                    String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);

                    // Create the text view
                    // TextView textView = new TextView(this);
                    mTitleText.setText(message);

                    // Set the text view as the activity layout
                   // setContentView(textView);


            //        mTitleText.setText(dana);


                    mRowId = (savedInstanceState == null) ? null :
                        (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
                    if (mRowId == null) {
                        Bundle extras = getIntent().getExtras();
                        mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
                                                : null;
                    }

                    populateFields();

                }
                  public void addFiles(View view)
                    {
                        /*Intent addFilesTarget = new Intent(this, Welcome.class);
                        startActivity(addFilesTarget);*/
                    }


                  public static class LineEditText extends EditText{
                        // we need this constructor for LayoutInflater
                        public LineEditText(Context context, AttributeSet attrs) {
                            super(context, attrs);
                                mRect = new Rect();
                                mPaint = new Paint();
                                mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
                                mPaint.setColor(Color.BLUE);
                        }

                        private Rect mRect;
                        private Paint mPaint;       

                        @Override
                        protected void onDraw(Canvas canvas) {

                            int height = getHeight();
                            int line_height = getLineHeight();

                            int count = height / line_height;

                            if (getLineCount() > count)
                                count = getLineCount();

                            Rect r = mRect;
                            Paint paint = mPaint;
                            int baseline = getLineBounds(0, r);

                            for (int i = 0; i < count; i++) {

                                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
                                baseline += getLineHeight();

                            super.onDraw(canvas);
                        }

                    }
                  }

                  @Override
                    protected void onSaveInstanceState(Bundle outState) {
                        super.onSaveInstanceState(outState);
                        saveState();
                        outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
                    }

                    @Override
                    protected void onPause() {
                        super.onPause();
                        saveState();
                    }

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

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

                    @Override
                    public boolean onOptionsItemSelected(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.menu_about:

                            /* Here is the intro about myself */            
                            AlertDialog.Builder dialog = new AlertDialog.Builder(NoteEdit.this);
                            dialog.setTitle("About");
                        dialog.setMessage("Hello! I'm Dana, creator of this application. This is for documenting research."
                                +"\n melaninabeauty@gmail.com");
                            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                                   @Override
                                   public void onClick(DialogInterface dialog, int which) {
                                       dialog.cancel();

                                   }
                               });
                               dialog.show();              
                               return true;
                        case R.id.menu_delete:
                            if(note != null){
                                note.close();
                                note = null;
                            }
                            if(mRowId != null){
                                mDbHelper.deleteNote(mRowId);
                            }
                            finish();

                            return true;
                        case R.id.menu_save:
                            saveState();
                            finish();           
                        default:
                            return super.onOptionsItemSelected(item);
                        }
                    }

                    private void saveState() {
                        String title = mTitleText.getText().toString();
                        String body = mBodyText.getText().toString();


                        if(mRowId == null){
                            mDbHelper.createNote(title, body, curDate);
                        }else{
                            mDbHelper.updateNote(mRowId, title, body, curDate);
                        }
                    }


                    private void populateFields() {
                        if (mRowId != null) {
                            note = mDbHelper.fetchNote(mRowId);
                            startManagingCursor(note);

                            mTitleText.setText(note.getString(
                                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
                            mBodyText.setText(note.getString(
                                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
                            curText = note.getString(
                                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
                        }
                    }



            }
        ***********************************
        ****AndroidManifest.xml****
        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.note"
            android:versionCode="1"
            android:versionName="1.0" >

             <uses-sdk
                android:minSdkVersion="8"
                android:targetSdkVersion="18" />  

            <application
                android:allowBackup="true"
                android:icon="@drawable/ic_launcher"
                android:label="@string/app_name"
                android:theme="@style/AppTheme" >
                <activity
                    android:name="com.example.note.Welcome"
                    android:label="@string/app_name" >
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>

                <activity
                    android:name="com.example.note.NoteList">   
                </activity>

                <activity
                    android:name="com.example.note.NoteEdit">

                </activity>
                <activity
                    android:name="com.example.note.Export">   
                </activity>
                <activity
                    android:name="com.example.note.NoteEditAdd">  
                </activity>
                <activity
                    android:name="com.example.note.EnterNewFile">
                </activity>

            </application>

        </manifest>
        <!--
        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.note"
            android:versionCode="1"
            android:versionName="1.0" >

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

            <application
                android:allowBackup="true"
                android:icon="@drawable/ic_launcher"
                android:label="@string/app_name"
                android:theme="@style/AppTheme" >
                <activity android:name="com.example.note.Welcome">
                     <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>
                <activity
                    android:name="com.example.note.NoteList"
                    android:label="@string/app_name" >

                </activity>
                <activity        
                    android:name="com.example.note.NoteEdit"
                    android:label="@string/edit_note"
                    android:parentActivityName="com.example.note.Welcome" >
                      <meta-data 
                    android:name="android.support.PARENT_ACTIVITY"
                        android:value="com.example.note.Welcome" />
                </activity>

            </application>

        </manifest>
        -->


        <!--
               activity 2  android:name= com.example.note.NoteEdit
                    android:label=@string/app_name
                    android:windowSoftInputMode="djustUnspecified/>
        -->
    *****************************

  >  *****LogCat of crash**** Crash occurs after nextButton is clicked****(I inputted the text "nouy", clicked nextButton, then application crashes.********************  

LogCat of crash** Crash occurs after nextButton is clicked*(I inputted the text "nouy", clicked nextButton, then application crashees.**

08-02 20:48:36.703: D/EditText(3575): nouy
08-02 20:48:36.793: I/Choreographer(3575): Skipped 68 frames!  The application may be doing too much work on its main thread.
08-02 20:48:37.143: D/dalvikvm(3575): GC_CONCURRENT freed 1331K, 34% free 2956K/4428K, paused 4ms+59ms, total 137ms
08-02 20:48:37.353: D/AndroidRuntime(3575): Shutting down VM
08-02 20:48:37.394: W/dalvikvm(3575): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-02 20:48:37.443: E/AndroidRuntime(3575): FATAL EXCEPTION: main
08-02 20:48:37.443: E/AndroidRuntime(3575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.NoteEdit}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.os.Looper.loop(Looper.java:137)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at java.lang.reflect.Method.invokeNative(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at java.lang.reflect.Method.invoke(Method.java:511)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at dalvik.system.NativeStart.main(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at com.example.note.NoteEdit.populateFields(NoteEdit.java:231)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at com.example.note.NoteEdit.onCreate(NoteEdit.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.Activity.performCreate(Activity.java:5104)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-02 20:48:37.443: E/AndroidRuntime(3575):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-02 20:48:37.443: E/AndroidRuntime(3575):     ... 11 more
08-02 20:48:40.073: E/Trace(3598): error opening trace file: No such file or directory 

(2)

回答1:

Take the input from Edittext send it through the Intent to your destination activity and then set it in the TextView there.

I think you seem to already be doing that in your code: The issue might be the you've not defined in your XML that nextButton function should be call on click ( inside android:onClick: inside your Button).

What you can also do is, in your onCreate funcion set up a listener which listens to the button click and call the intent from within it.

final EditText editText = (EditText) findViewById(R.id.file_name_edittext);
mButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            /** Called when the user clicks the Next button */
            Log.d("EditText", mText.getText().toString());
            Intent intent = new Intent(EnterNewFile.this, NoteEdit.class);
            String message = editText.getText().toString();
            intent.putExtra(EXTRA_MESSAGE, message);
            startActivity(intent);
        }
    });
//here you are taking value from EditText and send it to other activity:

Instead of

 // Get the message from the intent
 Intent intent = getIntent();
 String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);

use following in onCreate() of your other NoteEdit activity:

Intent intent = getIntent(); 
if((intent.getExtras()!=null) && !intent.getExtras().isEmpty()){
    String message = intent.getExtras().getString(EnterNewFile.EXTRA_MESSAGE);
}


回答2:

this code is working:-

    scrollview=(ScrollView)findViewById(R.id.scrollview1); 
    tb2.setTextSize(30); 
    tb2.setMovementMethod(new ScrollingMovementMethod());
    scrollview.post(new Runnable() { 
    public void run() { 
        scrollview.fullScroll(View.FOCUS_DOWN);  
        }
    }); 
    chat1.setOnClickListener(new OnClickListener() { 
        public void onClick(View v) { 
         {
             textsaring1=edt1.getText().toString();
             tb2.setText(tb2.getText()+" "+textsaring1);
             edt1.setText("");
        } 
        }
    });