如何将MYSQL中的Blob数据转换为Android ImageView


How to convert Blob data in MYSQL to Android ImageView

Android 3.1(API 12)-严格,这是一款商业应用程序,不会在任何其他设备上使用。

我(n00b)正试图在我们的服务器上检索Mysql中存储为Blob的一组图像,并将它们添加到Android中的ImageView中。

首先,服务器端:我不确定是base64_encode还是json_encode,这是我当前的PHP和结果。


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

结果:

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

现在来谈谈安卓方面的事情。在我尝试提取图像之前,我连接到不同Activity中的同一数据库以获得公司名称列表(成功),单击公司名称后,通过将Company name by Intent传递到我的Main类来收集图像。

我以公司名称收集的成功为起点,所以这个Main.java文件代码非常原始,可能非常错误。

Main.java(目前,我还没有包含显示所有图像的forwhile循环,我很乐意在此时只返回一个图像):

    @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错误日志:

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

我一直在研究这个问题,老实说,我不知道现在该去哪里,也不知道我是否在服务器端正确设置了它。我为自己是n00b而道歉。非常感谢您的帮助或指导。

您有两个问题。

首先,您的URL编码不正确。很可能是businessName中的空格导致了问题。您需要URLEncoder.encode(businessName,"UTF-8")来处理可能出现在businessName的s中的任何空格或特殊字符。因此,"companyName=HOLIDAY SIGNS"将变为"companyName=HOLIDAY+SIGNS"。

第二个问题是您试图在后台线程中设置ImageView。您需要在主线程(UI线程)上设置ImageView内容。更改doInBackground()以返回解码后的位图,而不是void,并添加一个onPostExcecute(位图位图)方法,将位图设置到ImageView中。onPostExecute在UI线程中运行。(请务必检查是否为空)。

URL

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

根据例外情况,具有非法字符。

这个字符就是空格"。用加号(+)替换所有空格,然后重试!

空格非法的原因如下:

一个典型的HTTP请求启动如下:

GET /url HTTP/1.1

因此,有三件事用空格隔开:方法、URI和HTTP协议版本。如果你把一个像你的网址放在那里呢?

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

出了问题,对吧?

这就是为什么不允许使用空格。