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

时间:2013-12-12 09:09:19

标签: java android

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

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

activiyt_main 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>

4 个答案:

答案 0 :(得分:1)

试试这个 -

 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;
        }

    }

答案 1 :(得分:0)

请参阅此at android.app.Activity.findViewById(Activity.java:1883),这表示您的XML文件R.layout.activity_main没有名称为button1的按钮,请检查。

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

在设置内容视图后将其放入OnCreate中,即使在布局实际膨胀之前,您也试图访问它们,即此错误即将到来。

答案 2 :(得分:0)

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

公共类MainActivity扩展了Activity {

private static final int FILE_SELECT_CODE = 0;

// private static final String TAG = 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;
}

}

答案 3 :(得分:0)

根据您LogCat error获得的NullPointerException

在全球范围内(ImageView之前)初始化您的{{1and1}},例如

TextView

并将OnCreateImageView iv; TextView tv; 放在findViewById(R.id.imageView1)方法中。