从TXT文件中获取ArrayList

时间:2013-03-11 11:24:50

标签: android arraylist widget

的所有人。早上好。

这是一个Android小部件。我正在使用此代码。我只想将外部文件中的ArrayList作为.TXT(保存在assets文件夹中)而不是从java文件中获取引号列表。但是这段代码有问题。它没有读取“quote.txt文件夹”中的“assets”文件。

这是我的代码:

   public class UpdateWidgetService extends Service {
private static final String TAG = UpdateWidgetService.class.getSimpleName();

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    Log.d(TAG, "onStart started");

    // Create some random data
    Random random = new Random();

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());

    int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

    if (appWidgetIds.length > 0) {

        for (int widgetId : appWidgetIds) {
            List<String> qList = getListFromTxtFile("quote.txt");
            int nextInt = random.nextInt(qList.size());

            RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);
            remoteViews.setTextViewText(R.id.widget_textview, qList.get(nextInt));
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
        stopSelf();
    }
    super.onStart(intent, startId);
}

public List<String> getListFromTxtFile(String txtFileName){

//  File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
// File file = new File(sdcard,txtFileName);

AssetManager am = this.getAssets();

List<String> qList = new ArrayList<String>();

//Read text from file

try {
    InputStream is = am.open("quote.txt");
          //BufferedReader br = new BufferedReader(new FileReader(file));
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;

     // get data in text file line by line
    while ((line = br.readLine()) != null) {

       qList.add(line);
    }
}
catch (IOException e) {
    //You'll need to add proper error handling here
}
return qList;

}
}

2 个答案:

答案 0 :(得分:0)

尝试使用

   AssetFileDescriptor descriptor = getAssets().openFd("quote.txt");
   FileReader reader = new FileReader(descriptor.getFileDescriptor());

答案 1 :(得分:0)

我把这个代码放在哪里,Ics?在&#34;尝试{&#34;