У меня есть html-файлы в активах с именем n0.html, n1.html и т. Д. Я хочу создать listview со ссылками на эти файлы, но я не знаю, как это сделать. У меня такое решение с необработанной папкой. Как мне изменить его на файлы активов?Как получить listview со ссылками на активы?
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, хочет изменить тип «е» в «String». Помогите мне пожалуйста. Я буду очень благодарен, если вы сможете помочь мне в моей борьбе.
Спасибо очень много, но как я должен изменить это: Bundle пучок = getIntent() getExtras();. String itemname = "n" + bundle.getString ("defStrID"); // получение строки и формирование имени ресурса Контекстный контекст = getBaseContext(); // получение контекста // чтение текстового файла из ресурсов по имени String text = readRawTextFile (контекст, getResources(). getIdentifier (itemname, "raw", "ru.falcon5f.carguide;")); – Sabre
Я отредактировал ваш фрагмент, надеюсь, это сделает его самым легким для вас. Я предполагаю, что вы создаете имя файла html из данного пакета. –
Так что я должен только изменить оставшийся код? – Sabre