How to Read Felder & Solomon Index
Read text file !!! How to read text file in android app? Some fourth dimension developer think that it is very difficult to read text file in android, just truth is – information technology is very like shooting fish in a barrel. You can read any text file and excel canvas from android app whether file located in internal storage or external storage. If you want to know how to read excel file from nugget binder, please read this tutorial.
To read any file from android app, y'all must take permission to read external storage. otherwise app will crash at run time. In this tutorial, I am going to show yous, how to select text file from gallery OR internal storage OR external storage and read text file. I am using a uncomplicated textview to display the text written on selected text file.
And so in this tutorial the procedure is as follow. Offset I am writing the code for run time permission, and then code for select file from gallery then read the text written in text file. If you lot desire work with PDF file than you can read this tutorial – How to create PDF file, write text and epitome
How to Read Text file in android
Login & Download the Code
Footstep by Step Process
- Add run time permission in Androidmanifest.xml
- MainActivity.coffee run time permission lawmaking
- Add select file from gallery or file director
- Get actual file path from file URI
- Read file using bufferreader
- Run the lawmaking
Add together run time permission
Start, add run time permission in androidmanifest.xml file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="blueappsoftware.readtextfile"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="truthful" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@manner/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.Principal" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
action-main.xml
<?xml version="1.0" encoding="utf-eight"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="blueappsoftware.readtextfile.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/text2" android:textColor="@colour/colorAccent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.back up.constraint.ConstraintLayout>
MainActivity.java run time permission code
Considering we are trying to read text file from telephone storage, then you must add the code for run time permission in android app. Android introduce run time permission in api 24 marshmallow. So commencement check user phone'due south android version is greater than or equal to marshmallow.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ // offset runtime permission Boolean hasPermission =( ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermission){ Log.e(TAG, "get permision "); ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, request_code); }else { Log.e(TAG, "get permision-- already granted "); showFileChooser(); } }else { //readfile(); showFileChooser(); }
If android version is greater than marshmallow than user volition run across a alert dialog to accept permission to read text file. One time user will click on allow/ denied button the response volition be received in onRequestPermissionsResult() method. There if it is positive response (means allow) than you should get-go function to choose file from gallery, otherwise evidence fault massage to user.
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode){ case one:{ if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){ //readfile(); showFileChooser(); }else { // show a msg to user } } } }
Select file from gallery
It is the best style to give complete control to user to select whatsoever file from the gallery. You lot have to apply intent to open gallery option. The response of the intent volition exist receive in onActivityResult() method. The onActivityResult will return the intent data.
Notation- you can merely get the URI of the file using intent, not the bodily file path. to get the actual file path, you accept to write different functions. Actually the URI is a alphabetize of file not the exact path. The text file can exist located into any binder, so we demand to write multiple condition to get file path. below is the table of URI path according to binder location.
URI: content://media/external/images/media/1701 select file from photographic camera binder -- /external/images/media/1701 auth media select from screenshot folder -- /certificate/image:1760 auth com.android.providers.media.documents // download folder /document/1899 auth com.android.providers.downloads.documents // external storage folder ---- /external/images/media/2372 auth com.android.externalstorage.documents
Get actual file path from URI
You must check auth of each file. auth is parent binder name, using this proper name you can identify which condition will exist correct to get file path.
beneath is the lawmaking to go actual file path from gallery file. Please watch the above video to empathize why you must check multiple condition to get file path.
@Override protected void onActivityResult(int requestCode, int resultCode, Intent information) { super.onActivityResult(requestCode, resultCode, data); // Log.due east(TAG, " upshot is "+ information + " uri "+ data.getData()+ " auth "+ data.getData().getAuthority()+ " path "+ data.getData().getPath()); String fullerror =""; if (requestCode == FILE_SELECT_CODE){ if (resultCode == RESULT_OK){ try { Uri imageuri = data.getData(); InputStream stream = null; String tempID= "", id =""; Uri uri = information.getData(); Log.eastward(TAG, "file auth is "+uri.getAuthority()); fullerror = fullerror +"file auth is "+uri.getAuthority(); if (imageuri.getAuthority().equals("media")){ tempID = imageuri.toString(); tempID = tempID.substring(tempID.lastIndexOf("/")+1); id = tempID; Uri contenturi = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String selector = MediaStore.Images.Media._ID+"=?"; actualfilepath = getColunmData( contenturi, selector, new String[]{id} ); }else if (imageuri.getAuthority().equals("com.android.providers.media.documents")){ tempID = DocumentsContract.getDocumentId(imageuri); String[] split = tempID.split(":"); String type = split[0]; id = split[i]; Uri contenturi = zilch; if (type.equals("image")){ contenturi = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; }else if (blazon.equals("video")){ contenturi = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; }else if (type.equals("audio")){ contenturi = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } Cord selector = "_id=?"; actualfilepath = getColunmData( contenturi, selector, new String[]{id} ); } else if (imageuri.getAuthority().equals("com.android.providers.downloads.documents")){ tempID = imageuri.toString(); tempID = tempID.substring(tempID.lastIndexOf("/")+1); id = tempID; Uri contenturi = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); // String selector = MediaStore.Images.Media._ID+"=?"; actualfilepath = getColunmData( contenturi, zero, zippo ); }else if (imageuri.getAuthority().equals("com.android.externalstorage.documents")){ tempID = DocumentsContract.getDocumentId(imageuri); Cord[] split = tempID.split(":"); String type = split[0]; id = split[1]; Uri contenturi = nix; if (type.equals("primary")){ actualfilepath= Environment.getExternalStorageDirectory()+"/"+id; } } File myFile = new File(actualfilepath); // MessageDialog dialog = new MessageDialog(Home.this, " file details --"+actualfilepath+"\n---"+ uri.getPath() ); // dialog.displayMessageShow(); Cord temppath = uri.getPath(); if (temppath.contains("//")){ temppath = temppath.substring(temppath.indexOf("//")+1); } Log.eastward(TAG, " temppath is "+ temppath); fullerror = fullerror +"\northward"+" file details - "+actualfilepath+"\due north --"+ uri.getPath()+"\n--"+temppath; if ( actualfilepath.equals("") || actualfilepath.equals(" ")) { myFile = new File(temppath); }else { myFile = new File(actualfilepath); } //File file = new File(actualfilepath); //Log.e(TAG, " bodily file path is "+ actualfilepath + " name ---"+ file.getName()); // File myFile = new File(actualfilepath); Log.e(TAG, " myfile is "+ myFile.getAbsolutePath()); readfile(myFile); // lyf path - /storage/emulated/0/kolektap/04-06-2018_Admin_1528088466207_file.xls } catch (Exception due east) { Log.e(TAG, " read errro "+ e.toString()); } //------------ /document/main:kolektap/30-05-2018_Admin_1527671367030_file.xls } } } public String getColunmData( Uri uri, String selection, String[] selectarg){ Cord filepath =""; Cursor cursor = cipher; String colunm = "_data"; Cord[] projection = {colunm}; cursor = getContentResolver().query( uri, projection, option, selectarg, zero); if (cursor!= null){ cursor.moveToFirst(); Log.e(TAG, " file path is "+ cursor.getString(cursor.getColumnIndex(colunm))); filepath = cursor.getString(cursor.getColumnIndex(colunm)); } if (cursor!= null) cursor.close(); return filepath; }
Read text file in android
Now you have file path, use this file path to read file using buffer reader. below is the consummate code of MainActivity.java
packet blueappsoftware.readtextfile; import android.Manifest; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.internet.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.back up.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Package; import android.util.Log; import android.widget.TextView; import coffee.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private int request_code =i, FILE_SELECT_CODE =101; private TextView textView; private Cord TAG ="mainactivty"; public String actualfilepath=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // sdcard/myfolder/mytextfile.txt //URI sdcard/media/123242 textView =(TextView) findViewById(R.id.text2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ // outset runtime permission Boolean hasPermission =( ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermission){ Log.due east(TAG, "get permision "); ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, request_code); }else { Log.due east(TAG, "get permision-- already granted "); showFileChooser(); } }else { //readfile(); showFileChooser(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode){ instance 1:{ if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){ //readfile(); showFileChooser(); }else { // show a msg to user } } } } private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); endeavour { startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); } take hold of (Exception due east) { Log.e(TAG, " cull file fault "+e.toString()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, information); // Log.e(TAG, " result is "+ data + " uri "+ data.getData()+ " auth "+ data.getData().getAuthority()+ " path "+ data.getData().getPath()); String fullerror =""; if (requestCode == FILE_SELECT_CODE){ if (resultCode == RESULT_OK){ endeavor { Uri imageuri = data.getData(); InputStream stream = aught; Cord tempID= "", id =""; Uri uri = information.getData(); Log.e(TAG, "file auth is "+uri.getAuthority()); fullerror = fullerror +"file auth is "+uri.getAuthority(); if (imageuri.getAuthority().equals("media")){ tempID = imageuri.toString(); tempID = tempID.substring(tempID.lastIndexOf("/")+1); id = tempID; Uri contenturi = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; Cord selector = MediaStore.Images.Media._ID+"=?"; actualfilepath = getColunmData( contenturi, selector, new String[]{id} ); }else if (imageuri.getAuthority().equals("com.android.providers.media.documents")){ tempID = DocumentsContract.getDocumentId(imageuri); Cord[] separate = tempID.split up(":"); String type = split[0]; id = carve up[one]; Uri contenturi = null; if (type.equals("image")){ contenturi = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; }else if (type.equals("video")){ contenturi = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; }else if (blazon.equals("sound")){ contenturi = MediaStore.Sound.Media.EXTERNAL_CONTENT_URI; } String selector = "_id=?"; actualfilepath = getColunmData( contenturi, selector, new String[]{id} ); } else if (imageuri.getAuthority().equals("com.android.providers.downloads.documents")){ tempID = imageuri.toString(); tempID = tempID.substring(tempID.lastIndexOf("/")+one); id = tempID; Uri contenturi = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); // String selector = MediaStore.Images.Media._ID+"=?"; actualfilepath = getColunmData( contenturi, null, zippo ); }else if (imageuri.getAuthority().equals("com.android.externalstorage.documents")){ tempID = DocumentsContract.getDocumentId(imageuri); String[] split = tempID.split(":"); Cord blazon = dissever[0]; id = split[1]; Uri contenturi = null; if (type.equals("principal")){ actualfilepath= Surroundings.getExternalStorageDirectory()+"/"+id; } } File myFile = new File(actualfilepath); // MessageDialog dialog = new MessageDialog(Home.this, " file details --"+actualfilepath+"\n---"+ uri.getPath() ); // dialog.displayMessageShow(); String temppath = uri.getPath(); if (temppath.contains("//")){ temppath = temppath.substring(temppath.indexOf("//")+one); } Log.e(TAG, " temppath is "+ temppath); fullerror = fullerror +"\n"+" file details - "+actualfilepath+"\n --"+ uri.getPath()+"\due north--"+temppath; if ( actualfilepath.equals("") || actualfilepath.equals(" ")) { myFile = new File(temppath); }else { myFile = new File(actualfilepath); } //File file = new File(actualfilepath); //Log.e(TAG, " actual file path is "+ actualfilepath + " proper noun ---"+ file.getName()); // File myFile = new File(actualfilepath); Log.e(TAG, " myfile is "+ myFile.getAbsolutePath()); readfile(myFile); // lyf path - /storage/emulated/0/kolektap/04-06-2018_Admin_1528088466207_file.xls } grab (Exception e) { Log.e(TAG, " read errro "+ east.toString()); } //------------ /document/chief:kolektap/30-05-2018_Admin_1527671367030_file.xls } } } public Cord getColunmData( Uri uri, String selection, String[] selectarg){ String filepath =""; Cursor cursor = zippo; String colunm = "_data"; String[] projection = {colunm}; cursor = getContentResolver().query( uri, projection, option, selectarg, null); if (cursor!= cypher){ cursor.moveToFirst(); Log.e(TAG, " file path is "+ cursor.getString(cursor.getColumnIndex(colunm))); filepath = cursor.getString(cursor.getColumnIndex(colunm)); } if (cursor!= zero) cursor.close(); render filepath; } public void readfile(File file){ // File file = new File(Environment.getExternalStorageDirectory(), "mytextfile.txt"); StringBuilder builder = new StringBuilder(); Log.e("main", "read showtime"); endeavour { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine())!=zilch){ builder.append(line); builder.append("\n"); } br.close(); }catch (Exception e){ Log.e("main", " error is "+e.toString()); } Log.e("main", " read text is "+ builder.toString()); textView.setText(builder.toString()); } }
Run the lawmaking
At present every thing has setup. Please run the lawmaking, select file from gallery. Yous will see the text read from the text file will be display on screen.
If you lot have whatsoever question, please contact me or employ chat box.
Please annotate below, if this tutorial help yous. Your feed dorsum is more than important for me to create new videos and tutorial.
How to Add together Referral Arrangement in Android App Using Firebase
How To Integrate Google Pay In Android App- UPI Payment
How to Read Felder & Solomon Index
Source: https://www.blueappsoftware.com/how-to-read-text-file-in-android-tutorial/
0 Response to "How to Read Felder & Solomon Index"
Post a Comment