我正在尝试编写一个遍历文本文件的类,它看起来像这样(大约5000行):

Postnr  Poststad    Bruksområde Kommunenummer   Lat Lon Merknad Nynorsk Bokmål  Engelsk
0001    Oslo    Postboksar  301 59.91160    10.75450    Datakvalitet: 2. Koordinatar endra 28.09.2012. Oppdatert 04.12.2012 url1    url2    url3


我的麻烦是:对于类型SearchTabTxt,getassets方法未定义

我正在尝试从资产文件夹中读取文件,但似乎找不到解决方案。我试图为此编写一个搜索类:

public class SearchTabTxt extends AsyncTask<String, Void, ArrayList<String[]>> {

    protected ArrayList<String[]> doInBackground(String... inputString) {
        ArrayList<String[]> list = new ArrayList<String[]>();
        try {
            InputStream is = getAssets().open("file.txt");
            if (is != null) {
                String search = inputString[0].toString();
                InputStreamReader inputreader = new InputStreamReader(is,
                        "UTF-8");
                BufferedReader buffreader = new BufferedReader(inputreader);
                int antallTreff = 0;

                while (buffreader.readLine() != null) {
                    ArrayList<String> placeInformation = new ArrayList<String>();
                    if (buffreader.readLine().contains(search)) {
                        antallTreff++;
                        System.out.println("Found: " + search);
                        placeInformation.clear();
                        for (String i : buffreader.readLine().split("\t")) {
                            placeInformation.add(i);
                        }
                        System.out.println(placeInformation.get(11));
                        // Sorry about the Norwegian will rewrite
                        if (antallTreff >= 3) {
                            System.out.println("Did I find something?");
                            break;
                        }
                        if (buffreader.readLine() == null) {
                            break;
                        }
                    }

                }

            }

        } catch (ParseException e) {
            Log.e("Error", e + "");

        } catch (ClientProtocolException e) {
            Log.e("Error", e + "");

        } catch (IOException e) {
            Log.e("Error", e + "");

        }
        return list;
    }
}

最佳答案

好吧,这很简单。 SearchTabTxt类中没有方法getAssets()。要获取资产,您需要一个上下文。为您的SearchTabTxt类创建一个公共构造函数,并传递一个Context。

private Context context;
public SearchTabTxt (Context myContext) {
    this.context = myContext;
}


现在,在doINbackground方法中,您可以执行以下操作:

InputStream is = context.getAssets().open("file.txt");


现在,在创建AsyncTask的活动中,您可以像这样启动任务:new SearchTabTxt(this).execute(params);之所以有效,是因为您的活动(此)是上下文的子类型。
有关更多信息,请参见:getAssets(); from another class

10-07 19:19
查看更多