Passing String values from custom dialog to another activity

穿精又带淫゛_ 提交于 2019-12-11 11:37:31

问题


A custom dialog is being used to take in user input, and then these values are being passed to another activity using getter methods.

But when I pass the values to a method that outputs the string values to a CSV file, shipName, analystName etc the values appear as empty in the file like this, " " although I have entered the values in the dialog.

I debugged the problem by watching the String values in the debug menu's expression window, shipName and analystName but the values never update in the expression window.

I gather from this that the method i which the input is being passed over is not correct.

Does anyone know why the values being output are empty?

This the dialog class being used:

package ie.gmi.computing;



import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.renderscript.Sampler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyMessageDialog {

    private Context context;
    private EditText shipText, scientistNameText , scientistEmailText , volumeText , colourText ;

    private String shipString, scientistNameString , scientistEmailString , volumeString , colourString ;



    public AlertDialog displayMessage(Context context, String title, String message){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        LayoutInflater inflater = LayoutInflater.from(context);
        final View v = inflater.inflate(R.layout.custom_view, null);
        builder.setView(v);
        shipText = (EditText)v.findViewById(R.id.shipNameEditText);
        scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
        scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
        volumeText = (EditText)v.findViewById(R.id.volumeEditText);
        colourText  = (EditText)v.findViewById(R.id.colourEditText);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {



            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog dialog= builder.create();
        dialog.show();
        Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        tb.setOnClickListener(new CustomListener(dialog));

        return dialog;
    }


    //getter/setters to allow access to string values
    //in SearchResult class
    public EditText getShipText() {
        return shipText;
    }



    public void setShipText(EditText shipText) {
        this.shipText = shipText;
    }



    public EditText getScientistNameText() {
        return scientistNameText;
    }



    public void setScientistNameText(EditText scientistNameText) {
        this.scientistNameText = scientistNameText;
    }



    public EditText getScientistEmailText() {
        return scientistEmailText;
    }


    public void setScientistEmailText(EditText scientistEmailText) {
        this.scientistEmailText = scientistEmailText;
    }



    public String getShipString() {
        return shipString;
    }


    public void setShipString(String shipString) {
        this.shipString = shipString;
    }


    public String getScientistNameString() {
        return scientistNameString;
    }


    public void setScientistNameString(String scientistNameString) {
        this.scientistNameString = scientistNameString;
    }


    public String getScientistEmailString() {
        return scientistEmailString;
    }


    public void setScientistEmailString(String scientistEmailString) {
        this.scientistEmailString = scientistEmailString;
    }


    public String getVolumeString() {
        return volumeString;
    }


    public void setVolumeString(String volumeString) {
        this.volumeString = volumeString;
    }


    public String getColourString() {
        return colourString;
    }


    public void setColourString(String colourString) {
        this.colourString = colourString;
    }


    public EditText getVolumeText() {
        return volumeText;
    }



    public void setVolumeText(EditText volumeText) {
        this.volumeText = volumeText;
    }



    public EditText getColourText() {
        return colourText;
    }



    public void setColourText(EditText colourText) {
        this.colourText = colourText;
    }



    @SuppressLint("NewApi")
    class CustomListener implements View.OnClickListener {
        private final Dialog dialog;
        public CustomListener(Dialog dialog) {
            this.dialog = dialog;
        }
        @SuppressLint("NewApi")
        @Override
        public void onClick(View v) {


            if(shipText.getText().toString().isEmpty() && !shipText.getText().toString().equals(null)){
                shipText.setError("The Field is required");

            }else if(scientistNameText.getText().toString().isEmpty() && !scientistNameText.getText().toString().equals(null)){
                scientistNameText.setError("The Field is required");
            }else if(scientistEmailText.getText().toString().isEmpty() && !scientistEmailText.getText().toString().equals(null)){
                scientistEmailText.setError("The Field is required");
            }else if(volumeText.getText().toString().isEmpty() && !volumeText.getText().toString().equals(null)){
                volumeText.setError("The Field is required");
            }else if(colourText.getText().toString().isEmpty() && !colourText.getText().toString().equals(null)){
                colourText.setError("The Field is required");
            }else{
                shipText.setError(null);
                scientistNameText.setError(null);
                scientistEmailText.setError(null);
                volumeText.setError(null);
                colourText.setError(null);


                shipString = shipText.getText().toString();
                scientistNameString = scientistNameText.getText().toString();
                scientistEmailString = scientistEmailText.getText().toString();
                volumeString = volumeText.getText().toString();
                colourString = colourText.getText().toString();


                Toast.makeText(dialog.getContext(), "The Values you get from : " +
                        "\n Ship name value: " + shipText.getText().toString() +
                        "\n Scientist name value: " + scientistNameText.getText().toString() +
                        "\n email value: " + scientistEmailText.getText().toString() +
                        "\n sample volume value: " + volumeText.getText().toString() +
                        "\n sample colour value: " + colourText.getText().toString() , Toast.LENGTH_SHORT).show();

                dialog.dismiss();
            }
        }
    }
}

And this is how I'm retrieving the values in my SearchResult class, when i select the settings button:

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_settings:

            MyMessageDialog dialog =new MyMessageDialog(); 
            dialog.displayMessage(SearchResult.this, "Sample Info", "Required");



            // store / use the values here
            shipName = dialog.getShipString();
            analystName = dialog.getScientistNameString();
            analystEmail = dialog.getScientistEmailString();
            sampleVolume = dialog.getVolumeString();
            sampleColour = dialog.getColourString();
            longitudeValue = String.valueOf(lng);
            latitudeValue = String.valueOf(lat);
            sampleMaterial = message;

            return true;

        default:
          return super.onOptionsItemSelected(item);
        } 
    } 

