2013-12-23 73 views
0

我有一個gridView的baseadapter,它在沒有時創建一個視圖。這裏是getView部分:如何從另一個類獲取imageView

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // Try to reuse the views 
    ImageView view = (ImageView) convertView; 
    boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked()); 
    // if convert view is null then create a new instance else reuse it 
    if (view == null) { 
     view = new ImageView(Context); 
     Log.d("GridViewAdapter", "new imageView added"); 
     view.setId(R.id.iconImageView_id); 
    } 
    if(checked == true){ 
     isSdReadable(); 
     Log.i("GridViewAdapter", "checkbox is checked"); 
    } else { 
     Log.i("GridView", "Icons not for use/checkbox not checked"); 
    } 
    view.setImageResource(drawables.get(position)); 
    view.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70)); 
    view.setTag(String.valueOf(position)); 
    return view; 
} 

,你可以看到,我給視圖的新ID iconImageView_id基於在我的價值觀節這個XML佈局文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<item type="id" name="iconImageView_id"/> 
</resources> 

我試圖使用imageView在另一個類,以便我可以像這樣分配一個位圖:

// Load back the image file to confirms it works 
          Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); 
          ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id); 
          imageView1.setImageBitmap(bitmap); 
          Log.i("AppInfoAdapter", "The icon image has been set into the gridView"); 
         } 

但其他類也是baseadapter。

這裏就是我試圖使用的ImageView類的全斷面:

 Log.d("AppInfoAdapter", "Data Set To Display"); 
    addCheckbox 
      .setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        if (addCheckbox.isChecked()) { 
         System.out.println("Checked"); 

         PackageManager pm = mContext.getPackageManager(); 
         final int DEST_IMAGE_WIDTH = 100; 
         final int DEST_IMAGE_HEIGHT = 100; 
         ApplicationInfo appInfo = mContext.getApplicationInfo(); 
         Drawable appIcon = pm.getApplicationIcon(appInfo); 
         Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888); 

         // Creates a new canvas based on the image specification 
         // created just above. 
         Canvas canvas = new Canvas(appBmp); 
         // (optional) Fills the entire canvas 
         canvas.drawColor(Color.WHITE); 
         // You need to set bounds otherwise a 0,0 sized image would be drawn. 
         appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT); 
         appIcon.draw(canvas); 

         /// Let's save to a .jpg file ... 
         File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg"); 
         FileOutputStream out; 
         try 
         { 
          file.createNewFile(); 
          out = new FileOutputStream(file); 
          appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out); 
          Log.i("AppInfoAdapter", "The icon for use in gridView is saved"); 
          out.close(); 

          // Load back the image file to confirms it works 
          Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); 
          ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id); 
          imageView1.setImageBitmap(bitmap); 
          Log.i("AppInfoAdapter", "The icon image has been set into the gridView"); 
         } 

         catch (FileNotFoundException e1) 
         { 
          e1.printStackTrace(); 
         } 
         catch (IOException e2) 
         { 
          e2.printStackTrace(); 
         } 


        } else { 
         System.out.println("Un-Checked"); 
        } 

       } 
      }); 

    // return view 
    return v; 
} 

所以我得到了NPE,因爲我顯然不能只是靜態地引用視圖。

那麼我怎樣才能讓它在我的其他課程中使用該imageView?

這裏是堆棧跟蹤錯誤:

FATAL EXCEPTION: main 
12-22 15:58:45.782: E/AndroidRuntime(28793): java.lang.NullPointerException 
12-22 15:58:45.782: E/AndroidRuntime(28793): at com.example.awesomefilebuilderwidget.AppInfoAdapter$1.onClick(AppInfoAdapter.java:200) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.view.View.performClick(View.java:2532) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.widget.CompoundButton.performClick(CompoundButton.java:99) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.view.View$PerformClick.run(View.java:9308) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.os.Handler.handleCallback(Handler.java:587) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.os.Handler.dispatchMessage (Handler.java:92) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.os.Looper.loop(Looper.java:150) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at android.app.ActivityThread.main(ActivityThread.java:4333) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at java.lang.reflect.Method.invokeNative(Native Method) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at java.lang.reflect.Method.invoke(Method.java:507) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
12-22 15:58:45.782: E/AndroidRuntime(28793): at dalvik.system.NativeStart.main(Native Method) 

與線200之中:

