-2

enter image description here 1. I cant get the hang on it how to use assets folder to view a text at click of list view on a different activity which has a textview

1this is the activity where i want to display the text

  • Your question is not clear. Do you want to read text file from 1st activity and pass that text to the another activity, then click specific listview item there and display that passed text in a text view ? – Dinith Rukshan Kumara Mar 17 '18 at 12:04
  • In my 1st activity there is listview items and on clicking that item the text from assest folder should be displayed on 2n activity that has textview to display text....... – Tapan Mehta Mar 18 '18 at 15:24
  • Read my answer in the question. It has all what you expected. – Dinith Rukshan Kumara Mar 18 '18 at 16:22

1 Answers1

0

Add below code to your activity OnCreate method

ListView lv = (ListView) findViewById(R.id.Listview1); // Reference to ListViev
TextView AssetText = (TextView) findViewById(R.id.textview1); // Reference to TextViev
ArrayList<String> listViewItems = new ArrayList<String>(); //Create a ArrayList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems); //Create ArrayAdapter
String filename = "Text file name" //Asset folder Textfile name

lv.setAdapter(adapter); //set adapter to listview
listViewItems.add("Read Asset Text"); //Add Item to ArrayList, to display in listview
adapter.notifyDataSetChanged();

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String lvItem = list.getAdapter().getItem(position).toString(); //getting clicked item as a string
                if(lvItem.matches("Read Asset Text")){ //check for matching specific item name
                    AssetText.setText(readAssetsText(getApplicationContext(),filename)); //call readAssetsText() method. You have to pass context & filename

                }

            }
        });

Create below method outside the OnCreate method. This method is to read Asset folder textfile and get text as a string.

public String readAssetsText(Context context, String filename) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
    StringBuilder sb = new StringBuilder();
    String mLine = br.readLine();

    while (mLine != null) {
        sb.append(mLine);
        mLine = br.readLine();
    }
    br.close();
    return sb.toString(); //return text file text as a string
}
Dinith Rukshan Kumara
  • 638
  • 2
  • 10
  • 19