Можете ли вы помочь мне понять, почему, когда я хочу установить текст в TextView, я получаю NullPointerException? Я знаю, потому что мой TextView нулевой, но как я могу снова получить TextView?
В чем моя логика:
nullPoint и получите данные от firebase, когда обработка завершится, вернитесь к MainActivity и обновите текст в TextView.Это мой пример кода:
Основная деятельность
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAddNewWord = findViewById(R.id.button);
btnAddNewWord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nullPoint np = new nullPoint();
np.takeCount();
}
});
}
public void setTextView(int count){
TextView tv = findViewById(R.id.textView);
tv.setText("count = " + count);
}
}
nullPoint
public class nullPoint {
//the class gets asynchronous data from the Firebase database and does not know when the process will end
public void takeCount(){
//det data
//.
//.
// finish
//send data to MainActivity and update textView text
MainActivity ma = new MainActivity();
ma.setTextView(5);
}
}
XML
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
tools:context = ".MainActivity"
android:layout_gravity = "center">
<TextView
android:id = "@+id/textView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Hello World!"
android:layout_gravity = "center"/>
<Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Button"
android:layout_gravity = "center"/>
</LinearLayout>




Я предполагаю, что класса nullPoint нет внутри MainActivity. В результате внутри вашего класса nullPoint нет ссылки на TextView, в котором вы пытаетесь установить данные.
В вашем случае я хотел бы предложить вам реализовать слушателя, подобного следующему.
public interface FirebaseResponseListener {
void onFirebaseResponseReceived(int count);
}
Теперь с вашего MainActivity вам нужно реализовать слушатель следующим образом.
public class MainActivity extends AppCompatActivity implements FirebaseResponseListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAddNewWord = findViewById(R.id.button);
btnAddNewWord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nullPoint np = new nullPoint();
np.listener = this; // Initialize the listener here
np.takeCount();
}
});
}
public void setTextView(int count){
TextView tv = findViewById(R.id.textView);
tv.setText("count = " + count);
}
@Override
void onFirebaseResponseReceived(int count) {
setTextView(count);
}
}
И вы также должны добавить слушателя в свой класс nullPoint.
public class nullPoint {
public FirebaseResponseListener listener;
//the class gets asynchronous data from the Firebase database and does not know when the process will end
public void takeCount(){
//det data
//.
//.
// finish
//send data to MainActivity and update textView text
listener.onFirebaseResponseReceived(5);
}
}
Надеюсь, что это решит вашу проблему.
Спасибо, Реаз Муршед, да, ты решил мою проблему :)
Определен ли класс
nullPointвнутри вашегоMainActivity?