2017-06-22 96 views
0

所以我有一個數據庫,其中的用戶名與圖像的名稱相對應。所以在我的AsyncHTTP我檢索用戶名,並希望將該用戶名映射到其正確的圖像(所有圖像位於我的可繪製文件夾中)用異步更新圖像

在我的XML中,這幅圖像將呈現我只是把imageview,並從未分配它一個圖像(這個圖像的Id是myImage)

所以當我運行我的代碼時,圖像不會呈現。由於範圍問題,我無法在異步之外分配圖像。

Context context = this; 



     AsyncHTTPPost asyncHttpPost2 = new AsyncHTTPPost(
       "http://lamp.ms.wits.ac.za/~s1363679/avatars.php", params) { 

      @Override 
      protected void onPostExecute(String s) { 


       try { 
        JSONArray all = new JSONArray(s); 
        for (int i = 0; i < all.length(); i++) { 

         JSONObject item = all.getJSONObject(i); 

         fName = item.getString("avatarName"); 
         System.out.println(); 
         Toast.makeText(Profile.this, fName, Toast.LENGTH_LONG).show(); 

         ImageView Image = (ImageView) findViewById(R.id.myImage); 
         System.out.println(""); 
         theName = fName; 
         //String imagename="kaius"; 

         Resources res = context.getResources(); 
         int resID = res.getIdentifier(theName, "drawable", context.getPackageName()); 
         Image.setImageResource(resID); 

        } 
       } catch (Exception e) { 
        Toast.makeText(Profile.this, e.toString(), Toast.LENGTH_LONG).show(); 
       } 
      } 
     }; 
     asyncHttpPost2.execute(); 



    } 

imageName被正確地檢索並存儲在變量「theName」中,但它似乎沒有渲染到視圖上。

回答

0

在你繪製文件夾的同一水平,也應該有一些文件夾,這些名字:

-drawable,華電國際

-drawable-xhdpi

-drawable-xxhdpi

-drawable-xxxhdpi

您的圖片應根據不同的dpi進行縮放並放置在這些文件夾中以渲染更改在所有屏幕上都可以正常使用。

你可以做,而不是另一件事,就是:

// get drawable path 
    String imageUri = "drawable://" + R.drawable.image; 
    imageView.setImageBitmap(decodeSampledBitmapFromFile(imageUri , 1920, 1080)); 

與地方decodeSampledBitmapFromFile這樣的聲明:

public static Bitmap decodeSampledBitmapFromFile(String imagePath, 
                int reqWidth, int reqHeight) { 
    // BitmapFactory.decodeFile(this.getFilesDir().getPath() + "/" + imagestoplay[currImage]) 
    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    // BitmapFactory.decodeResource(res, resId, options); 
    BitmapFactory.decodeFile(imagePath, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(imagePath, options); 

} 

不要忘了改變1080年和1920年爲您所需的像素大小。