我正在尝试从我的数据库中获取图像并使用imageView在android中插入它
我的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";
}
?>
我的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,name,2nd name,age但没有找到图像! 错误是:
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)
请帮忙!
答案 0 :(得分:2)
你这样做是错的。您的服务器正在返回服务器上的照片的路径,而不是应用程序中的路径。当您打开文件时,您的应用会给您一个错误,因为该文件未在本地找到,这是您的应用所在的位置。要解决此问题,您应该从AsyncTask中的服务器下载照片或存储图片的Internet路径,并使用像Picasso这样的库将该路径下的图像下载到ImageView。
编辑:
正如@Zerkz在他的评论中指出的那样,你也可以通过在base64中对它们进行编码,然后将这些内容解码为AsyncTask中的Bitmap,在JSON中传递图像内容。如果您不打算公开将URL暴露给任何图像,或者它们最终将存储在数据库中,这将是有利的。