0

私の Android アプリでは、Image Blob を返す Java Web サービスを呼び出しています。これを ImageView のビットマップとして表示したいと思います。この画像ブロブは、HTML5 Canvas 要素の保存された toDataUrl() 表現です。メイン スレッドは、実行コマンドを使用して onclick として AsyncTask 内部クラスを起動します。メインスレッドは次のとおりです。

    public class MainActivity extends Activity
    {
        private ImageView outputIv;
        public View vue;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            setOutputIv((ImageView)findViewById(R.id.imageView1));
        }

        public void onClickBtn(View v){

            vue = v;
            new RequestTask(v).execute("http://10.0.2.2:8080/CasosDeUso5/webresources/casosdeusowsport/getimagenes?usuarioId=1");
        }

        /**
         * @return the outputIv
         */
        public ImageView getOutputIv() {
            return outputIv;
        }

        /**
         * @param outputIv the outputIv to set
         */
        public void setOutputIv(ImageView outputIv) {
            this.outputIv = outputIv;
        }


        class RequestTask extends AsyncTask<String, String, String>{

            private View rootView;

            public RequestTask(View rootView){
            this.rootView=rootView;
        }

        @Override
        protected String doInBackground(String... uri) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            String responseString = "STRAWBERRIES";
            try {
                response = httpclient.execute(new HttpGet(uri[0]));
                StatusLine statusLine = response.getStatusLine();
                Log.d("info", statusLine.toString());
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    responseString = out.toString();
                } else{
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
               Log.d("OH CRIKEY", e.toString());
            } catch (IOException e) {
                Log.d("OH CRIKEY", e.toString());
            }
            Log.d("info", responseString);
            return responseString;
        }

        @Override
        protected void onPostExecute(String result) {

            //super.onPostExecute(result);

            try{
                List<Imagen> imgs = Parser.parseByDOM(result);
//Below prints 3280                
Log.d("UUYU", String.valueOf(imgs.get(0).getImagen().getRowBytes()));
//Below prints 550
                Log.d("UUYU2", String.valueOf(imgs.get(0).getImagen().getHeight()));
//Below prints 820
                Log.d("UUYU3", String.valueOf(imgs.get(0).getImagen().getWidth()));

                outputIv.setImageBitmap(imgs.get(0).getImagen());                   
                //vue.invalidate();

            }catch(Exception e){ e.printStackTrace();
            Log.d("ERROR!!", ""+e.getMessage());}
            //outputTv.setText(result);    
        }

        /**
         * @return the rootView
         */
        public View getRootView() {
            return rootView;
        }

        /**
         * @param rootView the rootView to set
         */
        public void setRootView(View rootView) {
            this.rootView = rootView;
        }
        }

Bitmap の幅と高さは正しく、データがあるように見えます。完全を期すために、ここで Web サービスの応答文字列を解析し、ビットマップを設定します。すべてのデバッグは正常に見えます。

public static List<Imagen> parseByDOM(String response) throws ParserConfigurationException, SAXException, IOException{

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(response)));
    // normalize the document
    doc.getDocumentElement().normalize();
    // get the root node
    NodeList nodeList = doc.getElementsByTagName("return");
    Log.d("miaouw", nodeList.toString());
    List<Imagen> imgData = new ArrayList<Imagen>();

    for(int k = 0; k < nodeList.getLength(); k++){

        Node node=nodeList.item(0);
        Log.d("miaouw", node.getNodeName());

        Imagen img = new Imagen();

        try{

            for(int i = 0; i < node.getChildNodes().getLength(); i++){

                Node temp = node.getChildNodes().item(i);
                Log.d("miaouw", temp.getNodeName());

                if(temp.getNodeName().equalsIgnoreCase("fechaCreada")){

                    img.setFechaCreada(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH).parse(temp.getTextContent()));
                }

                else if(temp.getNodeName().equalsIgnoreCase("imagen")){

                    String encodedImg = temp.getTextContent();
                    Log.d("vroom", encodedImg); //prints long, correct base64 binary String.  If I try to convert it to an image in http://www.freeformatter.com/base64-encoder.html, I get the correct image.
                    Log.d("toom ", String.valueOf(encodedImg.length())); //prints 19383

                    byte[] decodedString = Base64.decode(encodedImg, Base64.DEFAULT);
                    Log.d("woom", decodedString.toString()); //prints B@417b72f0
                    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                    img.setImagen(decodedByte);
                }

                else if(temp.getNodeName().equalsIgnoreCase("titulo")){

                    img.setTitulo(temp.getTextContent());
                }
            }

            imgData.add(img);
            Log.d("MIAUOW", img.toString()); //prints com.example.android.Imagen@4175ec58

            Log.d("noddy", node.toString());
            return imgData;

        }catch(ParseException e){

            Log.d("MEWL", e.getMessage());
        }
    }

    return null;
}

そして最後に、これが私のレイアウトです。ビューが更新されていることを確認するためだけに、ImageView をデフォルトの Android ドローアブルに設定します (非同期であるため)。[テスト] をクリックすると、src イメージは消えますが、ビットマップに置き換えられません。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Test"
    android:onClick="onClickBtn" />
<ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:contentDescription="yep"
            android:src="@drawable/ic_launcher"/>
</LinearLayout>

これは単純な概念実証として意図されていましたが、機能しません。ビットマップがどのようにそこにあり、ビューが更新されるのかわかりませんが、ビットマップは表示されません。

4

3 に答える 3

0

自分へのメモ: 透明は白と同じではありません。

ImageView に対して次のことを行いました。

outputIv.setBackgroundColor(Color.WHITE);

そして、すべてが良かった。

于 2013-09-01T00:33:45.873 に答える
0

以下のコードでは

else if(temp.getNodeName().equalsIgnoreCase("imagen")){

                String encodedImg = temp.getTextContent();
                Log.d("vroom", encodedImg); //prints long, correct base64 binary String.  If I try to convert it to an image in http://www.freeformatter.com/base64-encoder.html, I get the correct image.
                Log.d("toom ", String.valueOf(encodedImg.length())); //prints 19383

                byte[] decodedString = Base64.decode(encodedImg, Base64.DEFAULT);
                Log.d("woom", decodedString.toString()); //prints B@417b72f0
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                img.setImagen(decodedByte);
            }

使用する

img.setImageBitmap(decodedByte);

ここでのタイプミスなのか、実際にそれを入れたのかはわかりませんが、それがコードにもある場合は、置き換えてください。

于 2013-08-31T22:07:44.120 に答える
0
/**
 * @param outputIv the outputIv to set
 */
public void setOutputIv(ImageView outputIv) {
    this.outputIv = outputIv;
}

そして、あなたはそれを次のように呼び出します:

setOutputIv((ImageView)findViewById(R.id.imageView1));

次に、this.outputIv から R.id.imageView1 の参照を配置します。OnCreate() の Layout.xml で指定されたクラス参照を一度設定しようとしましたか?

ImageView outputIv = (ImageView) findViewById(R.id.imageView1); 

それ以外の場合は、class.outputIvにR.id.imageView1のコンテンツを持たせるだけだと思いますが、これは、class.outputIvに追加しているものとは無関係のandroid:src="@drawable/ic_launcher"であることを示します。アクティビティのビューにも追加されました。

于 2013-08-31T22:08:45.467 に答える