当从一个Activity向另一个Activity传递长度值时,出现数组初始化错误[重复]。

问题描述 投票:0回答:1

我是一个新的Android开发.我通过一个值(int 类型)从一个 Activity 使用 Intent.

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("length", length);  //value is taken from a edit text
startActivity(intent);

然后在 NewActivity我把这段代码添加在 onCreate() 方法,然后我试图在数组上初始化一个数组。

arrayLength = getIntent().getIntExtra("length", 0);  //int type arrayLength variabel is diclared globally.

然后我尝试在 NewActivity (out of function)为。

char[] array = new char[arrayLength];

然后我在一个循环中添加数组元素,并尝试在一个循环中显示 TextView 使用 Button.但当我点击我的应用程序时,它就会崩溃。Button 用这行代码来显示数组元素。

arrayElemtsShow.setText(new String (array));

但是如果我用下面这样的常量初始化这个数组,就能正常工作。

char[] array = new char[20];

但重要的是,初始化这个数组时要使用之前的值 Activity.我该怎么做才能解决这个问题呢,为什么会出现这种情况呢?

Logcat:

> 2020-06-03 08:43:41.449 30912-30912/? I/.aam.secretnam: Late-enabling
> -Xcheck:jni 2020-06-03 08:43:41.721 30912-30912/com.aam.secretname I/Perf: Connecting to perf service. 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets;
> (light greylist, linking) 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> field Landroid/graphics/Insets;->left:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->right:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->top:I (light greylist, linking) 2020-06-03
> 08:43:41.836 30912-30912/com.aam.secretname W/.aam.secretnam:
> Accessing hidden field Landroid/graphics/Insets;->bottom:I (light
> greylist, linking) 2020-06-03 08:43:41.970
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z
> (light greylist, reflection) 2020-06-03 08:43:41.973
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V
> (light greylist, reflection) 2020-06-03 08:43:41.986
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic;
> (light greylist, linking) 2020-06-03 08:43:42.217
> 30912-30938/com.aam.secretname I/Adreno: QUALCOMM build               
> : 4e21c4c, I21281c58c8
>     Build Date                       : 03/01/19
>     OpenGL ES Shader Compiler Version: EV031.25.03.02
>     Local Branch                     : 
>     Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.5.R1.09.00.00.464.039
>     Remote Branch                    : NONE
>     Reconstruct Branch               : NOTHING 2020-06-03 08:43:42.217 30912-30938/com.aam.secretname I/Adreno: Build Config                 
> : S L 6.0.7 AArch32 2020-06-03 08:43:42.222
> 30912-30938/com.aam.secretname I/Adreno: PFP: 0x005ff110, ME:
> 0x005ff066 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/OpenGLRenderer: Initialized EGL, version 1.4 2020-06-03 08:43:42.227
> 30912-30938/com.aam.secretname D/OpenGLRenderer: Swap behavior 2
> 2020-06-03 08:43:42.370 30912-30912/com.aam.secretname
> I/AssistStructure: Flattened final assist data: 2924 bytes, containing
> 1 windows, 10 views 2020-06-03 08:43:46.687
> 30912-30912/com.aam.secretname I/Timeline: Timeline:
> Activity_launch_request time:527917018 2020-06-03 08:43:46.728
> 30912-30912/com.aam.secretname W/ActivityThread:
> handleWindowVisibility: no activity for token
> android.os.BinderProxy@22a035f 2020-06-03 08:43:51.641
> 30912-30912/com.aam.secretname D/AndroidRuntime: Shutting down VM
> 2020-06-03 08:43:51.645 30912-30912/com.aam.secretname
> E/AndroidRuntime: FATAL EXCEPTION: main
>     Process: com.aam.secretname, PID: 30912
>     java.lang.IllegalStateException: Could not execute method for android:onClick
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
>      Caused by: java.lang.reflect.InvocationTargetException
>         at java.lang.reflect.Method.invoke(Native Method)
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
>         at android.view.View.performClick(View.java:6608) 
>         at android.view.View.performClickInternal(View.java:6585) 
>         at android.view.View.access$3100(View.java:785) 
>         at android.view.View$PerformClick.run(View.java:25919) 
>         at android.os.Handler.handleCallback(Handler.java:873) 
>         at android.os.Handler.dispatchMessage(Handler.java:99) 
>         at android.os.Looper.loop(Looper.java:201) 
>         at android.app.ActivityThread.main(ActivityThread.java:6826) 
>         at java.lang.reflect.Method.invoke(Native Method) 
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
>      Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
>         at com.aam.secretname.FirstInput.getLineNumbers(FirstInput.java:71)
>         at com.aam.secretname.FirstInput.line3(FirstInput.java:57)
>         at java.lang.reflect.Method.invoke(Native Method) 
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
>         at android.view.View.performClick(View.java:6608) 
>         at android.view.View.performClickInternal(View.java:6585) 
>         at android.view.View.access$3100(View.java:785) 
>         at android.view.View$PerformClick.run(View.java:25919) 
>         at android.os.Handler.handleCallback(Handler.java:873) 
>         at android.os.Handler.dispatchMessage(Handler.java:99) 
>         at android.os.Looper.loop(Looper.java:201) 
>         at android.app.ActivityThread.main(ActivityThread.java:6826) 
>         at java.lang.reflect.Method.invoke(Native Method) 
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

