如何设置ImageView以显示图像网址中的图像?

时间:2016-01-24 03:33:08

标签: java android json bitmap imageview

当我尝试设置ImageView变量" profilePicture"从图像网址到位图,它没有显示任何内容。请帮忙!!我从我的数据库获取图像URL链接。这就是异步任务结果。 System.out:结果值:{" image":" http://www.myegotest.com/PhotoUpload/uploads/5.png"}

这是我的Java代码

public class HomeActivity扩展了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);
        }
}

}

1 个答案:

答案 0 :(得分:1)

如果您看到背景白色而不是图像。使用位图的内存不足。

您可以使用

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

我建议和Piccasso一起去。因为它会处理所有事情。