2012-05-02 4 views
0

私はres/rawからテキストファイルをロードしようとしています。いくつかのコードスニペットを見て、いくつかの方法を実装しようとしましたが、私にとってはうまくいくものはありません。私は現在、仕事に取得しようとしていたコードは、このAndroidロードファイルResエラーから

TextView helloTxt = (TextView)findViewById(R.id.hellotxt); 
     helloTxt.setText(readTxt()); 
    } 

    private String readTxt() { 

    InputStream inputStream = getResources().openRawResource(R.raw.hello); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    int i; 
    try { 
     i = inputStream.read(); 
     while (i != -1) { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 
    } 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return byteArrayOutputStream.toString(); 

ですが、他のすべてがそうであるように、それは、TEと同じ問題を抱えています。

a)(TextView)findViewById(R.id.hellotxt);は減価償却し、Eclipsesはコードの移行を推奨しています。

b)getResources()は認識されず、getResources()というメソッドを追加することを提案します。

最初はassetsフォルダを使用したかったのですが、b)と同じエラーが発生しましたが、getAssets()を使用しました。

これは、コンテキストから呼び出されるべきpublic String returnPass(){}

+0

は、Android 2.3.3に取り組んでいます。 –

+0

アクティビティクラスではありますが、別のアドオンクラスではありません – jskrwyk

+0

アドオンクラスとはどういう意味ですか? –

答えて

2

機能getAssetsとgetResourcesと呼ばれる現時点での一つの方法とpublic class PassGen{}と呼ばれ、私はこれを実装してい別々のクラスファイルです。

アクティビティクラス内から呼び出す場合は、プレフィックスは必要ありませんが、そうでない場合は、関数を必要とするクラスにコンテキストを渡して、たとえば呼び出します。 context.getAssets()。

+0

だから文脈はどうだろう? Androidデベロッパーサイトを探しましたが、AssetManager – jskrwyk

+0

コンテキストドキュメントの要約が返ってくるだけです: 「this」をアクティビティクラスは動作するはずです。 – Stuart

1

Activityクラス:

public class ReadFileActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Read read = new Read(getApplicationContext()); 

    TextView helloTxt = (TextView) findViewById(R.id.hellotxt); 
    helloTxt.setText(read.readTxt()); 
} 
} 

読むクラス:上記のコード

public class Read { 

Context ctx; 

public Read(Context applicationContext) { 
    // TODO Auto-generated constructor stub 

    this.ctx = applicationContext; 
} 


public String readTxt() { 

    InputStream inputStream = ctx.getResources().openRawResource(R.raw.hello); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    int i; 
    try { 
     i = inputStream.read(); 
     while (i != -1) { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return byteArrayOutputStream.toString(); 
} 
} 
関連する問題