繁体   English   中英

Android应用程序强制关闭并带有arrayindexoutofbounds异常

[英]Android app force closes with arrayindexoutofbounds exception

我的应用程序运行正常,突然在我的手机上运行时突然关闭。 试图撤消某些事情,但无济于事。 有人可以帮我找到问题吗?

我的第一个活动:

package com.ui.contactmanager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class DisplayContactsActivity extends Activity implements
        OnClickListener {

    String[][] data = new String[100][100];
    int i = 0;
    static int index = -1, count = 0;
    static View prev;

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

        // To set the status bar hidden.
        final Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        setContentView(R.layout.activity_display_contacts);

        // Creating text file
        try {
            File root = new File(Environment.getExternalStorageDirectory(),
                    "Notes");
            if (!root.exists()) {
                root.mkdirs();
            }
            File file = new File(root, "data.txt");
            PrintWriter create = new PrintWriter(new BufferedWriter(
                    new FileWriter(file, true)));
            create.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        init();

    }

    public void init() {

        // Creating a dynamic table
        TableLayout stk = (TableLayout) findViewById(R.id.table_main);
        TableRow tbrow0 = new TableRow(DisplayContactsActivity.this);
        TextView tv0 = new TextView(DisplayContactsActivity.this);
        tv0.setText(" Sl. No ");
        tv0.setTextColor(Color.WHITE);
        tv0.setHeight(100);
        tbrow0.addView(tv0);
        TextView tv1 = new TextView(DisplayContactsActivity.this);
        tv1.setText(" Name ");
        tv1.setTextColor(Color.WHITE);
        tv1.setHeight(100);
        tbrow0.addView(tv1);
        TextView tv2 = new TextView(DisplayContactsActivity.this);
        tv2.setText(" Phone Number ");
        tv2.setTextColor(Color.WHITE);
        tv2.setHeight(100);
        tbrow0.addView(tv2);
        stk.addView(tbrow0);

        initTable();

    }

    public void initTable() {
        // Reading and saving the text file
        try {
            File root = new File(Environment.getExternalStorageDirectory(),
                    "Notes");
            File file = new File(root, "data.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                // process the line.
                data[i] = line.split(";");
                i++;
            }
            br.close();
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        TableLayout stk = (TableLayout) findViewById(R.id.table_main);
        for (int j = 0; j < i; j++) {
            final TableRow tbrow = new TableRow(DisplayContactsActivity.this);
            TextView t1v = new TextView(DisplayContactsActivity.this);
            t1v.setText("" + (j + 1));
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            t1v.setHeight(50);
            tbrow.addView(t1v);
            TextView t2v = new TextView(DisplayContactsActivity.this);
            t2v.setText("" + data[j][0] + " " + data[j][1]);
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            t2v.setHeight(50);
            tbrow.addView(t2v);
            TextView t3v = new TextView(DisplayContactsActivity.this);
            t3v.setText("" + data[j][2]);
            t3v.setTextColor(Color.WHITE);
            t3v.setGravity(Gravity.CENTER);
            t3v.setHeight(50);
            tbrow.addView(t3v);
            tbrow.setId(j);
            tbrow.setOnClickListener(DisplayContactsActivity.this);
            stk.addView(tbrow);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_contacts, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id) {
        case R.id.addContact:
            Intent addContactIntent = new Intent(
                    "com.ui.contactmanager.CONTACTEDITORACTIVITY");
            startActivity(addContactIntent);
            break;
        case R.id.editContact:
            Bundle basket = new Bundle();
            basket.putInt("bread", index);
            Intent editContactIntent = new Intent(DisplayContactsActivity.this,
                    ContactEditorActivity.class);
            editContactIntent.putExtras(basket);
            startActivity(editContactIntent);
            break;
        case R.id.deleteContact:

            break;
        default:
            return false;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        int k = 0;
        try {
            File root = new File(Environment.getExternalStorageDirectory(),
                    "Notes");
            File file = new File(root, "data.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                // process the line.
                data[k] = line.split(";");
                k++;
            }
            br.close();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        if (k > i) {
            k--;
            TableLayout stk = (TableLayout) findViewById(R.id.table_main);
            final TableRow tbrow = new TableRow(DisplayContactsActivity.this);
            TextView t1v = new TextView(DisplayContactsActivity.this);
            t1v.setText("" + (k + 1));
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            t1v.setHeight(50);
            tbrow.addView(t1v);
            TextView t2v = new TextView(DisplayContactsActivity.this);
            t2v.setText("" + data[k][0] + " " + data[k][1]);
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            t2v.setHeight(50);
            tbrow.addView(t2v);
            TextView t3v = new TextView(DisplayContactsActivity.this);
            t3v.setText("" + data[k][2]);
            t3v.setTextColor(Color.WHITE);
            t3v.setGravity(Gravity.CENTER);
            t3v.setHeight(50);
            tbrow.addView(t3v);
            tbrow.setId(k);
            tbrow.setOnClickListener(DisplayContactsActivity.this);
            stk.addView(tbrow);
        }
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        count++;
        if (count > 1) {
            prev.setBackgroundColor(Color.rgb(61, 69, 91));
            v.setBackgroundColor(Color.GREEN);
            index = v.getId();
            prev = v;
        }
        v.setBackgroundColor(Color.GREEN);
        index = v.getId();
        prev = v;
    }
}

我的第二项活动:

package com.ui.contactmanager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class ContactEditorActivity extends Activity {

    static String[] currentData = new String[10];
    String[][] data = new String[100][100];
    int i = 0, index = -1;

    Button save, cancel;
    // TextView firstName, lastName, phone, address;
    EditText firstName, lastName, phone, address;

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

        // To set the status bar hidden.
        final Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        setContentView(R.layout.activity_contact_editor);

        Bundle getBasket = getIntent().getExtras();
        index = getBasket.getInt("bread");
        index--;

        firstName = (EditText) findViewById(R.id.etFirstName);
        lastName = (EditText) findViewById(R.id.etLastName);
        phone = (EditText) findViewById(R.id.etPhone);
        address = (EditText) findViewById(R.id.etAddress);
        save = (Button) findViewById(R.id.bSave);
        cancel = (Button) findViewById(R.id.bCancel);

        if (index > -1) {
            // Reading and saving the text file
            try {
                File root = new File(Environment.getExternalStorageDirectory(),
                        "Notes");
                File file = new File(root, "data.txt");
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    // process the line.
                    data[i] = line.split(";");
                    i++;
                }
                br.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            firstName.setText(data[index][0]);
            // if (data[index][1].equals(null))
            lastName.setText(data[index][1]);
            // if (!data[index][2].equals(null))
            phone.setText(data[index][2]);
            // if (!data[index][3].equals(null))
            address.setText(data[index][3]);

        }

        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (index == -1) {
                    // Reading input values
                    String line = null;
                    line = firstName.getText().toString() + ";"
                            + lastName.getText().toString() + ";"
                            + phone.getText().toString() + ";"
                            + address.getText().toString() + ";";

                    currentData = line.split(";");

                    try {
                        File root = new File(Environment
                                .getExternalStorageDirectory(), "Notes");
                        if (!root.exists()) {
                            root.mkdirs();
                        }
                        File file = new File(root, "data.txt");
                        PrintWriter out = new PrintWriter(new BufferedWriter(
                                new FileWriter(file, true)));
                        out.println(line);
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    finish();
                } else {
                    for (int j = 0; j < i; j++) {
                        if (j == index) {
                            // Reading input values
                            String line = null;
                            line = firstName.getText().toString() + ";"
                                    + lastName.getText().toString() + ";"
                                    + phone.getText().toString() + ";"
                                    + address.getText().toString() + ";";

                            try {
                                File root = new File(Environment
                                        .getExternalStorageDirectory(), "Notes");
                                if (!root.exists()) {
                                    root.mkdirs();
                                }
                                File file = new File(root, "data.txt");
                                PrintWriter out = new PrintWriter(
                                        new BufferedWriter(new FileWriter(file,
                                                true)));
                                out.println(line);
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        } else {
                            String line = data[j][0] + ";" + data[j][1] + ";"
                                    + data[j][2] + ";" + data[j][3] + ";";
                            try {
                                File root = new File(Environment
                                        .getExternalStorageDirectory(), "Notes");
                                if (!root.exists()) {
                                    root.mkdirs();
                                }
                                File file = new File(root, "data.txt");
                                PrintWriter out = new PrintWriter(
                                        new BufferedWriter(new FileWriter(file,
                                                true)));
                                out.println(line);
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.contact_editor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我的第一个xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:background="#3d455b"
    tools:context="com.ui.contactmanager.DisplayContactsActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" >

        <HorizontalScrollView
            android:id="@+id/hscrll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:id="@+id/RelativeLayout1"
                android:layout_width="wrap_content"
                android:layout_gravity="center"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TableLayout
                    android:id="@+id/table_main"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_centerHorizontal="true" >
                </TableLayout>
            </RelativeLayout>
        </HorizontalScrollView>
    </ScrollView>

</RelativeLayout>

我的第二个xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#3d455b"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

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

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.20" >

                <TextView
                    android:id="@+id/tvFirstName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tvfirstname"
                    android:textColor="#ffffff" />

                <EditText
                    android:id="@+id/etFirstName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:textColor="#ffffff" >

                    <requestFocus />
                </EditText>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.20" >

                <TextView
                    android:id="@+id/tvLastName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tvlastname"
                    android:textColor="#ffffff" />

                <EditText
                    android:id="@+id/etLastName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:textColor="#ffffff" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.20" >

                <TextView
                    android:id="@+id/tvPhone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tvphone"
                    android:textColor="#ffffff" />

                <EditText
                    android:id="@+id/etPhone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="phone"
                    android:textColor="#ffffff" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.20" >

                <TextView
                    android:id="@+id/tvAddress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tvaddress"
                    android:textColor="#ffffff" />

                <EditText
                    android:id="@+id/etAddress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="textPostalAddress"
                    android:textColor="#ffffff" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.05"
                android:weightSum="100" >

                <Button
                    android:id="@+id/bSave"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="50"
                    android:text="@string/bsave"
                    android:textColor="#ffffff" />

                <Button
                    android:id="@+id/bCancel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="50"
                    android:text="@string/bcancel"
                    android:textColor="#ffffff" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>

Logcat:

10-28 17:36:49.299: D/AndroidRuntime(14926): Shutting down VM
10-28 17:36:49.299: W/dalvikvm(14926): threadid=1: thread exiting with uncaught exception (group=0x41ba1c08)
10-28 17:36:49.304: E/AndroidRuntime(14926): FATAL EXCEPTION: main
10-28 17:36:49.304: E/AndroidRuntime(14926): Process: com.ui.contactmanager, PID: 14926
10-28 17:36:49.304: E/AndroidRuntime(14926): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ui.contactmanager/com.ui.contactmanager.DisplayContactsActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread.access$800(ActivityThread.java:138)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.os.Looper.loop(Looper.java:136)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread.main(ActivityThread.java:5034)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at java.lang.reflect.Method.invokeNative(Native Method)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at java.lang.reflect.Method.invoke(Method.java:515)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at dalvik.system.NativeStart.main(Native Method)
10-28 17:36:49.304: E/AndroidRuntime(14926): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
10-28 17:36:49.304: E/AndroidRuntime(14926):    at com.ui.contactmanager.DisplayContactsActivity.initTable(DisplayContactsActivity.java:121)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at com.ui.contactmanager.DisplayContactsActivity.init(DisplayContactsActivity.java:89)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at com.ui.contactmanager.DisplayContactsActivity.onCreate(DisplayContactsActivity.java:63)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.Activity.performCreate(Activity.java:5241)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 17:36:49.304: E/AndroidRuntime(14926):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
10-28 17:36:49.304: E/AndroidRuntime(14926):    ... 11 more

它说在第121行引起的arrayindexoutofbounds异常,但那里的索引值为0。

for (int j = 0; j < i; j++) {
            final TableRow tbrow = new TableRow(DisplayContactsActivity.this);
            TextView t1v = new TextView(DisplayContactsActivity.this);
            t1v.setText("" + (j + 1));
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            t1v.setHeight(50);
            tbrow.addView(t1v);
            TextView t2v = new TextView(DisplayContactsActivity.this);
            t2v.setText("" + data[j][0] + " " + data[j][1]);
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            t2v.setHeight(50);
            tbrow.addView(t2v);
            TextView t3v = new TextView(DisplayContactsActivity.this);
            t3v.setText("" + data[j][2]);
            t3v.setTextColor(Color.WHITE);
            t3v.setGravity(Gravity.CENTER);
            t3v.setHeight(50);
            tbrow.addView(t3v);
            tbrow.setId(j);
            tbrow.setOnClickListener(DisplayContactsActivity.this);
            stk.addView(tbrow);
        }

检查t3v.setText("" + data[j][2]);

如果data[j][2]具有任何值。

还要调试2维数组的长度

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM