2012-05-02 40 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(); 

但它遭受與所有其他人一樣的問題。

a)(TextView)findViewById(R.id.hellotxt);表示折舊和Eclipses建議遷移代碼。

b)getResources()不被識別,只是建議我添加一個名爲getResources()的方法。

最初我想使用資產文件夾,但得到了與b)相同的錯誤,但與getAssets()。

這是一個單獨的類文件,我實現這個叫public class PassGen{}與所謂public String returnPass(){}

+0

上面的代碼工作在Android 2.3.3。 –

+0

如果在Activity類中,但不在單獨的附加類中,則會發生 – jskrwyk

+0

這是什麼意思?ad-on class –

回答

2

功能getAssets和getResources當下一個方法應該從上下文中調用。

如果您從一個Activity類中調用它,它不需要前綴,否則您需要將該上下文傳遞給需要該函數的類並調用例如context.getAssets()。

+0

那麼上下文會是什麼?我查了一下Android開發者網站,但它只是說它返回了AssetManager的摘要 – jskrwyk

+0

上下文文檔:http://developer.android.com/reference/android/content/Context.html 只要將'this'從活動類應該工作。 – Stuart

1

活動課:

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