imageView1.setImageBitmap(bitmap); 

新增:

下面是我處理了兩個完整類:

AppInfoAdapter.java:

package com.example.awesomefilebuilderwidget; 

IMPORTS 

public class AppInfoAdapter extends BaseAdapter implements Filterable { 
private Context mContext; 
private List<ResolveInfo> mListAppInfo; 
private PackageManager mPackManager; 
private List<ResolveInfo> originalListAppInfo; 
private Filter filter; 
private String fname; 

public AppInfoAdapter(Context c, List<ResolveInfo> listApp, 
     PackageManager pm) { 
    mContext = c; 
    this.originalListAppInfo = this.mListAppInfo = listApp; 
    mPackManager = pm; 
    Log.d("AppInfoAdapter", "top"); 
} 

@Override 
public int getCount() { 
    Log.d("AppInfoAdapter", "getCount()"); 
    return mListAppInfo.size(); 
} 

@Override 
public Object getItem(int position) { 
    Log.d("AppInfoAdapter", "getItem"); 
    return mListAppInfo.get(position); 
} 

@Override 
public long getItemId(int position) { 
    Log.d("AppInfoAdapter", "getItemId"); 
    return position; 
} 

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 
    // get the selected entry 
    final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position); 

    // reference to convertView 
    View v = convertView; 

    // inflate new layout if null 
    if (v == null) { 
     LayoutInflater inflater = LayoutInflater.from(mContext); 
     v = inflater.inflate(R.layout.layout_appinfo, null); 
     Log.d("AppInfoAdapter", "New layout inflated"); 
    } 

    // load controls from layout resources 
    ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon); 
    TextView tvAppName = (TextView) v.findViewById(R.id.tvName); 
    TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack); 
    final CheckBox addCheckbox = (CheckBox) v 
      .findViewById(R.id.addCheckbox); 
    Log.d("AppInfoAdapter", "Controls from layout Resources Loaded"); 

    // set data to display 
    ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager)); 
    tvAppName.setText(entry.activityInfo.loadLabel(mPackManager)); 
    tvPkgName.setText(entry.activityInfo.packageName); 

    Log.d("AppInfoAdapter", "Data Set To Display"); 
    addCheckbox 
      .setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        if (addCheckbox.isChecked()) { 
         System.out.println("Checked"); 

         PackageManager pm = mContext.getPackageManager(); 
         final int DEST_IMAGE_WIDTH = 100; 
         final int DEST_IMAGE_HEIGHT = 100; 
         ApplicationInfo appInfo = mContext.getApplicationInfo(); 
         Drawable appIcon = pm.getApplicationIcon(appInfo); 
         Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888); 

         // Creates a new canvas based on the image specification 
         // created just above. 
         Canvas canvas = new Canvas(appBmp); 
         // (optional) Fills the entire canvas 
         canvas.drawColor(Color.WHITE); 
         // You need to set bounds otherwise a 0,0 sized image would be drawn. 
         appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT); 
         appIcon.draw(canvas); 

         /// Let's save to a .jpg file ... 
         File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg"); 
         FileOutputStream out; 
         try 
         { 
          file.createNewFile(); 
          out = new FileOutputStream(file); 
          appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out); 
          Log.i("AppInfoAdapter", "The icon for use in gridView is saved"); 
          out.close(); 

          // Load back the image file to confirms it works 
          Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); 
          ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id); 
          imageView1.setImageBitmap(bitmap); 
          Log.i("AppInfoAdapter", "The icon image has been set into the gridView"); 
         } 

         catch (FileNotFoundException e1) 
         { 
          e1.printStackTrace(); 
         } 
         catch (IOException e2) 
         { 
          e2.printStackTrace(); 
         } 


        } else { 
         System.out.println("Un-Checked"); 
        } 

       } 
      }); 

    // return view 
    return v; 
} 

和GridViewAdapter.java:

package com.example.awesomefilebuilderwidget; 

IMPORTS 

