Как получить просмотр списка со ссылками на ресурсы? - PullRequest
0 голосов
/ 19 февраля 2012

У меня есть html-файлы в ресурсах с именами n0.html, n1.html и т. Д. Я хочу создать просмотр списка со ссылками на эти файлы, но я не знаю, как это сделать. У меня есть такое решение с необработанной папкой. Как мне изменить его на файлы ресурсов?

public class ViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.view);


        Bundle bundle = getIntent().getExtras();

        String itemname = "n" + bundle.getString("defStrID"); //getting string and forming resource name

        Context context = getBaseContext(); //getting context

        //reading text file from resources by name
        String text = readRawTextFile(context, getResources().getIdentifier(itemname, "raw", "ru.falcon5f.carguide;"));

        WebView wWebView = (WebView) findViewById(R.id.webView);
        String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
        wWebView.loadData(summary, "text/html", "utf-8"); //uploading text to webview
    }

    public static String readRawTextFile(Context ctx, int resId) //reading text raw txt file
    {
         InputStream inputStream = ctx.getResources().openRawResource(resId);

            InputStreamReader inputreader = new InputStreamReader(inputStream);
            BufferedReader buffreader = new BufferedReader(inputreader);
             String line;
             StringBuilder text = new StringBuilder();

             try {
               while (( line = buffreader.readLine()) != null) {
                   text.append(line);
                   text.append('\n');
                 }
           } catch (IOException e) {
               return null;
           }
             return text.toString();
    }
}

Добавлена ​​ Извините, если я задаю слишком глупые вопросы и задаю слишком много, но я хочу обработать свое первое заявление. Это очень важно для меня. Итак, он состоит из двух действий:

ViewActivity , который я изменил по вашим советам

public class ViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.view);


        Bundle bundle = getIntent().getExtras();

        String htmlFileName = "n" + bundle.getString("defStrID"); //getting file name 
        Context context = getBaseContext(); //getting context. You still need that

        //reading text file from resources by name
        try {
            String text = readAssetTextFile(context, htmlFileName);

            WebView wWebView = (WebView) findViewById(R.id.webView);
            String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
            wWebView.loadData(summary, "text/html", "utf-8"); //uploading text to webview
        } catch (IOException e) {
            Log.e("TAG", e); // note that you will need to import android.util.Log
        }
    }

    public static String readAssetTextFile(Context ctx, String fileName) throws IOException //reading html file from assets
    {
         InputStream inputStream = ctx.getAssets().open(fileName);

     InputStreamReader inputreader = new InputStreamReader(inputStream);
     BufferedReader buffreader = new BufferedReader(inputreader);
      String line;
      StringBuilder text = new StringBuilder();

      try {
        while (( line = buffreader.readLine()) != null) {
            text.append(line);
            text.append('\n');
          }
    } catch (IOException e) {
        return null;
    }
      return text.toString();
}
}

В Log.e("TAG", e); Eclipse хочет изменить тип "e" на "String". Помоги мне, пожалуйста. Я буду очень признателен, если вы сможете помочь мне в моей борьбе.

1 Ответ

1 голос
/ 19 февраля 2012

Это не будет так сильно отличаться. Теперь вы можете получить доступ к файлу в активах следующим образом: InputStream inputStream = ctx.getAssets().open(fileName);

Вы можете разместить это вместо вашей линии InputStream inputStream = ctx.getResources().openRawResource(resId);. Тогда вам нужно передать правильное имя файла. При работе с активами вам не нужно использовать идентификаторы.

РЕДАКТИРОВАТЬ Редактирование вашего фрагмента:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.view);


    Bundle bundle = getIntent().getExtras();

    String htmlFileName = "n" + bundle.getString("defStrID") + ".html"; //getting file name 
    Context context = getBaseContext(); //getting context. You still need that

    //reading text file from resources by name
    try {
        String text = readAssetTextFile(context, htmlFileName);

        WebView wWebView = (WebView) findViewById(R.id.webView);
        String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
        wWebView.loadData(summary, "text/html", "utf-8"); //uploading text to webview
    } catch (IOException e) {
        Log.e("TAG", "Exception thrown", e); // note that you will need to import android.util.Log
    }
}

public static String readAssetTextFile(Context ctx, String fileName) //reading html file from assets
{
     InputStream inputStream = ctx.getAssets().open(fileName);
     .....
...