无法使用Android将Array元素设置为TextView?

时间:2018-08-24 04:58:53

标签: java android arrays textview

我在数组中有七个 TextViews 和七个元素。现在,我想在七个不同的TextViews中设置这些数组元素。但是,当此活动打开时,我的应用程序停止了。

这是我的Activity.xml

    String msgs="<InfoStart>\r\n"
            + "id:1234\r\n"
            + "phone:912119882\r\n"
            + "info_type:1\r\n"
            + "<InfoEnd>\r\n" // you lack an open double quote;
            +"<InfoStart>\r\n"
            + "id:5678\r\n"
            + "phone:912119881\r\n"
            + "info_type:1\r\n"
            + "<InfoEnd>\r\n"; // you lack an open double quote;

这是Activity.java

<RelativeLayout 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:gravity="center"
tools:context=".ProfileActivity">


<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <include
        android:id="@+id/main_page_toolbar"
        layout="@layout/main_app_bar_layout" />

</android.support.design.widget.AppBarLayout>

<TextView
    android:id="@+id/profile_name_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="67dp"
    android:text="Name"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="26sp" />

<TextView
    android:id="@+id/profile_email_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="110dp"
    android:text="Email"
    android:textSize="18sp" />

<TextView
    android:id="@+id/profile_id_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp"
    android:text="ID"
    android:textColor="@color/spots_dialog_color"
    android:textSize="24sp" />


<LinearLayout
    android:id="@+id/linearLayoutCode"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="50dp"
    android:layout_marginTop="223dp"
    android:paddingLeft="30dp"
    android:paddingRight="30dp">

    <TextView
        android:id="@+id/profile_invite_code1"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="1"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code2"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="2"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code3"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="3"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code4"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="4"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code5"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="e"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code6"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="r"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/profile_invite_code7"
        android:layout_width="5dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="s"
        android:textSize="20sp" />
</LinearLayout>
</RelativeLayout> 

我的logact出现这些错误:

public class ProfileActivity extends AppCompatActivity {

// toolbar instance
private Toolbar mToolbar;
RelativeLayout rootLayout;

//Array for invite code digits
public char inviteArray[] = new char[7];

// Text view Instances
private TextView mUserConnectionId;
private TextView mProfileUsernameView;
private TextView mProfileEmailView;
public TextView mInviteCodetext1;
public TextView mInviteCodetext2;
public TextView mInviteCodetext3;
public TextView mInviteCodetext4;
public TextView mInviteCodetext5;
public TextView mInviteCodetext6;
public TextView mInviteCodetext7;

TextView []  inviteTextView = { mInviteCodetext1 ,
                                mInviteCodetext2 ,
                                mInviteCodetext3 ,
                                mInviteCodetext4 ,
                                mInviteCodetext5 ,
                                mInviteCodetext6 ,
                                mInviteCodetext7 };

//Firebase
private DatabaseReference mUserDataBaseRef;
private FirebaseAuth mAuth;


@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //set contentView
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
            .setDefaultFontPath("fonts/Arkhip_font.ttf")
            .setFontAttrId(R.attr.fontPath)
            .build()
    );

    setContentView(R.layout.activity_profile);

    //Custom Toolbar
    mToolbar = findViewById(R.id.main_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar()
            .setTitle("Profile");
    //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mUserConnectionId = (TextView) findViewById(R.id.profile_id_text);
    mProfileUsernameView = (TextView) findViewById(R.id.profile_name_view);
    mProfileEmailView = (TextView) findViewById(R.id.profile_email_view);

    //Invite code Text view
    mInviteCodetext1 = (TextView) findViewById(R.id.profile_invite_code1);
    mInviteCodetext2 = (TextView) findViewById(R.id.profile_invite_code2);
    mInviteCodetext3 = (TextView) findViewById(R.id.profile_invite_code3);
    mInviteCodetext4 = (TextView) findViewById(R.id.profile_invite_code4);
    mInviteCodetext5 = (TextView) findViewById(R.id.profile_invite_code5);
    mInviteCodetext6 = (TextView) findViewById(R.id.profile_invite_code6);
    mInviteCodetext7 = (TextView) findViewById(R.id.profile_invite_code7);

    mInviteCodetext1.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext2.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext3.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext4.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext5.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext6.setBackground(getResources().getDrawable(R.drawable.edittext_background));
    mInviteCodetext7.setBackground(getResources().getDrawable(R.drawable.edittext_background));

}   

