2014-01-06 52 views
0

我想從我的數據的基礎上獲得的圖像,並在Android的插入圖像到ImageView的安卓

我的PHP代碼中使用ImageView的插入:

<?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"; 
} 
?> 

我的Java代碼:

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

}}

當我編譯它,我得到的:ID,姓名,第二名,年齡但沒有找到圖像! 錯誤是:

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) 

請幫助!

回答

2

你這樣做很不對。您的服務器正在返回服務器上的照片的路徑,而不是在應用程序中。當你打開文件時,你的應用程序會給你一個錯誤,因爲該文件沒有在本地找到,這是你的應用程序正在尋找的地方。要解決這個問題,您應該從AsyncTask中的服務器下載照片或存儲圖片的Internet路徑,並使用像Picasso這樣的庫將該路徑下的圖像下載到ImageView。

編輯:

由於@Zerkz在他的評論中指出的那樣,你也可以通過Base64編碼它們,然後在你的AsyncTask這些內容爲位圖解碼通過圖像內容本身在你的JSON。如果您不打算公開地將URL映射到您的任何圖像,或者它們最終將被存儲在數據庫中,這將是有利的。

+1

注意,要從您的服務器下載照片,常見的路線是base64對圖像數據進行編碼,以JSON格式發送,然後在接收後將其解碼爲ImageView。 – Zerkz

+0

如何從AsyncTask中的服務器下載照片? – user3166804

+0

你最好的選擇可能是直接編碼到你的JSON中。它看起來像你現在在本地服務器上運行它,這使得通過URL公開一個圖像變得更加困難,並且這不是一個好的長期解決方案。 –