0

I am trying to get an image from my data base and insert it using imageView in android

my php code:

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

My java code:

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

} }

When i compiled it i get the: id, name, 2nd name, age but no image found! And the error is:

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)

Help please!

1 Answer 1

2

You are doing this very wrong. Your server is returning the path of the photo on the server, not in the app. When you go to open the file, your app gives you an error because the file is not found locally, which is where your app is looking. To fix this, you should either download the photo from the server in your AsyncTask or store the Internet path of your picture and use a library like Picasso to download the image at that path to the ImageView.

EDIT:

As @Zerkz noted in his comment, you could also pass the image contents itself in your JSON by encoding them in base64 and then decoding those contents to a Bitmap in your AsyncTask. This would be advantageous if you don't plan on publicly exposing the URL to any of your images or if they will eventually be stored in a database.

Sign up to request clarification or add additional context in comments.

7 Comments

Note, to download a photo from your server, a common route would be to base64 encode the image data, send it in the JSON, and then decode it into the ImageView once recieved.
how to download the photo from the server in AsyncTask?
Your best option is probably encoding it directly into your JSON. It looks like you're running this on a local server as of now, which makes it a bit more difficult to expose an image via a URL, and it would not be a good long-term solution.
@NathanWalters, as you told me i used Picasso, i placed: Picasso.with(mContext).load(strPictPath).into(imgViewPhoto); in onPostExecute(); but i got many errors.
This is because the path you are using is relative to the server, not the device. The device is looking for that path locally, but it doesn't find anything because it isn't there. You either need to use an internet URL, or else include the picture in the JSON.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.