字符串未被edittext字段填充。 Android的

时间:2013-12-19 22:37:54

标签: android android-edittext android-alertdialog

可能有一个简单的答案:当我的警告框显示时,我尝试将EditText的内容存储在字符串中,但字符串始终为空。

contents = inputElement.getText().toString(); 

代码:

public class MainActivity extends Activity {

EditText inputElement;
Spinner spinner;
MySQLiteAdapters adapter; 
MySQLiteHelper helper_ob;
AlertDialog  dialog;
List<String> lables;
String contents;
ArrayAdapter<String> dataAdapter;
public static final String PREFS = "examplePrefs";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button start = (Button) findViewById(R.id.start);
    //start.setVisibility(View.GONE);
    spinner = (Spinner) findViewById(R.id.spinner1);
    inputElement = new EditText(this);
    adapter = new MySQLiteAdapters(getApplicationContext());
    lables = adapter.getAllLabels();
    exmaplePrefs = getSharedPreferences(PREFS, 0);
    editor = exmaplePrefs.edit();

    final AlertDialog firstTimeUse = new AlertDialog.Builder(this)
            .setView(inputElement)
            .setTitle("TITLE")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, null).create();

    firstTimeUse.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            Button b = firstTimeUse.getButton(AlertDialog.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    contents = inputElement.getText().toString();
                    if (contents.matches("")){
                        showAlertbox("You Must Enter a Team");
                    }else{
                        adapter.insertTeamDetails(contents);
                        List<String> lables = adapter.getAllLabels();
                        dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, lables);
                        spinner.setAdapter(dataAdapter);
                        lables.add("Add New Team...");
                        firstTimeUse.dismiss();
                    }

                }

            });
        }
    });


    if (lables.isEmpty())
    {
        firstTimeUse.show();
    }
    else{
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);
        lables.add("Add New Team...");
    }

提前致谢

2 个答案:

答案 0 :(得分:3)

您在inputElement中创建了onCreate的新实例:

inputElement = new EditText(this);

因此,当您不将其添加到布局时,其中的文本始终为空。

使用findViewById从布局中实例化它,或将其添加到代码中的布局中。

答案 1 :(得分:1)

SetView(View view)接受view元素,我不确定你是如何在那里添加EditText的。您可以在布局文件中添加编辑文本,如下所示:

           

并在onCreate中声明如下:

inputElement = (EditText) findViewById(R.id.EditTextPassword);

你可以得到这样的字符串:

inputElement.getText().toString();