【问题标题】:Getting error of : Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference出现错误:尝试在空对象引用上调用虚拟方法“android.text.Editable android.widget.EditText.getText()”
【发布时间】:2021-06-22 11:44:17
【问题描述】:

我已经看到所有关于此的堆栈溢出问题,但找不到解决方案。 在这一行出现错误。

String p_score = player_score_US.getText().toString();

我的代码

public class UpdateScore_activity extends AppCompatActivity {

    private RecyclerView recyclerView2;
    private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
    private us_adapter usAdapter;
    private TextView playerName;
    private Button SaveScorebtn;
    public ArrayList<us_model> list1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updatescore);
        recyclerView2=findViewById(R.id.recycleview2);
        SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
        EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
        playerName=(TextView) findViewById(R.id.Player_Name);

        list1=new ArrayList<>();
        usAdapter=new us_adapter(this,list1);
        recyclerView2.setAdapter(usAdapter);
        recyclerView2.setLayoutManager(new LinearLayoutManager(this));

        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot: snapshot.getChildren()){
                    String name1 = dataSnapshot.child("Name").getValue(String.class);
                    us_model myModel=new us_model(name1);
                    list1.add(myModel);
                }
                usAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
            }
        });
        SaveScorebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String p_score = player_score_US.getText().toString();
                HashMap<String, String> usermap = new HashMap<>();
                usermap.put("Score",p_score);
                for (int i=1;i<4;i++){
                    root.child(String.valueOf(i)).setValue(usermap);
                }
                openMain();
            }
        });
    }}

更新Score Activity(Recyclerview)的布局文件

<?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:background="#ffffff"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/Match_Name"
                android:gravity="center_horizontal"
                android:text="Update Score"
                android:textAlignment="center"
                android:textColor="#000002"
                android:textSize="32dp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="456dp"
                android:layout_marginTop="10dp">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/recycleview2"
                    android:layout_width="match_parent"
                    android:layout_height="441dp" />
            </LinearLayout>

            <Button
                android:id="@+id/us_saveScore"
                android:layout_width="127dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="62pt"
                android:layout_marginTop="5dp"
                android:layout_marginRight="57dp"
                android:background="#FF80AB"
                android:text="Save Score"
                android:textStyle="bold" />


        </LinearLayout>
    </ScrollView>
</LinearLayout>

玩家卡片布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="115dp"
    android:layout_marginTop="10dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="111dp"
        app:cardBackgroundColor="#A6D673">

        <TextView
            android:id="@+id/Player_Name"
            android:layout_width="256dp"
            android:layout_height="71dp"
            android:layout_marginLeft="18dp"
            android:layout_marginTop="12dp"
            android:gravity="center"
            android:text="Player Name"
            android:textColor="#000000"
            android:textSize="25dp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/us_Player_Score12"
            android:layout_width="79dp"
            android:layout_height="61dp"
            android:layout_marginLeft="300dp"
            android:layout_marginTop="19dp"
            android:gravity="center_horizontal"
            android:textAlignment="center"
            android:textColor="#000000"
            android:hint="Enter"
            android:textSize="22dp"
            android:textStyle="bold" />

    </androidx.cardview.widget.CardView>
</LinearLayout>

适配器类

public class us_adapter extends RecyclerView.Adapter<us_adapter.Myviewholder> {

    ArrayList<us_model> mlist1;
    Context context;

    public us_adapter(Context context, ArrayList<us_model> mlist1){
        this.context=context;
        this.mlist1=mlist1;
    }

    public us_adapter.Myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v=LayoutInflater.from(context).inflate(R.layout.updatescore_row,parent,false);
        return new Myviewholder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Myviewholder holder, int position) {
        us_model model1 =mlist1.get(position);
        holder.Name.setText(model1.getName());
    }

    public int getItemCount() {
        return mlist1.size();
    }

    public class Myviewholder extends RecyclerView.ViewHolder {

        TextView Name;
        Button update;

        public Myviewholder(@NonNull View itemView) {
            super(itemView);
            Name=itemView.findViewById(R.id.Player_Name);
        }
    }
}

模型类

public class us_model{
    private String Name;

    public us_model(String Name) {
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }
}

【问题讨论】:

    标签: java android-studio firebase-realtime-database


    【解决方案1】:

    您可以尝试两种解决方案来解决此问题。

    解决方案 1:

    来自

    EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
    

    final EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
    

    原因是,如果两个方法在 Java 中看到相同的局部变量,Java 希望您确保不会更改它,在这种情况下您必须将其设为 final

    解决方案 2:

    此外,您还可以将其设为global variable

    public class UpdateScore_activity extends AppCompatActivity {
    
    private RecyclerView recyclerView2;
    private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
    private us_adapter usAdapter;
    private TextView playerName;
    private Button SaveScorebtn;
    private EditText player_score_US;
    public ArrayList<us_model> list1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updatescore);
        recyclerView2=findViewById(R.id.recycleview2);
        SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
        player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
        playerName=(TextView) findViewById(R.id.Player_Name);
    
        list1=new ArrayList<>();
        usAdapter=new us_adapter(this,list1);
        recyclerView2.setAdapter(usAdapter);
        recyclerView2.setLayoutManager(new LinearLayoutManager(this));
    
        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot: snapshot.getChildren()){
                    String name1 = dataSnapshot.child("Name").getValue(String.class);
                    us_model myModel=new us_model(name1);
                    list1.add(myModel);
                }
                usAdapter.notifyDataSetChanged();
            }
    
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
            }
        });
        SaveScorebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String p_score = player_score_US.getText().toString();
                HashMap<String, String> usermap = new HashMap<>();
                usermap.put("Score",p_score);
                for (int i=1;i<4;i++){
                    root.child(String.valueOf(i)).setValue(usermap);
                }
                openMain();
            }
        });
    }}
    

    【讨论】:

    • 我尝试了您的两种解决方案,但仍然出现该错误。还有什么我应该尝试的吗?
    • @SahilNasariwala,您可以在此处添加布局文件进行检查吗?
    • 添加了我的 xml、适配器和模型类文件。
    • @SahilNasariwala,您点击按钮时是否收到错误消息?
    • 是的,当我按下保存分数按钮时出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多