public class GridViewAdapter extends BaseAdapter { 
private Context Context; 

// Keep all Images in array list 
public ArrayList<Integer> drawables = new ArrayList<Integer>(); 

CheckBox mCheckBox=null; 

// Constructor 
public GridViewAdapter(Context c){ 
    Context = c; 
    Log.d("GridViewAdapter", "Constructor is set"); 

    drawables.add(R.drawable.pattern1); 
    Log.d("GridViewAdapter", "pattern1 added"); 

    drawables.add(R.drawable.pattern2); 
    Log.d("GridViewAdapter", "pattern2 added"); 

    drawables.add(R.drawable.trashcan); 
    Log.d("GridViewAdapter", "trashcan added"); 

    drawables.add(R.drawable.ic_launcher); 
    Log.d("GridViewAdapter", "ic_launcher added"); 
} 

public void setCheckBox(CheckBox checkbox){ 
    mCheckBox=checkbox; 
} 

@Override 
// How many items are in the data set represented by this Adapter 
public int getCount() { 
    return drawables.size(); 
} 

@Override 
// Get the data item associated with the specified position in the 
// data set 
public Object getItem(int position) { 
    return drawables.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

public boolean isSdReadable() { 

    boolean mExternalStorageAvailable = false; 
    String state = Environment.getExternalStorageState(); 

    if (Environment.MEDIA_MOUNTED.equals(state)) { 
    // We can read and write the media 
    mExternalStorageAvailable = true; 
    Log.i("isSdReadable", "External storage card is readable."); 
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
    // We can only read the media 
    Log.i("isSdReadable", "External storage card is readable."); 
    mExternalStorageAvailable = true; 
    } else { 
    // Something else is wrong. It may be one of many other 
    // states, but all we need to know is we can neither read nor write 
    mExternalStorageAvailable = false; 
    } 

    return mExternalStorageAvailable; 
    } 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // Try to reuse the views 
    ImageView view = (ImageView) convertView; 
    boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked()); 
    // if convert view is null then create a new instance else reuse it 
    if (view == null) { 
     view = new ImageView(Context); 
     Log.d("GridViewAdapter", "new imageView added"); 
     view.setId(R.id.iconImageView_id); 
    } 
    if(checked == true){ 
     isSdReadable(); 
     Log.i("GridViewAdapter", "checkbox is checked"); 
    } else { 
     Log.i("GridView", "Icons not for use/checkbox not checked"); 
    } 
    view.setImageResource(drawables.get(position)); 
    view.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70)); 
    view.setTag(String.valueOf(position)); 
    return view; 
} 

} 
+0

請發佈完整的堆棧跟蹤。 –

+0

同時發佈包含此圖像視圖佈局的LayoutFile ...我不認爲該資源文件是vlid佈局定義。 –

+0

我發佈了堆棧跟蹤。此imageView在xml中沒有佈局文件,它在GridView適配器的getView部分中創建(如果沒有視圖) – user2909006

回答

1

你怎麼想兩個adapaters在一起嗎?只是嘲笑你可能會得到那個NPE,因爲這兩個適配器指向的視圖不一樣。 (I.E他們各自產生自己的觀點,並且傳遞的觀點在適配器之間不相關)。

如果你真的想這樣做,你的方式,那麼你可能會發現通過執行以下操作的成功:

定義根佈局,的ROOT.xml。

在您的MainActivity構造,infalte這種觀點就像這樣:

ViewGroup viewRoot = LayoutInfalter.from(this).inflate(R.layout.xml); 
setContentView(viewRoot); 

保持整個應用程序中引用的viewRoot,並添加任何看法應該使用這個父視圖(或該父視圖中查看)到主持他們的觀點。

當你召喚:

ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id); 

,而不是使用視圖(我懷疑是從任一角度heiarchy的pralell部分不包含您的視圖(因此NPE來傳遞作爲你的排序是正確的(IE認爲存在於這個被稱爲點),你現在應該有機會只要

viewRoot.findViewById(R.id.iconImageView_id); 

:))使用。

+0

好的,謝謝你的解釋,現在我明白爲什麼要得到NPE。有一個問題,當你說「定義根佈局,root.xml」。在這個xml文件中是否必須有任何特定的內容,或者我可以將它留空? – user2909006

+0

還有,我會誇大整個應用程序中的所有類的root.xml文件,還是隻是特別誇大類root.java? (如果你可以解釋你在這裏的意思,我會勸解它的,謝謝!) – user2909006

+0

問題1:只需將線性佈局放在那裏,它基本上只是容納所有其他視圖。 問題2:一次膨脹此佈局,並將任何視圖添加到此視圖中。這給你一個頂級的元素來搜索。 –

相關問題