getcontentresolver()未定义类型

时间:2015-03-23 13:29:45

标签: java android eclipse android-fragments import

您好我是java的新手,我正在尝试创建一个应用程序来上传手机内存中的图片。我正在尝试将图片从我的图库上传到我的应用程序,我收到错误"方法getConstentResolver()未定义类型Upload"我该如何解决这个问题?

以下是我的代码......

public class Upload extends Fragment {

    private static final int SELECTED_PICTURE=1;
    ImageView iv;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.upload, container, false);

        iv=(ImageView)rootView.findViewById(R.id.imageView1);

        return rootView;

    }

    public void btnClick(View v){
        Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, SELECTED_PICTURE);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch(requestCode){
        case SELECTED_PICTURE:
            if(resultCode==RESULT_OK){
                Uri uri =data.getData();
                String[]projection={MediaStore.Images.Media.DATA};

                Cursor cursor=getConstentResolver().query(uri,projection,null,null,null);
                cursor.moveToFirst();
                int columnIndex=cursor.getColumnIndex(projection[0]);
                String filePath=cursor.getString(columnIndex);
                cursor.close();

                Bitmap yourSelectedImage=BitmapFactory.decodeFile(filePath);
                Drawable d=new BitmapDrawable(yourSelectedImage);
                iv.setBackground(d);


            }
                    }
    }


    }

3 个答案:

答案 0 :(得分:0)

您可以通过在getContentResolver()之前添加

来解决这个问题
getApplicationContext().getContentResolver() 

Cursor cursor=getConstentResolver().query(uri,projection...

这是错误告诉您,您无法从Fragment类获取ContentResolver,因为它不包含必需的Context。您应该从Activity或整个Application获取Context的实例以获取contentResolver。

答案 1 :(得分:0)

使用此代码:

public class EditProfileFragment extends Fragment {
private Button bt_browse;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.edit_profile_fragment,
            container, false);
    bt_browse = (Button) rootView.findViewById(R.id.bt_browse);


    bt_browse.setOnClickListener(new OnClickListener() {

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



    return rootView;

}



private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Select Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"), SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            File f = new File(Environment.getExternalStorageDirectory()
                    .toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);

                bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                iv_photo.setImageBitmap(bm);
                uploadImagePath = f.getAbsolutePath();

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();

            String tempPath = getPath(selectedImageUri, getActivity());
            Bitmap bm;
            BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
            bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
            iv_photo.setImageBitmap(bm);
            uploadImagePath = tempPath;

        }
    }
}

@SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
    String[] projection = { MediaColumns.DATA };
    Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);

}



}

您选择的图像存储在uploadImagePath字符串中。 只需在日志中打印,然后你理解..

任何进一步的帮助都不要犹豫,问我..

答案 2 :(得分:0)

嗨,请看下面的代码,它工作正常。

package test.actionbariconupdate;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;


public class ActionBarIconUpdate extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action_bar_icon_update2);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }
    }


    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        private Button buttonclick;
        private ImageView imageview;

        public PlaceholderFragment() {
            Log.d("TAG","PlaceholderFragment");
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            setHasOptionsMenu(true);
            View rootView = inflater.inflate(R.layout.fragment_action_bar_icon_update, container, false);
            imageview = (ImageView)rootView.findViewById(R.id.imageview);
            buttonclick = (Button)rootView.findViewById(R.id.buttonclick);
            buttonclick.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    btnClick();
                }
            });
            return rootView;
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data){
            super.onActivityResult(requestCode,resultCode,data);
            switch(requestCode){
                case 1:
                    if(resultCode==RESULT_OK){
                        Uri uri =data.getData();
                        String[]projection={MediaStore.Images.Media.DATA};

                        Cursor cursor= getActivity().getApplicationContext().getContentResolver().query(uri, projection, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex=cursor.getColumnIndex(projection[0]);
                        String filePath=cursor.getString(columnIndex);
                        cursor.close();

                        Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
                        Drawable d=new BitmapDrawable(yourSelectedImage);
                        imageview.setBackground(d);
                    }
            }
        }

        public void btnClick(){
            Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 1);

        }
    }
}