isEmpty()总是返回true

时间:2014-06-07 12:23:18

标签: android android-edittext is-empty

我在android上制作了一个表单。在检查文本字段时,我使用isEmpty()方法检查是否有任何文本。问题是,它总是返回真实。我无法弄清楚我哪里出错了。提前致谢! :)

如果需要任何其他文件,请在此处发表评论,我会尽快添加。

AddQuestionActivity.java

import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_ANSWER;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_HINT;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_NUMBER;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import chipset.quizzy.questionadder.R;
import chipset.quizzy.questionadder.resources.Functions;
import chipset.quizzy.questionadder.resources.ShowImageActivity;

public class AddQuestionActivity extends Activity {

    Functions functions = new Functions();

    EditText addQuestionNumber, addQuestion, addQuestionAnswer,
            addQuestionHint;
    Button addQuestionImage, addQuestionAdd;
    ImageView addQuestionImageView;
    private static int RESULT_LOAD_IMAGE = 1;
    String picturePath, question, questionNumber, questionAnswer, questionHint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_question);

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
        addQuestion = (EditText) findViewById(R.id.addQuestion);
        addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
        addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);
        addQuestionImage = (Button) findViewById(R.id.addQuestionImage);
        addQuestionImageView = (ImageView) findViewById(R.id.addQuestionImageView);
        addQuestionAdd = (Button) findViewById(R.id.addQuestionAdd);

        questionNumber = addQuestionNumber.getText().toString().trim();
        question = addQuestion.getText().toString().trim();
        questionAnswer = addQuestionAnswer.getText().toString().trim();
        questionHint = addQuestionHint.getText().toString().trim();

        addQuestionAdd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                functions.hideKeyboard(getApplicationContext(),
                        getCurrentFocus());
                if (functions.isConnected(getApplicationContext())) {
                    if (questionNumber.isEmpty() || question.isEmpty()
                            || questionAnswer.isEmpty()
                            || questionHint.isEmpty()) {
                        Toast.makeText(getApplicationContext(),
                                "Enter All Fields", Toast.LENGTH_SHORT).show();
                        Log.i(KEY_QUESTION, String.valueOf(question.isEmpty()));
                        Log.i(KEY_QUESTION_ANSWER,
                                String.valueOf(questionAnswer.isEmpty()));
                        Log.i(KEY_QUESTION_HINT,
                                String.valueOf(questionHint.isEmpty()));
                        Log.i(KEY_QUESTION_NUMBER,
                                String.valueOf(questionNumber.isEmpty()));
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                AddQuestionActivity.this);
                        builder.setTitle("Information");
                        builder.setMessage(KEY_QUESTION_NUMBER + " : "
                                + questionNumber + "\n" + KEY_QUESTION + " : "
                                + question + "\n" + KEY_QUESTION_ANSWER + " : "
                                + questionAnswer + "\n" + KEY_QUESTION_HINT
                                + " : " + questionHint + "\n");
                        builder.setNeutralButton(android.R.string.ok, null);
                        builder.create();
                        builder.show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(),
                            "No Internet Connection", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        addQuestionImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent addImage = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(addImage, RESULT_LOAD_IMAGE);

            }
        });

        addQuestionImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent loadBigImage = new Intent(getApplication(),
                        ShowImageActivity.class);
                loadBigImage.putExtra("picturePath", picturePath);
                startActivity(loadBigImage);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            addQuestionImageView.setVisibility(View.VISIBLE);
            addQuestionImageView.setImageBitmap(BitmapFactory
                    .decodeFile(picturePath));

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_logout) {

            functions.logout(getApplication(), getApplicationContext());

        } else if (id == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

}


activity_add_question.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/turquoize" >

    <TextView
        android:id="@+id/addTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:fontFamily="sans-serif-light"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/app_name"
        android:textColor="@color/clouds"
        android:textSize="30sp" />

    <ScrollView
        android:id="@+id/boxy"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addTitle"
        android:layout_margin="15dp"
        android:background="@color/clouds"
        android:orientation="vertical"
        android:padding="15dp"
        tools:ignore="UselessLeaf" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/addQuestionNumber"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/qNo"
                android:inputType="number" />

            <EditText
                android:id="@+id/addQuestion"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/q"
                android:inputType="textMultiLine" />

            <EditText
                android:id="@+id/addQuestionAnswer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/qAns"
                android:inputType="text" />

            <EditText
                android:id="@+id/addQuestionHint"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/qHint"
                android:inputType="text" />

            <Button
                android:id="@+id/addQuestionImage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/button_click"
                android:text="@string/uQImage"
                android:textColor="@color/turquoize" />

            <ImageView
                android:id="@+id/addQuestionImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="15dp"
                android:background="@color/black"
                android:contentDescription="@string/qImage"
                android:visibility="gone" />
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/addQuestionAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_margin="15dp"
        android:background="@drawable/button_click"
        android:text="@string/addQuestionDo"
        android:textColor="@color/turquoize" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

您需要在Button onClick(...)事件

下移动此内容
    questionNumber = addQuestionNumber.getText().toString().trim();
    question = addQuestion.getText().toString().trim();
    questionAnswer = addQuestionAnswer.getText().toString().trim();
    questionHint = addQuestionHint.getText().toString().trim();

更新

就像这样

 addQuestionAdd.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

      questionNumber = addQuestionNumber.getText().toString().trim();
      question = addQuestion.getText().toString().trim();
      questionAnswer = addQuestionAnswer.getText().toString().trim();
      questionHint = addQuestionHint.getText().toString().trim();

      ...........
      .............
       }
   });

答案 1 :(得分:0)

这是因为,在onCreate阶段本身,您将获取文本框的值并将其存储在变量中。最初,文本框将为空,因此该值也将为空。

因此,修改onclick Listener代码,以便在代码中获取文本框值,然后对其进行处理。但是,还要在onclicklistener中检查空字符串,因为用户可能没有向文本框输入任何值。 :)

//可以在onCreate

中声明编辑文本实例
protected void onCreate(Bundle savedInstanceState) 
{

    ....

    addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
    addQuestion = (EditText) findViewById(R.id.addQuestion);
    addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
    addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);

    ....
}

//编辑文本值获取应位于onClick

public void onClick(View v) {

     questionNumber = addQuestionNumber.getText().toString().trim();
     question = addQuestion.getText().toString().trim();
     questionAnswer = addQuestionAnswer.getText().toString().trim();
     questionHint = addQuestionHint.getText().toString().trim();

     ...
}