第一类xml

    <TextView
        android:id="@+id/textView5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="serif-monospace"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/length"
        android:textColor="#66B1F3"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.243" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:autofillHints=""
        android:ems="10"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/Enterlength"
        android:inputType="textPersonName"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView5"
        app:layout_constraintVertical_bias="0.122" />

    <Button
        android:id="@+id/button2"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="44dp"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:background="@drawable/radius_button"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.491"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnexample"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:visibility="invisible"
        android:textAllCaps="false"
        android:textSize="18sp"
        android:onClick="exampleOnClick"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.781"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

第二类Xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="@drawable/gradient_background">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/instruction"
        android:textColor="#2E183E"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line1"
        android:text="@string/alphabet_1"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView7" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line6"
        android:text="@string/alphabet_6"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line5"
        android:text="@string/alphabet_5"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button6" />

    <Button
        android:id="@+id/button6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line4"
        android:text="@string/alphabet_4"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button7" />

    <Button
        android:id="@+id/button7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line3"
        android:text="@string/alphabet_3"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button8" />

    <Button
        android:id="@+id/button8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line2"
        android:text="@string/alphabet_2"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button9"
        android:layout_width="150sp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/line_numbers"
        android:padding="2dp"
        android:textColor="#fff"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />

    <Button
        android:id="@+id/button10"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginBottom="4dp"
        android:background="@drawable/back_button"
        android:onClick="reset"
        android:text="@string/reset"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button20"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:textAllCaps="false"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/button9"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

一流的

package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LengthActivity extends AppCompatActivity {
    //variables
    int length = 0;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_length);
    }

    public void nextOnClick(View view) {
        getLength();
        if ((length > 0) && (length < 20)) {
            intent = new Intent(LengthActivity.this, FirstInput.class);
            intent.putExtra("length", length);   //sending value in second activity
            startActivity(intent);
        }
    }

    public void exampleOnClick(View view) {
        TextView showInfo = (TextView) findViewById(R.id.textView5);
        Button example = (Button) findViewById(R.id.btnexample);
        showInfo.setText(R.string.example);
        example.setVisibility(View.INVISIBLE);
    }

    private void getLength() {
        try {
            EditText wordLength = (EditText) findViewById(R.id.editText);
            int tempLength = Integer.parseInt(wordLength.getText().toString());

            if ((tempLength<20) && (tempLength>0)) {
                length = tempLength;
            }
            else {
                TextView showInfo = (TextView) findViewById(R.id.textView5);
                showInfo.setTextColor(Color.RED);

                if (tempLength == 0) showInfo.setText(R.string.warningOfLenthZero);
                else showInfo.setText(R.string.warningOfLengthLimitation);
            }
        }
        catch (Exception e){
            TextView showInfo = (TextView) findViewById(R.id.textView5);
            Button example = (Button) findViewById(R.id.btnexample);
            showInfo.setTextColor(Color.RED);

            showInfo.setText(R.string.instuctForGivingLength);
            example.setVisibility(View.VISIBLE);
        }
    }
}

二等兵

package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;

public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers = new char[wordLength]; //problem
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
    }

    public void nextOnClick(View view) {
        intent = new Intent(FirstInput.this, FinalInput.class);
        if (lineNumbers[wordLength - 1] != '\0'){
            intent.putExtra("lineNumbers", new String(lineNumbers));
            intent.putExtra("length", wordLength); 
            startActivity(intent);
        }
        else {
            TextView warning = (TextView) findViewById(R.id.textView6);
            warning.setTextColor(Color.RED);
            warning.setText(R.string.instuctionForTappingOnLine);
        }
    }

    public void reset(View view) {
        count = 0;
        Arrays.fill(lineNumbers, '\0');
        Toast.makeText(this, "Reseted", Toast.LENGTH_SHORT ).show();
        TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
        showLineNumbers.setText("");
    }

    public void line1(View v){
        getLineNumbers('1');
    }
    public void line2(View v){
        getLineNumbers('2');
    }
    public void line3(View v){
        getLineNumbers('3');
    }
    public void line4(View v){
        getLineNumbers('4');
    }
    public void line5(View v){
        getLineNumbers('5');
    }
    public void line6(View v){
        getLineNumbers('6');
    }

    private void getLineNumbers(char line) {
        if(count < wordLength){
            lineNumbers[count++] = line;
            TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
            showLineNumbers.setText(new String(lineNumbers));
        }
        else{
            TextView showInfo = (TextView) findViewById(R.id.textView6);
            showInfo.setText(R.string.completedInput);
        }
    }
}
java android android-intent android-activity start-activity
1个回答
-1
投票

你应该提供异常logcat;但我猜你你错过了转换字符串到int,当你从EditText取值

intent.putExtra("length", Integer.parseInt(length));

更新。

你的问题是你正在初始化... lineNumbers 数组的成员,值为0;这是因为默认的 int 在java中的值是0。

所以,当你使用下面的声明语句时,你是在给一个长度为0的值分配给 lineNumbers 阵列,因为 wordLength 是s直到0;所以你需要做的是在你做完这个作业后,你的 getIntent().getIntExtra() 值。

要在代码中做到这一点(请注意标有 // <<<<<<<<<<<< Change here)

public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers; // <<<<<<<<<<<<<<<< Change here
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
         lineNumbers = new char[wordLength] // <<<<<<<<<<<<<<< Change here
    }

.... 
© www.soinside.com 2019 - 2024. All rights reserved.