回答1:


Your dialog showing is asynchronous; that is, code execution in onOptionsItemSelected() does not pause after the call to dialog.displayMessage(), so the getters are returning the initial values for those fields, which is null in all cases. You should create an interface that the Activity implements to receive a callback after those fields are set in the onClick() method of your CustomListener, and update the Activity's variables then.

In the dialog class, we create an interface. For example:

public class MyMessageDialog {
    public interface DialogCallback {
        public void onValuesSet();
    }
    ...
}

Be sure to save a reference to the Context:

public AlertDialog displayMessage(Context context, String title, String message){
    this.context = context;
    ...
}

And at the end of the onClick() method, after the fields' values are set:

((DialogCallback) context).onValuesSet();

The Activity needs to implement the interface we created, the dialog should be a class member, and the fields will be set in the interface's callback method:

public class SearchResult extends Activity 
    implements MyMessageDialog.DialogCallback {
    ...
    MyMessageDialog dialog;

    @Override
    public void onValuesSet()
    {
        shipName = dialog.getShipString();
        analystName = dialog.getScientistNameString();
        ...
    }
    ...
}



回答2:


Does anyone know why the values being output are empty?

Because all statements from getting data from dialog class is executing after dialog.displayMessage on menu option section.

How to get data from MyMessageDialog on Ok button click ?

1. Instead of getting EditText from MyMessageDialog change all getter/setter method return type to String..

2. Create a event Listener using interface for getting event of Alert close on Ok button click in Activity. you can create event listener as:

Android Custom Event Listener

3. call all setter method on Ok button click of Alert. after calling all setter method call event listener method to execute event in Activity after Alert finish.:

      @Override
        public void onClick(DialogInterface dialog, int which) {
             setShipText(shipText.getText().toString());
             setScientistNameText(shipText.getText().toString());
             ....
             //..close alert and call event listener method
        }



回答3:


Your getters don't seem to actually call the getText() method on each EditText view. Modify them do that they do (e.g., scientistNameText.getText()).

PS And, yes, Mike M may indeed write about asyncronicity contributing to the problem. Another approach around that would be to add something like this to the code for each EditText view:

myEditTextView.addTextChangedListener(new TextWatcher() {

        @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

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            //Set the variable here that you call in your getter. Use `getText()` to get the string (e.g., myGetterVariable = myEditTextView.getText().


        }
    }


来源:https://stackoverflow.com/questions/27877258/passing-string-values-from-custom-dialog-to-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!