0

みんな。こんにちは。

これはAndroidウィジェットです。私はこのコードを使用しています。Javaファイルから引用符のリストを取得するのではなく、外部ファイルから.TXTとしてArrayListを取得したかっただけです。

これは私のコードです:

   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;

}
}
4

1 に答える 1

0

このメソッドを使用して、Assets からテキスト ファイルを読み取り、リストを返します

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(txtFileName);
          //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;

}

于 2013-03-09T19:31:22.670 に答える