Java 在android中从filedialog获取图片并在imageview中显示

Java 在android中从filedialog获取图片并在imageview中显示,java,android,Java,Android,我想从文件选择器中拍摄一张照片,并将其显示在图像视图中。。但当我运行我的应用程序时,它会停止运行。问题在哪里? 这些代码是“MainActivity.java”的代码。我没有在我的项目的其他文件中更改任何内容。我的代码基于。我的代码是: public class MainActivity extends Activity { private static final int FILE_SELECT_CODE = 0; private static final String TA

我想从文件选择器中拍摄一张照片,并将其显示在图像视图中。。但当我运行我的应用程序时,它会停止运行。问题在哪里? 这些代码是“MainActivity.java”的代码。我没有在我的项目的其他文件中更改任何内容。我的代码基于。我的代码是:

public class MainActivity extends Activity {

    private static final int FILE_SELECT_CODE = 0;
    private static final String TAG = null;
    public TextView tv=(TextView) findViewById(R.id.textView1);
    ImageView iv=(ImageView) findViewById(R.id.imageView1);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b=(Button) findViewById(R.id.button1);


        b.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showFileChooser();

            }
        });
    }


    private void showFileChooser() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("*/*"); 
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(
                    Intent.createChooser(intent, "Select a File to Upload"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install a File Manager.", 
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {
                // Get the Uri of the selected file 
                Uri uri = data.getData();
                iv.setImageURI(uri);
                Log.d(TAG, "File Uri: " + uri.toString());
               }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

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

}
日志为:

12-12 04:21:32.343: D/AndroidRuntime(1068): Shutting down VM
12-12 04:21:32.343: W/dalvikvm(1068): threadid=1: thread exiting with uncaught exception (group=0xb4a60b90)
12-12 04:21:32.433: E/AndroidRuntime(1068): FATAL EXCEPTION: main
12-12 04:21:32.433: E/AndroidRuntime(1068): Process: com.example.a55j, PID: 1068
12-12 04:21:32.433: E/AndroidRuntime(1068): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.a55j/com.example.a55j.MainActivity}: java.lang.NullPointerException
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2102)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.os.Looper.loop(Looper.java:137)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread.main(ActivityThread.java:4998)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at java.lang.reflect.Method.invoke(Method.java:515)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at dalvik.system.NativeStart.main(Native Method)
12-12 04:21:32.433: E/AndroidRuntime(1068): Caused by: java.lang.NullPointerException
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.Activity.findViewById(Activity.java:1883)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at com.example.a55j.MainActivity.<init>(MainActivity.java:23)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at java.lang.Class.newInstanceImpl(Native Method)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at java.lang.Class.newInstance(Class.java:1208)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
12-12 04:21:32.433: E/AndroidRuntime(1068):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
12-12 04:21:32.433: E/AndroidRuntime(1068):     ... 11 more
12-12 04:21:34.823: I/Process(1068): Sending signal. PID: 1068 SIG: 9
12-1204:21:32.343:D/AndroidRuntime(1068):关闭虚拟机
12-12 04:21:32.343:W/dalvikvm(1068):threadid=1:线程以未捕获异常退出(组=0xb4a60b90)
12-1204:21:32.433:E/AndroidRuntime(1068):致命异常:主
12-1204:21:32.433:E/AndroidRuntime(1068):进程:com.example.a55j,PID:1068
12-12 04:21:32.433:E/AndroidRuntime(1068):java.lang.RuntimeException:无法实例化活动组件信息{com.example.a55j/com.example.a55j.MainActivity}:java.lang.NullPointerException
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2102)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.ActivityThread.access$700(ActivityThread.java:135)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.os.Handler.dispatchMessage(Handler.java:102)上
12-1204:21:32.433:E/AndroidRuntime(1068):在android.os.Looper.loop(Looper.java:137)
12-12 04:21:32.433:E/AndroidRuntime(1068):位于android.app.ActivityThread.main(ActivityThread.java:4998)
12-12 04:21:32.433:E/AndroidRuntime(1068):位于java.lang.reflect.Method.Invokenactive(本机方法)
12-12 04:21:32.433:E/AndroidRuntime(1068):在java.lang.reflect.Method.invoke(Method.java:515)
12-12 04:21:32.433:E/AndroidRuntime(1068):在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-1204:21:32.433:E/AndroidRuntime(1068):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-12 04:21:32.433:E/AndroidRuntime(1068):在dalvik.system.NativeStart.main(本机方法)
12-12 04:21:32.433:E/AndroidRuntime(1068):由以下原因引起:java.lang.NullPointerException
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.Activity.findViewById(Activity.java:1883)上
12-12 04:21:32.433:E/AndroidRuntime(1068):位于com.example.a55j.MainActivity。(MainActivity.java:23)
12-12 04:21:32.433:E/AndroidRuntime(1068):位于java.lang.Class.newInstanceImpl(本机方法)
12-12 04:21:32.433:E/AndroidRuntime(1068):位于java.lang.Class.newInstance(Class.java:1208)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.Instrumentation.newActivity(Instrumentation.java:1061)
12-12 04:21:32.433:E/AndroidRuntime(1068):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
12-1204:21:32.433:E/AndroidRuntime(1068):。。。还有11个
12-12 04:21:34.823:I/进程(1068):发送信号。PID:1068信号:9
活动的主要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="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="35dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="@string/open" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginTop="81dp"
        android:layout_toLeftOf="@+id/button1"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

