简体   繁体   English

图片未设置为imageview

[英]Image is not getting set to imageview

I am converting string to url and then url to bitmap to set image in image view in AsynTask method. 我将字符串转换为url,然后将url转换为位图,以在AsynTask方法的图像视图中设置图像。 but when i am calling AsyncTask method it doesn't goes into it and app crashes with nullpointerexception.Where I am making mistake?please correct me..any help will be greatly appreciated. 但是当我调用AsyncTask方法时,它没有进入其中,应用程序因nullpointerexception崩溃而崩溃。我在哪里出错?请更正我..任何帮助将不胜感激。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contributor_profile);
        contributorName = (TextView) findViewById(R.id.contributor_name);
        androidOS = Build.VERSION.RELEASE;
        device_uuid= Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);

        profile_pic = (ImageView) findViewById(R.id.profile_pic);
        myChronometer = (Chronometer)findViewById(R.id.recordtime);
        per = (TextView) findViewById(R.id.per);
        statement = (EditText) findViewById(R.id.reason);
        time = (EditText) findViewById(R.id.hours_count);
        month_week = (Spinner) findViewById(R.id.weekmonth);
        Bundle bun = getIntent().getExtras();
        contributor_name = bun.getString("FIRST_NAME");
        profile_id = bun.getString("P_ID");
        profile_img = bun.getString("PROFILE_PIC");
        profileImg = "https://www.thetagoreproject.org"+profile_img;
        try {
            URL url = new URL(profileImg);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        new BitmapAsyncTask().execute();
        profile_pic.setImageBitmap(bitmap);

        Log.d(TAG, " contributor_name Check :" + contributor_name);
        Log.d(TAG, " profile_id Check :" + profile_id);

        finished= (Button) findViewById(R.id.finished);
        finished.setOnClickListener(this);
        buttonStart = (ImageButton) findViewById(R.id.samplerecord);
        buttonStart.setImageResource(R.mipmap.vs_sample_record);
        buttonStop = (ImageButton) findViewById(R.id.stop);
        buttonPlayLastRecordAudio = (ImageButton) findViewById(R.id.play);
        buttonStopPlayingRecording = (ImageButton) findViewById(R.id.stopplay);
        buttonStop.setEnabled(false);
        buttonPlayLastRecordAudio.setEnabled(false);
        buttonStopPlayingRecording.setEnabled(false);
        contributorName.setText("Hey" +contributor_name);
        //profile_pic.setImageBitmap(bitmap);
        db = new SQLiteHandler(getApplicationContext());

           random = new Random();

        buttonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(checkPermission()) {

                    AudioSavePathInDevice =
                            Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
                                    CreateRandomAudioFileName(5) + "AudioRecording.mp3";

                    MediaRecorderReady();

                    try {
                        mediaRecorder.prepare();
                        mediaRecorder.start();
//                        mediaRecorder.setMaxDuration(6000);
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    buttonStart.setEnabled(false);
                    buttonStart.setVisibility(View.INVISIBLE);
                    buttonStop.setImageResource(R.mipmap.vs_sample_stoprecord);
                    buttonStop.setEnabled(true);
                    buttonStop.setVisibility(View.VISIBLE);
                    myChronometer.setBase(SystemClock.elapsedRealtime());
                    myChronometer.setVisibility(View.VISIBLE);
                    myChronometer.start();
                    Toast.makeText(ContributorProfile.this, "Recording started",
                            Toast.LENGTH_LONG).show();
                } else {
                    requestPermission();
                }

            }
        });

        buttonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaRecorder.stop();
                myChronometer.stop();
                myChronometer.setVisibility(View.INVISIBLE);
                buttonStop.setEnabled(false);
                buttonStop.setVisibility(View.INVISIBLE);
                buttonPlayLastRecordAudio.setEnabled(true);
                buttonPlayLastRecordAudio.setVisibility(View.VISIBLE);
