将mysql数据库中的图像插入ImageView android

将mysql数据库中的图像插入ImageView android,android,Android,我正在尝试从我的数据库中获取图像,并在android中使用imageView插入它 我的php代码: <?php if(isset($_POST["IdToSearch"]) && $_POST["IdToSearch"] != "") { $firstid = $_POST["IdToSearch"]; $con = mysqli_connect("localhost","root","","bdUniv"); if(my

我正在尝试从我的数据库中获取图像,并在android中使用imageView插入它

我的php代码:

<?php
if(isset($_POST["IdToSearch"]) && $_POST["IdToSearch"] != "") {

        $firstid = $_POST["IdToSearch"];
        $con = mysqli_connect("localhost","root","","bdUniv");
        if(mysqli_connect_errno()) {
                echo'Database connection error: '. mysqli_connect_error();
                exit();
        }
        $firstid = mysqli_real_escape_string($con,$firstid);
        $userdetails = mysqli_query($con,"SELECT * FROM Etudiant WHERE id = '$firstid'");
        if(!$userdetails) {
                echo'Couldnotrunquery: '. mysqli_error($con);
                exit();
        }
        $row = mysqli_fetch_row($userdetails);
        $result_data = array(
        'id' => $row[0],
        'nom' => $row[1],
        'prenom' => $row[2],
        'age' => $row[3],
        'photo' => $row[4],
        );

        echo json_encode($result_data);
}else{
        echo"Could not complete query. Missingparameter";
}
?>

救命啊

你这样做是大错特错的。您的服务器返回的是服务器上的照片路径,而不是应用程序中的照片路径。当你打开文件时,你的应用程序会给你一个错误,因为该文件在本地找不到,这就是你的应用程序正在查找的地方。要解决此问题,您应该在AsyncTask中从服务器下载照片,或者存储照片的Internet路径,并使用类似库的方法将该路径处的图像下载到ImageView

编辑:


正如@Zerkz在他的评论中所指出的,您还可以通过在base64中编码图像内容,然后在异步任务中将这些内容解码为位图,从而在JSON中传递图像内容本身。如果您不打算将URL公开给您的任何图像,或者如果这些图像最终将存储在数据库中,这将是非常有利的。

注意,要从服务器下载照片,一个常见的方法是base64编码图像数据,以JSON发送,如何在AsyncTask中从服务器下载照片?最好的选择可能是将其直接编码到JSON中。看起来您现在正在本地服务器上运行此功能,这使得通过URL公开图像有点困难,而且这不是一个好的长期解决方案。@NathanWalters,正如您告诉我使用毕加索时,我将:Picasso.with(mContext).load(strPictPath).into(imgViewPhoto);在onPostExecute()中;但我有很多错误。这是因为您使用的路径是相对于服务器的,而不是相对于设备的。设备正在本地查找该路径,但找不到任何内容,因为它不在那里。您需要使用internet URL,或者将图片包含在JSON中。
package com.example.getdatafrombdd;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity_GET extends Activity {

    Button buttonGetData = null;
    EditText editTextSearchString = null;
    TextView textViewId = null;
    TextView textViewNom = null;
    TextView textViewPrenom = null;
    TextView textViewAge = null;
    ImageView imgViewPhoto = null;


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

        buttonGetData = (Button) findViewById(R.id.buttonGetData);
        editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
        textViewId = (TextView) findViewById(R.id.txtId);
        textViewNom = (TextView) findViewById(R.id.txtNom);
        textViewPrenom = (TextView) findViewById(R.id.txtPrenom);
        textViewAge = (TextView) findViewById(R.id.txtAge);
        imgViewPhoto = (ImageView) findViewById(R.id.imgPhoto);

        //Setup the Button's OnClickListener
        buttonGetData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Get the data
                DoPOST mDoPOST = new DoPOST(MainActivity_GET.this, editTextSearchString.getText().toString());
                mDoPOST.execute("");
                buttonGetData.setEnabled(false);
            }
        });
    }

    @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_activity__get, menu);
        return true;
    }

    public class DoPOST extends AsyncTask<String, Void, Boolean> {
        // String: le type des paramètres fournis à la tâche.
        // Void: le type de données transmises durant la progression du traitement.
        // Boolean: le type du résultat de la tâche.

        Context mContext = null;
        String IdToSearch = "";

        //Result data
        int intId;
        String strNom;
        String strPrenom;
        int intAge;
        String strPictPath;


        Exception exception = null;

        DoPOST(Context context, String nameToSearch) {
            mContext = context;
            IdToSearch = nameToSearch;
        }

        @Override
        protected Boolean doInBackground(String... arg0) {

            try{
                //Setup the parameters
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                //                                               key               value
                nameValuePairs.add(new BasicNameValuePair("IdToSearch", IdToSearch));   
                //Add more parameters as necessary

                //Create the HTTP request
                HttpParams httpParameters = new BasicHttpParams();

                //Setup timeouts
                HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
                HttpConnectionParams.setSoTimeout(httpParameters, 15000);           

                HttpClient httpclient = new DefaultHttpClient(httpParameters);

                HttpPost httppost = new HttpPost("http://10.0.2.2/univ/getFromUniv.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));        

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                String result = EntityUtils.toString(entity);

                // Create a JSON object from the request response
                JSONObject jsonObject = new JSONObject(result);

                //Retrieve the data from the JSON object
                intId = jsonObject.getInt("id");
                strNom = jsonObject.getString("nom");
                strPrenom = jsonObject.getString("prenom");
                intAge = jsonObject.getInt("age");
                strPictPath = jsonObject.getString("photo");

            }catch (Exception e){
                Log.e("ClientServerDemo", "Error:", e);
                exception = e;
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean valid){
            //Update the UI
            textViewId.setText("Id: " + intId);
            textViewNom.setText("Nom: " + strNom);
            textViewPrenom.setText("Prenom: " + strPrenom);
            textViewAge.setText("Age: " + intAge);  

            File imgFile = new  File(strPictPath);
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            imgViewPhoto.setImageBitmap(myBitmap);

            buttonGetData.setEnabled(true);

            if(exception != null){
                Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
1-06 20:19:17.527: E/BitmapFactory(786): Unable to decode stream: java.io.FileNotFoundException: /home/user/images/myPict.jpg: open failed: ENOENT (No such file or directory)