2013-12-23 3 views
0

아무 것도없는 경우보기를 만드는 gridView의 baseadapter가 있습니다. 나는 것을 사용하는 것을 시도하고있다다른 클래스에서 imageView를 얻는 방법

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

을 :

@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; 
} 

당신이 내 값 섹션에서이 XML 레이아웃 파일을 기반으로 뷰에게 새로운 ID iconImageView_id 준 볼 수 있습니다 : 여기의 getView 부분이다

// 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입니다 : 다른 클래스의 이미지 뷰 나는 이런 식으로 비트 맵을 할당 할 수 있도록. 내가 분명히 단지 정적 뷰를 참조 할 수 없기 때문에

 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); 

ADDED :

여기

내가 처리하고있는이 개 전체 클래스입니다 :

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을하려고? 이 점에서 loking은 아마도 두 NEP가 가리키는보기 heirachies가 같지 않기 때문에 NPE를 얻고있을 것입니다. (I.E 그들은 각각 자신의 뷰를 생성하고, 전달 된 뷰는 어댑터를 통해 상관하지 않습니다).

당신이 정말 당신이 길하고 싶은 경우에, 당신은 다음을 수행하여 성공을 찾을 수 있습니다 :

는 루트 레이아웃을 정의 root.xml합니다. 당신의 MainActivity의 생성자에서

, 그래서 같이이보기를 infalte :

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

응용 프로그램 전반에 걸쳐 viewRoot에 대한 참조를 유지하고, 당신이 추가 한 전망이 부모 뷰를 사용한다 (또는이 부모 뷰에서 뷰)에 그들의 견해를 주최한다.

당신은 전화 할 때 : 나는 이렇게합니다 (NPE보기를 포함하지 않는 뷰 heiarchy의 pralell 섹션 중 하나에서 오는 의심 뷰 (전달 사용하는 대신

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

을))는 다음을 사용하십시오 :

viewRoot.findViewById(R.id.iconImageView_id); 

주문이 정확하면 (IE가 뷰가있는 곳에서 호출 됨) 이제는 액세스 권한이 있어야합니다.

+0

네가 설명해 주셔서 고맙습니다. 왜 지금 NPE를 얻었는지 이해가됩니다. 하지만 한 가지 질문은 "루트 레이아웃, root.xml을 정의"라고 말했을 때입니다. 이 XML 파일에 특정 내용이 있어야합니까? 아니면 그냥 비워 둘 수 있습니까? – user2909006

+0

또한 응용 프로그램 전체에 걸쳐 모든 클래스에서 root.xml을 부 풀리겠습니까? 아니면 단지 root.java 클래스를 부 풀리겠습니까? (당신이 여기서 의미하는 것을 설명 할 수 있다면, 나는 그것을 apperciate 것이다. 고마워!) – user2909006

+0

질문 1 : 그냥 거기에 선형 레이아웃을 넣어, 기본적으로 다른 모든보기를 개최거야. 질문 2 :이 레이아웃을 한 번 팽창시키고이 뷰에 추가 된 뷰가 있어야합니다. 이렇게하면 검색 할 최상위 요소가 제공됩니다. –

관련 문제