2017-06-22 123 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年为您所需的像素大小。