试试这个-

 public class MainActivity extends Activity {

        private static final int FILE_SELECT_CODE = 0;
        private static final String TAG = null;
        public TextView tv;
        public ImageView iv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv=(TextView) findViewById(R.id.textView1);
            iv=(ImageView) findViewById(R.id.imageView1);
            Button b=(Button) findViewById(R.id.button1);


            b.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    showFileChooser();

                }
            });
        }


        private void showFileChooser() {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
            intent.setType("*/*"); 
            intent.addCategory(Intent.CATEGORY_OPENABLE);

            try {
                startActivityForResult(
                        Intent.createChooser(intent, "Select a File to Upload"),
                        FILE_SELECT_CODE);
            } catch (android.content.ActivityNotFoundException ex) {
                // Potentially direct the user to the Market with a Dialog
                Toast.makeText(this, "Please install a File Manager.", 
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file 
                    Uri uri = data.getData();
                    iv.setImageURI(uri);
                    Log.d(TAG, "File Uri: " + uri.toString());
                   }
                break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

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

    }
试试这个-

 public class MainActivity extends Activity {

        private static final int FILE_SELECT_CODE = 0;
        private static final String TAG = null;
        public TextView tv;
        public ImageView iv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv=(TextView) findViewById(R.id.textView1);
            iv=(ImageView) findViewById(R.id.imageView1);
            Button b=(Button) findViewById(R.id.button1);


            b.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    showFileChooser();

                }
            });
        }


        private void showFileChooser() {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
            intent.setType("*/*"); 
            intent.addCategory(Intent.CATEGORY_OPENABLE);

            try {
                startActivityForResult(
                        Intent.createChooser(intent, "Select a File to Upload"),
                        FILE_SELECT_CODE);
            } catch (android.content.ActivityNotFoundException ex) {
                // Potentially direct the user to the Market with a Dialog
                Toast.makeText(this, "Please install a File Manager.", 
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file 
                    Uri uri = data.getData();
                    iv.setImageURI(uri);
                    Log.d(TAG, "File Uri: " + uri.toString());
                   }
                break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

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

    }

在android.app.Activity.findViewById(Activity.java:1883)上查看此
,这意味着您的XML文件
R.layout.Activity\u main
没有名为
button1
的按钮,请检查

public TextView tv=(TextView) findViewById(R.id.textView1);
ImageView iv=(ImageView) findViewById(R.id.imageView1);

设置内容视图后,将其放入OnCreate中,您甚至在布局实际膨胀之前就试图访问它们,这就是为什么会出现此错误。

请参见android.app.Activity.findViewById(Activity.java:1883)
,这意味着您的XML文件
R.layout.activity\u main
没有名为
button1
的按钮,请检查该按钮

public TextView tv=(TextView) findViewById(R.id.textView1);
ImageView iv=(ImageView) findViewById(R.id.imageView1);

设置内容视图后,将其放入OnCreate中,您甚至在布局实际膨胀之前就试图访问它们,这就是为什么会出现此错误。

尝试此操作。它在我的机器上工作

公共类MainActivity扩展了活动{

private static final int FILE_SELECT_CODE = 0;
//私有静态最终字符串标记=null

TextView tv;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b=(Button) findViewById(R.id.button1);
    tv=(TextView) findViewById(R.id.textView1);
    iv=(ImageView) findViewById(R.id.imageView1);



    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            showFileChooser();

        }
    });
}


private void showFileChooser() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            iv.setImageURI(uri);
       //     Log.d(TAG, "File Uri: " + uri.toString());
           }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

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

}试试这个。它在我的机器上工作

公共类MainActivity扩展了活动{

private static final int FILE_SELECT_CODE = 0;
//私有静态最终字符串标记=null

TextView tv;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b=(Button) findViewById(R.id.button1);
    tv=(TextView) findViewById(R.id.textView1);
    iv=(ImageView) findViewById(R.id.imageView1);



    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            showFileChooser();

        }
    });
}


private void showFileChooser() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            iv.setImageURI(uri);
       //     Log.d(TAG, "File Uri: " + uri.toString());
           }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

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

}

根据您的
LogCat错误
您将获得
NullPointerException

初始化您的
ImageView
TextView
全局(在
OnCreate
之前)像

ImageView iv;
TextView tv;

并将
findViewById(R.id.imageView1)
findViewById(R.id.textView1)
放在
onCreate
方法中。

根据您的
LogCat错误
您将获得
NullPointerException

初始化您的
ImageView
TextView
全局(在
OnCreate
之前)像

ImageView iv;
TextView tv;


并将
findViewById(R.id.imageView1)
findViewById(R.id.textView1)
放在
onCreate
方法中。

您能发布日志吗here@sachingarg我编辑我的答案并添加登录您的主要活动哪个是23行?@KanwaljitSingh。。什么?在哪里?发布您的活动\u main.xml。您可以发布日志吗here@sachingarg我编辑我的答案并添加登录您的主要活动哪个是23行?@KanwaljitSingh。。什么?在哪里?发布你的活动_main.xml。我做了,但我的问题没有解决。当我运行它的时候,我的应用程序停止了并且没有运行。试一下Techfist所说的。检查xml中按钮的名称。OK运行正常。但是当从文件资源管理器中选择图片时,imageview没有显示任何内容。查看此链接,我这样做了,但我的问题没有解决。当我运行它的时候,我的应用程序停止了并且没有运行。试一下Techfist所说的。检查xml中按钮的名称。OK运行正常。但是当从文件资源管理器中选择图片时,imageview没有显示任何内容。查看此链接,我将
按钮1
我自己放入
活动\u main.xml
中并进行了检查。我在上面看到这个按钮!!!!我在回答中添加了xml文件修改了我的回答,更改您的