结合使用Spinner和Button onClick Listener会给我一个Null Pointer异常

时间:2018-07-23 11:45:35

标签: java android android-studio nullpointerexception android-spinner

我有一个应用程序,允许一个人发布公告。该人员必须在微调框上选择其公告的类别,然后在EditText上键入其公告。在输入这两个字段之后,按钮将允许人员发表通知,但是如果微调框值或EditText值为空,则应生成错误。我尝试使键入公告的人员看不见按钮,因为我收到了Null Pointer Exception,但切换到该按钮后,仍然看不见该错误。这是我的代码:

public class MakeAnnouncements extends AppCompatActivity {

private EditText announcement;
private Button announce_button;
private ProgressDialog announcementDialog;
private DatabaseReference mRootRef;

private FirebaseAuth mAuth;
private String mCurrentUserId;
private String announcer;
private String []SPINNERCATEGORY ={"General","Cubs","Scouts","Seniors"};
private String category_text;

private MaterialBetterSpinner betterSpinner;

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

    announcementDialog = new ProgressDialog(this);
    mRootRef = FirebaseDatabase.getInstance().getReference();

    mAuth = FirebaseAuth.getInstance();
    mCurrentUserId =  mAuth.getCurrentUser().getUid();
    announcement = (EditText)findViewById(R.id.announce_text);
    announce_button = (Button)findViewById(R.id.announce_btn);

    announce_button.setVisibility(View.VISIBLE);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,SPINNERCATEGORY);
    betterSpinner = (MaterialBetterSpinner)findViewById(R.id.category_spinner);


    betterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

            String spinner_value= adapterView.getItemAtPosition(position).toString();
            if(position==0){
                // no item selected show Toast message
                announce_button.setVisibility(View.INVISIBLE);
            } else{
                announce_button.setVisibility(View.VISIBLE);
                // item selected
            }

                category_text = spinner_value;


            return;
        }

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

            announce_button.setVisibility(View.INVISIBLE);

        }
    });


    betterSpinner.setAdapter(arrayAdapter);


    mRootRef.child("Users").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            announcer = dataSnapshot.child("name").getValue().toString();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    announce_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {  //<----- This is where i am getting a null point exception 

            String announced_text = announcement.getText().toString().trim();
            String choosen_category = category_text.trim();



            if (TextUtils.isEmpty(announced_text)){

                announcement.setError("You did not type any announcement");

                return;


            }



            announcementDialog.setTitle("Posting Announcement...");
            announcementDialog.setMessage("Please wait...");
            announcementDialog.setCanceledOnTouchOutside(false);
            announcementDialog.show();
            PostAnnouncement(announced_text,choosen_category);
        }
    });
}

private void PostAnnouncement(String announced_text, String choosen_category) {



    DatabaseReference chat_push_key = mRootRef.child("Announcements").child(announcer).push();

    String push_key = chat_push_key.getKey();

    Map messageMap = new HashMap();
    messageMap.put("announcement",announced_text);
    messageMap.put("type","text");
    messageMap.put("category",choosen_category);
    messageMap.put("from",announcer);
    messageMap.put("time", ServerValue.TIMESTAMP);

    Map messageUserMap = new HashMap();
    messageUserMap.put( "Announcements" + "/" + push_key, messageMap);

    announcement.setText("");
    announcementDialog.hide();
    Toast.makeText(getApplicationContext(), "Your announcement was successfully posted",Toast.LENGTH_LONG).show();

    mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

            if(databaseError != null){

                Log.d("CHAT_LOG", databaseError.getMessage().toString());

            }

        }
    });



}
}

如果微调框的值不为空,我需要做什么以验证?

2 个答案:

答案 0 :(得分:0)

根据您的代码,您可以检查变量 category_text

if(TextUtils.isEmpty(category_text)){
    //Show your error message
}

答案 1 :(得分:0)

在检查了解决此问题的可能方法后,This Link帮助了我。 我首先将spinner_value更改为全局变量。然后写这段代码:

    String announced_text = announcement.getText().toString().trim();
    String choosen_category = null;

        if (TextUtils.isEmpty(announced_text)){

            announcement.setError("You did not type any announcement");

            return;


        }
         if(spinner_value != null){
            choosen_category = spinner_value.trim();

           return;
         }
          else if(spinner_value == null){

           betterspinner.setError("This section must be selected before proceeding");

           return;

          }

此后,我删除了初始代码中的按钮可见性。