1

在我的主类中,我有一个按钮来调用一个类,该类显示一个带有编辑文本的对话框。我的问题是 - 主要活动在第一次运行时没有获得 edittext 值,如果我第二次运行它,我会得到旧的 edittext 值。

似乎主活动类执行完整的代码块并返回存储在类中的先前值,我尝试了许多方法,包括共享首选项。

MainActivity.java

public class MainActivity extends Activity {
    EditText comment_et,input_et;
    Spinner spinner;
    Button addbutton,reportbut;
    String input_string,date,time,comment,item;
    TextView date_tv,time_tv;
    String temp[];
    Datas datatemp;
    String savedinput;

    ArrayList<String> list = new ArrayList<String>();


    ArrayAdapter<String> adapter;
    DatabaseHandler db = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) 
{

        SharedPreferences prefs = getSharedPreferences("myprefs", 0);
        savedinput=  prefs.getString("KEY_SAVEDINPUT","");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner = (Spinner)findViewById(R.id.spin1);
        input_et = (EditText)findViewById(R.id.input_et);
        addbutton = (Button)findViewById(R.id.addbutton);
        reportbut = (Button)findViewById(R.id.report);

        comment_et = (EditText)findViewById(R.id.comment_et);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
        date_tv = (TextView)findViewById(R.id.date_tv);
        time_tv = (TextView)findViewById(R.id.time_tv);

        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        date = ""+mDay+"/"+mMonth+1+"/"+mYear;
        time = ""+mHour+":"+mMinute;
        date_tv.setText(date);
        time_tv.setText(time);

        int max_id = db.getDatasCount();

        for(int i = 1; i<max_id+1 ;i++)
         {          

        datatemp = db.getItemOnly(i);
        String s = datatemp._item.toString();
        list.add("   "+ s);
         }


        addbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlertDialogManager alert = new AlertDialogManager();

                alert.showAlertDialog(MainActivity.this, "Enter Item",
                        "Please enter the spinner item",
                        true);
                System.out.println("main : " +savedinput);

            }   

        });



            reportbut.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
                    startActivity(i);

                }

            });


        spinner.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                item = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {


            }
        });

        Button submit = (Button)findViewById(R.id.save);
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) 
            {

                 comment  = comment_et.getText().toString();

                    System.out.println("comment:"+comment);

                /**
                 * CRUD Operations
                 * */
                // Inserting Contacts
                Log.d("Insert: ", "Inserting ..");
                db.addData(new Datas(item, comment, date, time));
                Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
                Toast.LENGTH_LONG).show();
                // Reading all contacts
                Log.d("Reading: ", "Reading all contacts..");
                List<Datas> datas = db.getAllDatas();       

                for (Datas d : datas) {
                    String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
                        // Writing Contacts to log
                Log.d("Item: ", log);
                }
            }
        });
}

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

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

}

AlertDialogManager.java

public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    String savedinput;
    public void showAlertDialog(final Context context, String title, String message,
            Boolean status) 
    {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        //setting input
         final EditText input = new EditText(context);
         alertDialog.setView(input);

         // saving input to a string
         savedinput = input.getText().toString();
         System.out.println(savedinput);

        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                savedinput = input.getText().toString();

                SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
                SharedPreferences.Editor editor =prefs.edit();
                editor.putString("KEY_SAVEDINPUT", savedinput);
                editor.commit();                
                System.out.println("from class "+savedinput);
            }
        });



        // Showing Alert Message
        alertDialog.show();

    }

    String getItem()
    {
        return savedinput;
    }
}

这是我的logcat,只是为了进一步澄清

02-01 13:48:43.372: I/System.out(897): main : firstexecute
02-01 13:48:46.942: W/KeyCharacterMap(897): No keyboard for id 0
02-01 13:48:46.942: W/KeyCharacterMap(897): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 13:48:49.532: I/System.out(897): from class secondexecute
4

3 回答 3

3

你在这里有几个问题。

  1. 您不应该阅读savedValueonCreate只有在实际使用时才应该阅读。请参阅@ρяσѕρєяK 答案。
  2. alert.showAlertDialog是非阻塞的。因此,在显示对话框后System.out.println("main : " + savedInput);执行行。它不会等待您的输入。因此,除了保存到对话框的确定​​按钮上的共享首选项之外,您还应该调用其他一些操作。此操作应调用用户在对话框中输入一些文本后应发生的逻辑。

更新

public void showAlertDialog(final Context context, String title, String message,
                            Boolean status, final Spinner spinner) 
{
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    //setting input
     final EditText input = new EditText(context);
     alertDialog.setView(input);

     // saving input to a string
     savedinput = input.getText().toString();
     System.out.println(savedinput);

    if(status != null)
        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            savedinput = input.getText().toString();
            // do whatever you want with spinner and savedInput here.
        }
    });

    // Showing Alert Message
    alertDialog.show();
 }

onClick 显示对话框:

alert.showAlertDialog(MainActivity.this, "Enter Item",
     "Please enter the spinner item",
     true, (Spinner) findViewById(R.id.spin1));

更新 2 显然您需要将新项目添加到您的微调器适配器。为此,您可以创建所有项目的列表并将此列表与适配器一起传递给对话框。当用户输入字符串并按下 OK 按钮时,onClick方法将此字符串添加到列表中并调用notifyDataSetChanged以更新 UI:

将其添加到MainActivity

List<String> spinnerItems;

onCreate

spinnerItems = new ArrayList<String>();
adapter = enw ArrayAdapter<String>(this, 0, spinnerItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

传递到:spinnerItems_adaptershowAlertDialog

alert.showAlertDialog(MainActivity.this, "Enter Item",
     "Please enter the spinner item",
     true, spinnerItems, adapter);

最后将文本添加到列表并通知适配器:

alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        savedinput = input.getText().toString();
        spinnerItems.add(savedInput);
        adapter.notifyDataSetChanged();
    }
});
于 2013-02-01T08:53:32.210 回答
1

您需要在 Button click 而不是 onCreate 上获取最新值才能从 SharedPreferences 中获取最新值:

addbutton.setOnClickListener(new View.OnClickListener() {

        @Override
         public void onClick(View v) {
           AlertDialogManager alert = new AlertDialogManager();

           alert.showAlertDialog(MainActivity.this, "Enter Item",
                        "Please enter the spinner item",
                        true);
           savedinput=  prefs.getString("KEY_SAVEDINPUT",""); //<<< get value here
           System.out.println("main : " +savedinput);

       }   

   });

或者你会尝试从 Activity 的 onResume 中获取价值

于 2013-02-01T08:48:53.787 回答
0

savedinput = input.getText().toString();

在运行时进行评估。不是你打电话的时候getItem()。在这种情况下,您将获得的值是显示警报之前的值。

同样的逻辑适用

savedinput=  prefs.getString("KEY_SAVEDINPUT","");
于 2013-02-01T08:51:40.593 回答