//                buttonStart.setEnabled(true);
//                buttonStart.setVisibility(View.VISIBLE);
//                buttonStopPlayingRecording.setEnabled(false);


                Toast.makeText(ContributorProfile.this, "Recording Completed",
                        Toast.LENGTH_LONG).show();
            }
        });

        buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) throws IllegalArgumentException,
                    SecurityException, IllegalStateException {
//                buttonStop.setEnabled(false);
//                buttonStart.setEnabled(false);
                buttonStopPlayingRecording.setEnabled(true);
                buttonStopPlayingRecording.setVisibility(View.VISIBLE);

                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(AudioSavePathInDevice);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();
                Toast.makeText(ContributorProfile.this, "Recording Playing",
                        Toast.LENGTH_LONG).show();
            }
        });

        buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                buttonStop.setEnabled(false);
                buttonStart.setEnabled(true);
                buttonStart.setVisibility(View.VISIBLE);
                buttonStopPlayingRecording.setEnabled(false);
                buttonStopPlayingRecording.setVisibility(View.INVISIBLE);
//                buttonPlayLastRecordAudio.setEnabled(true);

                if(mediaPlayer != null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    MediaRecorderReady();
                }
            }
        });


    }
    private class BitmapAsyncTask extends AsyncTask<Void,Void,Void> {


        @Override
        protected Void doInBackground(Void... params) {
            getBitmapFromURL(profileImg);

            return null;
        }


    }

    public  Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(input);

            return bitmap;

        } catch (IOException e) {
            // Log exception
            return null;
        }
    }


    @Override
    public void onClick(View v) {
        if (v == finished) {

            String tag_string_req = "req_login";

            StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            Log.d(TAG, "Reponse Check for sound upload login :" + response);

                            // Log.d(TAG,"Object Check :"+json);
                            try {
                                JSONObject json = new JSONObject(response);
                                access_token = json.getString("access_token");
                                expires_in = json.getString("expires_in");
                                refresh_token = json.getString("refresh_token");
//                                doFileUpload();
                                new AsyncTaskRunner().execute();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
                            Log.e(TAG, "Error Response Check :" + error);

                        }
                    }) {

                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("client_id", client_id);
                    params.put("client_secret", client_secret);
                    params.put("grant_type", grant_type);
                    params.put("username", username);
                    params.put("password", user_password);
                    Log.d(TAG, "Params :" + params);
                    return params;

                }


            };
            //how to do tht??
            AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

//                ContributorsProfile();
//            forwardtoOurServer();
            Intent i = new Intent(ContributorProfile.this, Categories.class);
            startActivity(i);
//               UploadAudio();
        }

//        }else if(v==buttonUpload){
        // accesstoken.checkLogin();//yahan pe call lr rhe h....nd isk ajo v response aa rha h...uska value isi class me chahiye...

    }

    public byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] buffer = new byte[1024];
        while (read != -1) {
            read = in.read(buffer);
            if (read != -1)
                out.write(buffer,0,read);
        }
        out.close();
        return out.toByteArray();
    }

    public void forwardtoOurServer() {
        final String statemnt = statement.getText().toString().trim();
        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, CONTRIBUTORPROFILE_API,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        Log.d(TAG,"Object Check :"+response);
                        try {
                            JSONObject json = new JSONObject(response).getJSONObject("contributor").getJSONObject("Contributor");
                            contributor_id = json.getString("id");
                            String profile_id = json.getString("profile_id");
                            String secret_token = json.getString("secret_token");
                            String statement = json.getString("statement");
                            String status = json.getString("status");
                            String time = json.getString("time");
                            String uploaded_on = json.getString("uploaded_on");
                            String vs_cdn_id = json.getString("vs_cdn_id");
                            String created = json.getString("created");
                            String modified = json.getString("modified");
                            contributor_id = json.getString("id");
                            session.addContributorSession(contributor_id);
                            db.addContributor(contributor_id, profile_id, secret_token, statement, status, time, uploaded_on, vs_cdn_id, created, modified);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Contributor][statement]",statemnt);
                params.put("data[Contributor][profile_id]",profile_id);
                params.put("data[Contributor][status]","1");
                params.put("data[Contributor][secret_token]",secret_token);
                params.put("data[Contributor][vs_cdn_id]",vs_cdn_id);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Contributor][uploaded_on]",strDate);
                //params.put("data[Contributor][time]",hours+" hours "+"per "+months);


