简体   繁体   中英

How to convert Blob data in MYSQL to Android ImageView

Android 3.1 (API 12) - Strict, this is a commercial app and will not be on any other devices.

I (n00b) am trying to retrieve an array of images stored as Blobs in Mysql on our servers and add them to ImageView 's in Android.

First, server-side: I am not sure whether to base64_encode or json_encode , here is my current PHP and results.


PHP:

$query = "SELECT `locations`.`businessName`, `photos`.`img` 
        FROM `locations` 
        JOIN `photos` ON `locations`.`co_id` = `photos`.`co_id` 
        WHERE `locations`.`businessName` = '".$companyID."'";

    mysql_connect($dbserver, $dbusername, $dbpassword) or die(mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    $result = mysql_query($query) or die(mysql_error());  


    while ($row = mysql_fetch_array($result)) {
        $finalImg[] = $row['img'];

        foreach ($finalImg as $img) {
            $finallyWeAreThere = base64_encode($img);
        }

    }

    echo $finallyWeAreThere;

    mysql_close();

Result:

/9j/4AAQSkZJRgABAQEAYABgAAD/... and so on.. and so on..

Now to the Android side of things. Before I try to pull the images I connect to the same database in a different Activity to get a list of Company names (Successfully), once clicking on the company name that's when the images are gathered through passing the Company Name by Intent to my Main class.

I used the success of my Company Name gathering as a starting ground so this Main.java file code is very raw and potentially very wrong.

Main.java (Right now, I haven't included a for or while loop to display all images, I'd be happy to get just one image returned at this point):

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Get the appropriate layout
        setContentView(R.layout.main);

        Bundle extras = getIntent().getExtras();
        businessName = extras.getString("companyName");

        // Load AsyncTask to get photos from server
        new RetrievePhotos().execute(businessName);
    }

    class RetrievePhotos extends AsyncTask<String, String, Void> {
        private ProgressDialog progressDialog = new ProgressDialog(Main.this);
        InputStream inputStream = null;
        String result = ""; 

        protected void onPreExecute() {
            progressDialog.setMessage("Gathering photos...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener() {
                public void onCancel(DialogInterface diaInterface) {
                    RetrievePhotos.this.cancel(true);
                    diaInterface.dismiss();
                }
            });
        }

        @Override
        protected Void doInBackground(String... params) {

            String url_select = "http://www.someCompany.com/someFile.php?imgTest=true&companyName=" + businessName;
            imView = (ImageView)findViewById(R.id.imageView1);

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            try {
                // Set up HTTP post
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url_select);
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // Read content & Log

                inputStream = httpEntity.getContent();
                bmImg = BitmapFactory.decodeStream(inputStream);
                imView.setImageBitmap(bmImg);

                Log.i("HttpClient", "Called on the HTTP Client and went to: " + url_select);
            } catch (UnsupportedEncodingException e1) {
                Log.e("UnsupportedEncodingException", e1.toString());
                e1.printStackTrace();
            } catch (ClientProtocolException e2) {
                Log.e("ClientProtocolException", e2.toString());
                e2.printStackTrace();
            } catch (IllegalStateException e3) {
                Log.e("IllegalStateException", e3.toString());
                e3.printStackTrace();
            } catch (IOException e4) {
                Log.e("IOException", e4.toString());
                e4.printStackTrace();
            }

            // Convert response to string using String Builder
            try {
                BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
                StringBuilder sBuilder = new StringBuilder();

                String line = null;
                while ((line = bReader.readLine()) != null) {
                    sBuilder.append(line + "\n");
                }

                inputStream.close();
                result = sBuilder.toString();

            } catch (Exception e) {
                Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
            }
            return null;

        } // end doInBackground

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/hsdarker"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="150dp"
        android:layout_height="112dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="50dp" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="300dp"
        android:layout_height="225dp"
        android:layout_below="@id/imageView1"
        android:layout_toRightOf="@id/imageView1" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="150dp"
        android:layout_height="112dp"
        android:layout_alignTop="@id/imageView1"
        android:layout_marginLeft="208dp"
        android:layout_toRightOf="@id/imageView2" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="300dp"
        android:layout_height="225dp"
        android:layout_below="@id/imageView3"
        android:layout_marginRight="75dp"
        android:layout_toRightOf="@id/imageView3" />

</RelativeLayout>

Logcat Error log:

07-17 09:39:00.775: W/dalvikvm(5222): threadid=11: thread exiting with uncaught exception (group=0x40202760)
07-17 09:39:00.775: E/AndroidRuntime(5222): FATAL EXCEPTION: AsyncTask #2
07-17 09:39:00.775: E/AndroidRuntime(5222): java.lang.RuntimeException: An error occured while executing doInBackground()
07-17 09:39:00.775: E/AndroidRuntime(5222):     at android.os.AsyncTask$3.done(AsyncTask.java:266)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.lang.Thread.run(Thread.java:1020)
07-17 09:39:00.775: E/AndroidRuntime(5222): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 82: http://www.holidaysigns.com/db/nstCompanyList.php?imgTest=true&companyName=HOLIDAY SIGNS
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.net.URI.create(URI.java:769)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at holidaysigns.nst.Main$RetrievePhotos.doInBackground(Main.java:148)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at holidaysigns.nst.Main$RetrievePhotos.doInBackground(Main.java:1)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at android.os.AsyncTask$2.call(AsyncTask.java:252)
07-17 09:39:00.775: E/AndroidRuntime(5222):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-17 09:39:00.775: E/AndroidRuntime(5222):     ... 4 more

I have researched non-stop on this, and to be honest I don't have a clue where to go at this point or if I am setting it up properly server-side. I apologize for being a n00b. Any help or direction is much appreciated.

You have 2 problems.

First, your URL is not properly encoded. Most likely the space in the businessName that's causing you the problem. You need to URLEncoder.encode(businessName,"UTF-8") to handle any spaces or special characters that might appear in the businessName's.So "companyName=HOLIDAY SIGNS" will become "companyName=HOLIDAY+SIGNS".

The second problem is that you are attempting to set the ImageView inside a background thread. You need to set the ImageView contents on the main thread (the UI thread). Change your doInBackground() to return the decoded bitmap, instead of void, and add an onPostExcecute(Bitmap bitmap) method that will set the bitmap into the ImageView. onPostExecute runs in the UI thread. (Be sure to check for null).

The URL

http://www.holidaysigns.com/db/nstCompanyList.php?imgTest=true&companyName=HOLIDAY SIGNS

has an illegal character, according to the exception.

This character is the space, " ". Replace all spaces with a plus (+) sign and try again!

The reason that spaces are illegal is as follows:

A typical HTTP request initiates like this:

GET /url HTTP/1.1

So theres three things seperated by spaces: the method, the URI and the HTTP protocol version. What if you put a url like yours in there?

GET /db/nstCompanyList.php?imgTest=true&companyName=HOLIDAY SIGNS HTTP/1.1

Method: GET
URL: /db/nstCompanyList.php?imgTest=true&companyName=HOLIDAY
HTTP VERSION: SIGNS

... Something went wrong, right?

And this is why spaces are not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM