Saturday, February 5, 2022

Android - Reading a txt file from asset and outputing as a TextView in Android

You want to keep a .txt file in your Project, you must locate it in the assets folder.

Then you can access it with AssetManger .

Read this topic on how to create your assets folder, and then use this code:


public class subActivity extends Activity {


private TextView textView;

private StringBuilder text = new StringBuilder();


protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.text);

    BufferedReader reader = null;


    try {

        reader = new BufferedReader(

            new InputStreamReader(getAssets().open("inputNews.txt")));


        // do reading, usually loop until end of file reading  

        String mLine;

        while ((mLine = reader.readLine()) != null) {

            text.append(mLine);

            text.append('\n');

        }

    } catch (IOException e) {

        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();

        e.printStackTrace();

    } finally {

        if (reader != null) {

        try {

            reader.close();

        } catch (IOException e) {

            //log the exception

        }

    }


    TextView output= (TextView) findViewById(R.id.summtext);

    output.setText((CharSequence) text);


 }

}

No comments:

Post a Comment