错误:获取运行时异常

时间:2017-06-22 15:05:24

标签: java android gallery

我一直在尝试构建一个Imageviewer应用。但每当我运行这个应用程序时,它说不幸的是应用程序停止了。我正在获得运行时异常

E / AndroidRuntime:FATAL EXCEPTION:main                                                    处理:com.example.dell_1.gall5,PID:16741                                                    java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.dell_1.gall5 / com.example.dell_1.gall5.MainActivity}:java.lang.NullPointerException:尝试获取null数组的长度                                                        在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)                                                        在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)                                                        在android.app.ActivityThread.-wrap12(ActivityThread.java)                                                        在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1460)                                                        在android.os.Handler.dispatchMessage(Handler.java:102)                                                        在android.os.Looper.loop(Looper.java:154)                                                        在android.app.ActivityThread.main(ActivityThread.java:6077)                                                        at java.lang.reflect.Method.invoke(Native Method)                                                        在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:865)                                                        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)                                                     引起:java.lang.NullPointerException:尝试获取null数组的长度                                                        在com.example.dell_1.gall5.GridViewAdapter.getCount(GridViewAdapter.java:32)                                                        在android.widget.GridView.setAdapter(GridView.java:206)                                                        在com.example.dell_1.gall5.MainActivity.onCreate(MainActivity.java:62)                                                        在android.app.Activity.performCreate(Activity.java:6705)                                                        在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)                                                        在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)                                                        在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)                                                        在android.app.ActivityThread.-wrap12(ActivityThread.java)                                                        在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1460)                                                        在android.os.Handler.dispatchMessage(Handler.java:102)                                                        在android.os.Looper.loop(Looper.java:154)                                                        在android.app.ActivityThread.main(ActivityThread.java:6077)                                                        at java.lang.reflect.Method.invoke(Native Method)                                                        在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:865)                                                        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

我不确定如何解决它

这是xml文件: 的 gridview_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <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="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dip"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dell_1.gall5.MainActivity"
    tools:showIn="@layout/activity_main">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" />

</RelativeLayout>

这是MainActivity: MainActivity.java

  package com.example.dell_1.gall5;

import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

    private String[] FilePathStrings;
    private String[] FileNameStrings;
    private File[] listFile;
    GridView grid;
    GridViewAdapter adapter;
    File file;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview_main);

        // Check for SD Card
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                    .show();
        } else {
            // Locate the image folder in your SD Card
            file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "SDImageTutorial");
            // Create a new folder if no folder named SDImageTutorial exist
            file.mkdirs();
        }

        if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
            }
        }

        // Locate the GridView in gridview_main.xml
        grid = (GridView) findViewById(R.id.gridview);
        // Pass String arrays to LazyAdapter Class
        adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
        // Set the LazyAdapter to the GridView
        grid.setAdapter(adapter);

        // Capture gridview item click
        grid.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent i = new Intent(MainActivity.this, ViewImage.class);
                // Pass String arrays FilePathStrings
                i.putExtra("filepath", FilePathStrings);
                // Pass String arrays FileNameStrings
                i.putExtra("filename", FileNameStrings);
                // Pass click position
                i.putExtra("position", position);
                startActivity(i);
            }

        });
    }

}

这是第二个xml文件: gridview_item.xml

`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dip" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image" />

</RelativeLayout>`

这是第二个java文件: ViewImage.java

`package com.example.dell_1.gall5;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewImage  extends Activity{
    TextView text;
    ImageView imageview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from view_image.xml
        setContentView(R.layout.view_image);

        // Retrieve data from MainActivity on GridView item click
        Intent i = getIntent();

        // Get the position
        int position = i.getExtras().getInt("position");

        // Get String arrays FilePathStrings
        String[] filepath = i.getStringArrayExtra("filepath");

        // Get String arrays FileNameStrings
        String[] filename = i.getStringArrayExtra("filename");

        // Locate the TextView in view_image.xml
        text = (TextView) findViewById(R.id.imagetext);

        // Load the text into the TextView followed by the position
        text.setText(filename[position]);

        // Locate the ImageView in view_image.xml
        imageview = (ImageView) findViewById(R.id.full_image_view);

        // Decode the filepath with BitmapFactory followed by the position
        Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

        // Set the decoded bitmap into ImageView
        imageview.setImageBitmap(bmp);

    }
}'

这是创建的第三个xml文件: view_image.xml     `     

    <ImageView
        android:id="@+id/full_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/imagetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20dip" />

</RelativeLayout>`

这是第三个创建的java文件: GridViewAdapter.java

`package com.example.dell_1.gall5;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridViewAdapter extends BaseAdapter  {

    private Activity activity;
    private String[] filepath;
    private String[] filename;

    private static LayoutInflater inflater = null;

    public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
        activity = a;
        filepath = fpath;
        filename = fname;
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return filepath.length;

    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.gridview_item, null);
        // Locate the TextView in gridview_item.xml
        TextView text = (TextView) vi.findViewById(R.id.text);
        // Locate the ImageView in gridview_item.xml
        ImageView image = (ImageView) vi.findViewById(R.id.image);

        // Set file name to the TextView followed by the position
        text.setText(filename[position]);

        // Decode the filepath with BitmapFactory followed by the position
        Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

        // Set the decoded bitmap into ImageView
        image.setImageBitmap(bmp);
        return vi;
    }
}

`

这是字符串文件: strings.xml

`<resources>
    <string name="app_name">Gall5</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Gall5</string>
</resources>`

这是Android Manifest:

`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dell_1.gall5"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="15" />


    <application
        android:icon="@drawable/ic_action_name"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:uiOptions="splitActionBarWhenNarrow" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="http" />
                <data android:host="*" />
                <data android:mimeType="vnd.android.cursor.dir/image"/>
            </intent-filter>
        </activity>
        <activity android:name=".ViewImage" >
        </activity>
    </application>

</manifest>`

1 个答案:

答案 0 :(得分:1)

MainActivity中,if (file.isDirectory())FilePathStringsFileNameStrings将成为实例。 但如果file不是目录,则为null s。 在GridViewAdapter#getCount方法中,您未检查filepath是否为null

  public int getCount() {
        return filepath==null ? 0 : filepath.length;
  }