【问题标题】:Combining Spinner and Button onClick Listener is giving me a Null Pointer exception结合 Spinner 和 Button onClick 监听器给了我一个空指针异常
【发布时间】:2018-07-23 11:45:34
【问题描述】:

我有一个应用程序,允许一个人发布公告。该人必须在微调器上选择其公告的类别并在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());

            }

        }
    });



}
}

如果微调器值不为空,我需要做什么来验证?

【问题讨论】:

  • 使用微调器,您始终默认选择第一个值
  • 但是第一个值为 null,如果没有输入,我得到 NullPointerException
  • @BrijeshJoshi 你能看看我的解决方案吗

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在检查了解决此问题的可能方法后,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;
    
              }
    

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

    【讨论】:

    • 但是在选择一个微调器值之后,当没有选择任何内容和选择某个值时,我都会收到错误
    猜你喜欢
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多