java - 获取错误'尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'ON andoid app
问题描述
这是我的布局
配置文件显示.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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"
tools:context=".Profiledisplay">
<RelativeLayout
android:layout_width="match_parent"
android:background="@color/colorPrimaryDark"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profilimg"
android:layout_width="160dp"
android:elevation="20dp"
android:layout_height="160dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
app:civ_border_width="2dp"
android:src="@drawable/progileicon"
app:civ_border_color="#FF000000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26dp"
android:textColor="@color/white"
android:text="mailid@mail.com"
android:id="@+id/mailid"
android:layout_centerHorizontal="true"
android:layout_marginTop="220dp"
android:textStyle="bold"></TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:id="@+id/name1"
android:textColor="@color/white"
android:layout_marginTop="260dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bloggerorweiter"
android:textSize="20dp"
android:textColor="@color/white"
android:layout_marginTop="280dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:text="Blogger or Writer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:id="@+id/City"
android:textColor="@color/white"
android:layout_marginTop="300dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:text="City"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:id="@+id/state"
android:textColor="@color/white"
android:layout_marginTop="320dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:text="State"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:id="@+id/Country"
android:textColor="@color/white"
android:layout_marginTop="340dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:text="Country"
/>
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation"
android:background="#97145C"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_items"
app:headerLayout="@layout/header">
</com.google.android.material.navigation.NavigationView>
配置文件显示.java
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.media.Image;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.util.concurrent.ExecutionException;
public class Profiledisplay extends AppCompatActivity {
NavigationView navigationView;
ImageView imgview;
FirebaseAuth mauth;
String currentuserID;
private DatabaseReference userref1;
TextView name,country,mailid,city,state,blog_writer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgview=findViewById(R.id.profilimg);
name=(TextView) findViewById(R.id.name1);
country=(TextView)findViewById(R.id.Country);
mailid=(TextView)findViewById(R.id.mailid);
city=(TextView)findViewById(R.id.City);
state=(TextView)findViewById(R.id.state);
mauth=FirebaseAuth.getInstance();
blog_writer=(TextView)findViewById(R.id.bloggerorweiter);
currentuserID=mauth.getCurrentUser().getUid();
userref1 = FirebaseDatabase.getInstance().getReference().child("Users");
try{
userref1.child(currentuserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.hasChild("username")){
String fullname1 = dataSnapshot.child("username").getValue().toString();
**name.setText("123456");**
}
if(dataSnapshot.hasChild("urlimage")){
String imageurl=dataSnapshot.child("urlimage").getValue().toString();
Glide.with(getApplicationContext()).load(imageurl).into(imgview);
}else{
Toast.makeText(Profiledisplay.this, "username or profile not exist",
Toast.LENGTH_SHORT).show();
}
String Email="gaakash149@gmail.com";
mailid.setText(Email);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});}
catch(Exception e){
}
setContentView(R.layout.activity_profiledisplay);
navigationView=findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
Toast.makeText(Profiledisplay.this, "CLicked Home", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Home.class));
break;
case R.id.Profile:
Toast.makeText(Profiledisplay.this, "CLicked profile",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Profiledisplay.class));
break;
case R.id.Post:
Toast.makeText(Profiledisplay.this, "CLicked Post", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),forgotpass.class));
break;
}
return false;
}
});
}
}
错误
E/AndroidRuntime:致命异常:主进程:com.example.myapplication,PID:25982 java.lang.NullPointerException:尝试在 null 上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)' com.example.myapplication.Profiledisplay$1.onDataChange(Profiledisplay.java:51) 处的对象引用 在 com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) 在 com.google.firebase.database.core.view.DataEvent.fire(com .google.firebase:firebase-database@@16.0.4:63) 在 com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55 ) 在 android.os.Handler.handleCallback(Handler.java:790) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:198) 在 android.app .ActivityThread.main(ActivityThread.java:7055) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523) 在 com.android .internal.os.ZygoteInit.main(ZygoteInit.java:836)
每次尝试执行 SetText() 方法时都会出现此错误。
build.gradel 文件
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion '24.0.2'
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-
optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-storage:16.0.4'
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
implementation 'com.google.android.material:material:1.0.0'
implementation 'de.hdodenhof:circleimageview:3.0.1'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.makeramen:roundedimageview:2.3.0'
}
apply plugin: 'com.google.gms.google-services'
解决方案
您需要在调用 findViewbyID 之前设置内容视图。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profiledisplay); // move setContentView here
imgview=findViewById(R.id.profilimg);
name=(TextView) findViewById(R.id.name1);
....
您的问题是当您尝试 finditbyid 时视图为空。
更新
换句话说:
setContentView 在尝试获取对视图的引用之前:
重点在这里
setContentView(R.layout.activity_profiledisplay);
确保有一个名为的
name1
TextViewactivity_profiledisplay.xml
推荐阅读
- sql - 我只想从 SQL 语句中获取最高数字而不限制其他列
- node.js - 是否可以通过 Angular 在浏览器中启动 Express.js 服务器?
- mysql - 获取每个 game_index 的前 3 个条目
- groovy - 是否可以随机化 Spock 测试的执行顺序?
- swift - Alamofire 返回 html 代码而不是 json
- android - 微调器不会显示选择的值
- css - 线高图像居中中间
- mongodb - 用于子集合的 mongo "$and" 运算符
- python - 使用 joblib 在 x86 上转储 scikit-learn 模型,然后在 z/OS 上读取决策树传递,但在 GradientBoostingRegressor 上失败
- javascript - 使用 JavaScript 删除字符串中注释标记后面的文本、空格 - 在字符串中创建新行