Hello. I have a question. How to call an Activity by clicking on one of the options from the ListView , and so that on the second Activity shows the text from the res/raw folder In one article it was written that you can do this:

 private String Iv_ar[]={ "1. Text1",//n0 "2. Text2",//n1 "3. Text3",//n2 "4. Text4" //n7 }; 

But there was no complete code and no explanation at all. Then in the res/raw folder. Create files in .txt or .html format. With the names n0.txt, n1.txt, n2.txt, n7.txt. When you click on one of the options, the text from these files opens.

Tell me how to implement this? Desirable answer with explanations.

    1 answer 1

    The question is very general and voluminous, but approximately it will look like this:

    1. Add a click handler for ListView , get a position in it, pack it into the Internet and launch a new activation:

       mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("POSITION_KEY", position); startActivity(intent); }); 
    2. In the second activation you get the position:

       int position; Intent intent = getIntent(); if (intent != null) { position = intent.getIntExtra("POSITION_KEY", -1); } 
    3. Depending on the position, read the desired file:

        String content; switch (position) { case 1: content = loadStringFromRawResource(getResources(), R.raw.file_1); break; case 2: content = loadStringFromRawResource(getResources(), R.raw.file_2); break; case 3: content = loadStringFromRawResource(getResources(), R.raw.file_3); break; default: content = "Empty content"; break; } 

    Code methods for reading:

     private static String loadStringFromRawResource(Resources resources, int resId) { InputStream inputStream = resources.openRawResource(resId); String content = streamToString(inputStream); try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return content; } private static String streamToString(InputStream inputStream) { String line; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); try { while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } 
    • I apologize in advance. I am still new to this field. And all these codes where to enter? - akmaltilloev
    • @akmaltilloev, First - in onCreate , in which ListView is located. The second and third - in the second activation. Methods for reading can be distinguished in the utility class. - post_zeew