无法访问其他类的值

时间:2013-02-01 08:40:32

标签: android class alertdialog

在我的主课程中,我有一个按钮来调用一个显示带有edittext的对话框的类。我的问题是这样 - 主要活动在第一次运行时没有得到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

3 个答案:

答案 0 :(得分:3)

这里有几个问题。

  1. 您不应该在savedValue中阅读onCreate,只有在您实际使用它时才应该这样做。见@ρяσѕρєяK答案。
  2. alert.showAlertDialog无阻止。因此,在显示对话框后,执行行System.out.println("main : " + savedInput);不等待输入。因此,您应该在对话框的确定​​按钮上保存到共享首选项旁边调用其他一些操作。此操作应调用用户在对话框中输入一些文本后应发生的逻辑。
  3. <强>更新

    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();
     }
    

    点击以显示对话框:

    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);
    

    spinnerItemsadapter传递给showAlertDialog

    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();
        }
    });
    

答案 1 :(得分:1)

您需要在按钮点击而不是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);

       }   

   });

或者您将尝试从onResume of Activity获取价值

答案 2 :(得分:0)

这个

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

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

同样的逻辑

savedinput=  prefs.getString("KEY_SAVEDINPUT","");