I am new to Android, and I am trying to output the .docx and .doc file to TextView with the click of a button, it does not display my file correctly, how can I fix this? txt format is displayed as it should!
public class MainActivity extends AppCompatActivity {
TextView tv_output;
Button b_load;
private static final int PERMISSION_REQUEST_STORAGE=10000;
private static final int READ_REQUEST_CODE=42;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_STORAGE);}
tv_output=(TextView) findViewById(R.id.tv_output);
b_load=(Button) findViewById(R.id.b_load);
b_load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performFileSearch();
}
});
}
//read content of the file
private String readText(String input){
File file=new File(input);
StringBuilder text=new StringBuilder();
try{
BufferedReader br=new BufferedReader(new FileReader(file));
String line;
while((line= br.readLine())!=null){
text.append(line);
text.append("\n");
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return text.toString();
}
//select file from storage
private void performFileSearch(){
Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
startActivityForResult(intent,READ_REQUEST_CODE);}
@SuppressLint("MissingSuperCall")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode==READ_REQUEST_CODE && resultCode==Activity.RESULT_OK){
if(data!=null){Uri uri =data.getData();
String path=uri.getPath();
path=path.substring(path.indexOf(":")+1);
Toast.makeText(this,""+path,Toast.LENGTH_SHORT).show();
tv_output.setText(readText(path));}}}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{if(requestCode==PERMISSION_REQUEST_STORAGE){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission granted",Toast.LENGTH_SHORT).show();}
else{Toast.makeText(this,"Permission not granted",Toast.LENGTH_SHORT).show();
finish();}}}