@Override
protected void onStart() {
    super.onStart();

     mAuth = FirebaseAuth.getInstance();
    if(mAuth.getCurrentUser() != null){
        mUserDataBaseRef = FirebaseDatabase.getInstance().getReference()
                .child("Users").child(mAuth.getCurrentUser().getUid());

    }
    mUserDataBaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String username = dataSnapshot.child("name").getValue().toString();
            String email = dataSnapshot.child("email").getValue().toString();
            String inviteCode = dataSnapshot.child("uniqueID").getValue().toString();

            mUserConnectionId.setText(inviteCode);
            mProfileUsernameView.setText(username);
            mProfileEmailView.setText(email);

            for (int i = 0; i < inviteCode.length(); ++i) {
                inviteArray[i] = inviteCode.charAt(i); // This array giving me correct result
            }

            for (int i=0 ; i<inviteArray.length; ++i){
                inviteTextView[i].setText(inviteArray[i]);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

请告诉我我在这里做错了什么。并且,还有其他更好的方法吗?

5 个答案:

答案 0 :(得分:0)

尝试一下

public char inviteArray[] = new char[6]; // Array for invite code digits

我认为,这可能是由于数组索引值错误。 两个数组length()不同。

答案 1 :(得分:0)

at com.example.infonet.emonitor.ControlApplication.onCreate(ControlApplication.java:20)

在这里用i ++替换++ i并检查数组长度是否相同

答案 2 :(得分:0)

我已经测试了您的代码,看来您所面临的问题是由于类结构错误所致。将您的addListner放在onStart()方法内

 @Override
protected void onStart() {
    super.onStart();
    mUserDataBaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        String inviteCode = dataSnapshot.child("WYZ").getValue().toString();

        mUserConnectionId.setText(inviteCode);


        for (int i = 0; i < inviteCode.length(); i++) {
            inviteArray[i] = inviteCode.charAt(i); // This array giving me correct result
        }

        for(int i = 0; i < inviteArray.lenght() && i < invitetextview.lenght(); i++){ // this adding one more condition eliminate your nullPointerException
          invitetextView[i].setText(inviteArray[i]);
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
}

您正在通过任何方法使用它,这就是您的应用崩溃的原因

希望对您有帮助

答案 3 :(得分:0)

您的日志表明textviews为空。

这可能是因为在文本视图初始化之前调用了方法 mUserDataBaseRef.addValueEventListener()

解决方案:

1:在放置数据之前检查textview是否为null。然后等待一段时间,希望它会发生。然后去做(也许处理程序会有所帮助。)

2:将 mUserDataBaseRef.addValueEventListener()放在onStart中。

p.s。我更喜欢第二种选择。

答案 4 :(得分:0)

您确定此行是

String inviteCode = dataSnapshot.child("uniqueID").getValue().toString();

将返回正好包含7个字符的字符串?
如果不是,并且inviteCode的长度小于7,则此循环

for (int i = 0; i < inviteCode.length(); ++i) {
    inviteArray[i] = inviteCode.charAt(i);
}

将保留inviteArray的1个或多个元素未初始化,因此它们为null,然后在此循环中:

for (int i=0 ; i<inviteArray.length; ++i){
    inviteTextView[i].setText(inviteArray[i]);
}

您将获得一个NPE,应用程序将崩溃。

由于inviteArray[i]的类型为char,该应用仍然会崩溃,因此请使用以下内容替换最后一个循环:

for (int i=0 ; i<inviteArray.length; ++i){
    inviteTextView[i].setText("" + inviteArray[i]);
}

编辑:

for (int i=0 ; i<inviteArray.length; ++i){
    try {
        inviteTextView[i].setText("" + inviteArray[i]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}