【问题标题】:How to convert Blob data in MYSQL to Android ImageView如何将MYSQL中的Blob数据转换为Android ImageView
【发布时间】:2012-07-17 14:16:58
【问题描述】:

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..

现在到 Android 方面。在我尝试提取图像之前,我连接到不同 Activity 中的同一数据库以获取公司名称列表(成功),一旦单击公司名称,即通过按意图传递公司名称来收集图像我的主要课程。

我以公司名称收集的成功作为起点,所以这个 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而道歉。非常感谢任何帮助或指导。

【问题讨论】:

    标签: php android mysql


    【解决方案1】:

    你有两个问题。

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

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

    【讨论】:

    • %20 实际上并没有在 QueryStrings 中使用...那里是“+”。
    • 太好了,谢谢。一切都变了,@sinni800 就在+ 上。我将接受您的回答,它仍然无法正常工作,它只是挂在我的对话框上,但我没有收到任何错误。我应该从这里很好。希望。再次感谢!
    • 是的,我同意。他有更完整的答案。我对Android开发一无所知:)
    • 你也应该看看这里:stackoverflow.com/questions/3821423/… - 你会遇到旋转问题。 ;)
    • 完美运行,再次感谢。也感谢您的参考,非常好的材料。幸运的是,这个项目不允许任何屏幕旋转,所以我应该很好。然而,我正在从事的个人项目将受益匪浅。 :)
    【解决方案2】:

    网址

    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
    

    ...出了点问题,对吧?

    这就是不允许使用空格的原因。

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2020-10-09
      • 2020-11-10
      • 2015-03-12
      • 1970-01-01
      相关资源
      最近更新 更多