2013-02-16 155 views
1

我想從我的R.raw文件夾使用inputstream打開文件。但是,我總是得到這個錯誤:從R.raw文件夾打開文件

'The method getResources() is undefined for the type Wordchecker' 

,當我試圖用快速解決另一個錯誤appears.like這一個:

'The method openRawResource(int) is undefined for the type Object'... 

這裏是我的代碼:

public class Wordchecker { 
    public static void main(String arg[]){ 
     HashSet <String> newset = new HashSet <String>(); 
     try{ 
      //opening file of words 
      InputStream is = getResources().openRawResource(R.raw.wordlist); 
      DataInputStream in = new DataInputStream(is); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String strLine; 

      //reading file of words 
      while ((strLine = br.readLine()) != null) { 
       newset.add(strLine); //adding word to the hash set newset 
      } 
      in.close(); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    private static Object getResources() { 
     // TODO Auto-generated method stub 
     return null; 
    } 
} 

回答

0

你的問題這裏是你不擴展Activity。你可以不叫getResources(),因爲它不存在

沒有你不能使用getResources()Activity類,直到你過時了一個上下文參數

+0

謝謝你..我剛剛錯過了... @ Festus Tamakloe – kathy 2013-02-16 09:42:23

+0

@ user2078012不客氣。如果你喜歡我的回答就接受它。謝謝 – 2013-02-16 09:50:38

0

你需要有Context某處引用,如getResources()是一種方法在上下文中。

就拿它的一個實例在構造函數:

public class Wordchecker { 
    Context mContext; 

    public Wordchecker(Context c) { 
     mContext = c; 
     init() 
    } 

    public void init() { 
     HashSet <String> newset = new HashSet <String>(); 
     try{ 
      //opening file of words 
      InputStream is = getResources().openRawResource(R.raw.wordlist); 
      DataInputStream in = new DataInputStream(is); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String strLine; 
      //reading file of words 
      while ((strLine = br.readLine()) != null) { 
       newset.add(strLine); //adding word to the hash set newset 
      } 
      in.close(); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

,然後從使用擴展上下文的活動或服務或任何創建這個類的一個對象:

Wordchecker wordchecker = new Wordchecker(this); 

確保wordchecker = new Wordchecker(this);onCreate()或之後

+0

謝謝你的幫助,但是當我打電話給newset時,出現了一個錯誤..我只是想檢查我輸入的單詞是否包含在我的hashset(newset)中..謝謝.. @ Raghav Sood – kathy 2013-02-16 09:51:29