2017-12-21 23 views
1

このコードないエラーエラーのgetResource()別のクラスで

クラスmainActivity中:

cannot find symbol method getResources() 

コード:

public void printPhoto(int img) { 

     try { 
      Bitmap bmp = BitmapFactory.decodeResource(getResources(), 
        img); 
      if(bmp!=null){ 
       byte[] boleh = Utils.decodeBitmap(bmp); 
       mmOutputStream.write(PrinterCommands.ESC_ALIGN_CENTER); 
       printText(boleh); 
      }else{ 
       Log.e("Print Photo error", "the file isn't exists"); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.e("PrintTools", "the file isn't exists"); 
     } 

    } 

All of my function and method in another class. In my MainActivity just for button and listener. how to solve this. I am beginner in android studio. thanks

+0

フラグメントを使用していますか? – R2R

+1

getResources()を呼び出すにはコンテキストが必要です。 context.getResources()を呼び出す必要があります。 アクティビティはコンテキストなので、クラスへの参照を渡すことができます –

答えて

1

あなたはContextを渡す必要があります。

コード

public void printPhoto(Context ctx,int img) { 

    try { 
     Bitmap bmp = BitmapFactory.decodeResource(ctx.getResources(), 
       img); 

コール

printPhoto(YourActivityName.this, R.drawable.your_image); // For Activity 
printPhoto(getActivity(), R.drawable.your_image); // For Fragment 
+0

エラー:(308,36)エラー:囲むクラスではありません:MainActivity。私はprintPhoto(MainActivity.this、R.drawable.img)からこれを得ました。 –

+0

@IsaHerdyantoは 'printPhoto(this、R.drawable.img);'または 'printPhoto(getApplicationContext()、R.drawable.img);'を試してください。これがうまくいきたいです。 –

+0

メールを確認してください –

0

はあなたにあなたのMainActivityクラスカスタムクラスからContextを渡します。続行 -

public void printPhoto(Context context, int img) { 

    try { 
     Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), 
       img); 
     if(bmp!=null){ 
      byte[] boleh = Utils.decodeBitmap(bmp); 
      mmOutputStream.write(PrinterCommands.ESC_ALIGN_CENTER); 
      printText(boleh); 
     }else{ 
      Log.e("Print Photo error", "the file isn't exists"); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
     Log.e("PrintTools", "the file isn't exists"); 
    } 

} 

MainActivityから電話してください。

printPhoto(getApplicationContext(), R.drawable.img); 
関連する問題