//                    params.put("password", user_password);
                Log.d(TAG, "Params :" + params);
                return params;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };


        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }
    public void MediaRecorderReady(){
        mediaRecorder=new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    public String CreateRandomAudioFileName(int string){
        StringBuilder stringBuilder = new StringBuilder( string );
        int i = 0 ;
        while(i < string ) {
            stringBuilder.append(RandomAudioFileName.
                    charAt(random.nextInt(RandomAudioFileName.length())));

            i++ ;
        }
        return stringBuilder.toString();
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(ContributorProfile.this, new
                String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {
            case RequestPermissionCode:
                if (grantResults.length> 0) {
                    boolean StoragePermission = grantResults[0] ==
                            PackageManager.PERMISSION_GRANTED;
                    boolean RecordPermission = grantResults[1] ==
                            PackageManager.PERMISSION_GRANTED;

                    if (StoragePermission && RecordPermission) {
                        Toast.makeText(ContributorProfile.this, "Permission Granted",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(ContributorProfile.this,"Permission Denied",Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(),
                WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
                RECORD_AUDIO);
        return result == PackageManager.PERMISSION_GRANTED &&
                result1 == PackageManager.PERMISSION_GRANTED;
    }
    private class AsyncTaskRunner extends AsyncTask<String,Void,String> {


        @Override
        protected String doInBackground(String... params) {
            doFileUpload();
            return null;
        }


    }

This is my RoundedImageView.java and the nullpointerexception occuring in this line of RoundedImageview class "Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);" 这是我的RoundedImageView.java和nullpointerexception发生在RoundedImageview类的这一行中“ Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888,true);”

public class RoundedImageView extends android.support.v7.widget.AppCompatImageView{

    public RoundedImageView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }



    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                finalBitmap.getHeight() / 2 + 0.7f,
                finalBitmap.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
    }

log: 日志:

05-24 12:33:45.838 29693-29693/com.showhow2.www.thetagoreproject D/AndroidRuntime: Shutting down VM
05-24 12:33:45.839 29693-29693/com.showhow2.www.thetagoreproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                   Process: com.showhow2.www.thetagoreproject, PID: 29693
                                                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
                                                                                       at com.showhow2.www.thetagoreproject.RoundedImageView.onDraw(RoundedImageView.java:38)
                                                                                       at android.view.View.draw(View.java:16184)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15180)
                                                                                       at android.view.View.draw(View.java:15954)
                                                                                       at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
                                                                                       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15175)
                                                                                       at android.view.View.draw(View.java:15954)
                                                                                       at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
                                                                                       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
                                                                                       at android.view.View.draw(View.java:16187)
                                                                                       at android.widget.ScrollView.draw(ScrollView.java:1712)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15180)
                                                                                       at android.view.View.draw(View.java:15954)
                                                                                       at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
                                                                                       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15175)
                                                                                       at android.view.View.draw(View.java:15954)
                                                                                       at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
                                                                                       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15175)
                                                                                       at android.view.View.draw(View.java:15954)
                                                                                       at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
                                                                                       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
                                                                                       at android.view.View.draw(View.java:16187)
                                                                                       at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2690)
                                                                                       at android.view.View.updateDisplayListIfDirty(View.java:15180)
                                                                                       at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281)
                                                                                       at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287)
                                                                                       at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322)
                                                                                       at android.view.ViewRootImpl.draw(ViewRootImpl.java:2615)
                                                                                       at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2434)
                                                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2067)
                                                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                                       at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
05-24 12:38:45.892 29693-29693/com.showhow2.www.thetagoreproject I/Process: Sending signal. PID: 29693 SIG: 9

Use this method to convert your drawable to a bitmap: 使用此方法将可绘制对象转换为位图:

public static Bitmap drawableToBitmap (Drawable drawable){
        Bitmap bitmap = null;

        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if (bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable.getBitmap();
            }
        }

        if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }

Then instead of using in the original code, the following line: 然后,而不是在原始代码中使用,而是以下行:

Bitmap b = ((BitmapDrawable) drawable).getBitmap();

Use this instead: 使用此代替:

Bitmap b = drawableToBitmap(drawable);

Original answer by: Simon 原始答案:西蒙

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

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