简体   繁体   中英

How do i set an ImageView to show an image from an image url?

When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is. System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}

Here is my Java code

public class HomeActivity extends AppCompatActivity {

//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;

//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    //Get logged in user from LocalDataBase and
    //Destroy Activity if user is logged out
    mLocalDataBase = new LocalDataBase(this);
    User user = mLocalDataBase.getLoggedInUserInfo();
    if(!mLocalDataBase.userIsLoggedIn()){
        HomeActivity.this.finish();
    }

    //Initialize view item variables.
    loggedUsersName = (TextView)findViewById(R.id.login_user);
    successMessage = (TextView)findViewById(R.id.message);
    logoutButton = (Button)findViewById(R.id.logoutButton);
    profilePicture = (ImageView)findViewById(R.id.profile_Picture);

    //Get intent and values from the intent started this activity and
    //Get loggedIn user values from the LocalDataBase .
    Intent intent = getIntent();
    String message = intent.getStringExtra("MESSAGE");
    firstName = user.mFirstName;
    lastName = user.mLastName;
    email = user.mEmail;

    //Set view values to equal values sent from intent.
    loggedUsersName.setText(firstName + " " + lastName);
    successMessage.setText(message);

    netAsync();


}


//Call this method to execute the Async Task
private void netAsync() {
    new NetCheck().execute();
}

//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {

    private ProgressDialog mDialog;

    //Create and show progress dialog box so user knows the app is trying to login.
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mDialog = new ProgressDialog(HomeActivity.this);
        mDialog.setTitle("Logging In...");
        mDialog.setMessage("connecting to server");
        mDialog.setIndeterminate(false);
        mDialog.setCancelable(true);
        mDialog.show();
    }

    //Gets current device state and checks for working internet connection by trying Google.
    @Override
    protected Boolean doInBackground(Object[] objects) {
        ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
        if ( (myNetInfo != null) && (myNetInfo.isConnected())){
            try {
                URL url = new URL("http://google.com");
                HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
                myConnection.setConnectTimeout(3000);
                myConnection.connect();
                if (myConnection.getResponseCode() == 200){
                    return true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);

        //If successful internet connection start AsyncTask to register user info on server
        if(o.equals(true)){
            mDialog.dismiss();
            new RegisterUser().execute(getProfileImageURL, email);
        } else {
            mDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
        }
    }
}

//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
            LucasHttpURLConnection.setRequestMethod("POST");
            LucasHttpURLConnection.setDoOutput(true);
            LucasHttpURLConnection.setDoInput(true);
            LucasHttpURLConnection.setConnectTimeout(1000 * 6);
            LucasHttpURLConnection.setReadTimeout(1000 * 6);
            //OutputStream to get response
            OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

            String data =
                    URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            //InputStream to get response
            InputStream IS = LucasHttpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
            StringBuilder response = new StringBuilder();
            String json;
            while( (json = bufferedReader.readLine()) != null){
                response.append(json + "\n");
                break;
            }
            bufferedReader.close();
            IS.close();
            LucasHttpURLConnection.disconnect();
            return response.toString().trim();
        } catch (MalformedInputException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;


    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        //Print server AsyncTask response
        System.out.println("Resulted Value: " + result);

        //If null Response
        if (result != null && !result.equals("")) {
            String profilepic = returnParsedJsonObject(result);
            new GetBitmapImageFromUrl().execute(profilepic);
            profilePicture = (ImageView)findViewById(R.id.profile_Picture);
            profilePicture.setImageBitmap(profilePicBitmap);
        } else {
            Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
        }
    }

    //Method to parse json result and get the value of the key "image"
    private String returnParsedJsonObject(String result){
        JSONObject resultObject = null;
        String returnedResult = "";
        try {
            resultObject = new JSONObject(result);
            returnedResult = resultObject.getString("image");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return returnedResult;
    }
}




class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            try {

                profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
        }
}

}

If you are seeing background white instead image. Out of memory exception by using bitmap.

You could use

Option 1

  URL newurl = new URL(photo_url_str); 
    mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
    profile_photo.setImageBitmap(mIcon_val);

Picasso

Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);

I would suggest to go with Piccasso. Since it will handle everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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