[英]Attempt to invoke virtual method 'void android.widget.TextView.setVisibility(int)' on a null object reference
我在由 textview 組成的通知上將 textview 計數設置為VISIBLE
,但我收到錯誤 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.8841843.set8008(8841843.set8008)一個 null object 參考
主要活動
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot childSnapshot: snapshot.getChildren()) {
ids.add(childSnapshot.getKey());
}
int i;
for ( i = 0 ; i < ids.size();i++)
{
ref = FirebaseDatabase.getInstance().getReference().child("Items").child(ids.get(i));
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot childSnapshot: snapshot.getChildren()) {
hashmap.put(childSnapshot.getKey(),childSnapshot.getValue().toString());
}
if(Integer.parseInt(hashmap.get("qty"))<=25)
{
badge.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
在創建選項菜單上
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.actionbar,menu);
View notificaitons = menu.findItem(R.id.notification).getActionView();
ImageButton iconButtonMessages = (ImageButton) notificaitons.findViewById(R.id.badge_icon_button);
badge = (TextView) notificaitons.findViewById(R.id.noti);
iconButtonMessages.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(MainActivity.this,Notification.class);
startActivity(intent);
}
});
return super.onCreateOptionsMenu(menu);
}
onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.notification:
Intent intentHome = new Intent(this, Notification.class);
startActivity(intentHome);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
reference.addValueEventListener(...)
你什么時候運行這段代碼?
我假設您在初始化badge
object 之前收到對 ValueEventListener 偵聽器的回調
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.