2

I want to pick a file from an android device, convert that file into string format, convert that string to BASE64 encoding, then pass that encoded string to the server via an API.

I debugged my project and it goes up to this line:

 FileInputStream fis = new FileInputStream(new File(path)); 

It does not go further.

Can someone please tell me where I am doing wrong?

Thanks in advance.

Here is my code:

 package com.example.deepb.testingencodingapp; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.util.Base64; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { EditText fatchValue; TextView displayValue,Fpath; Button GetValue,SelectFile; String ret,uriString,finalString; File myFile; String line = null; private static final int PICKFILE_RESULT_CODE = 1; public static final int RESULT_OK = -1; Uri uri; byte[] fileBytes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fatchValue = findViewById(R.id.enterText); displayValue = findViewById(R.id.displayText); Fpath = findViewById(R.id.pathText); GetValue = findViewById(R.id.btn_go); SelectFile = findViewById(R.id.uploadFile); GetValue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String GotValue = fatchValue.getText().toString(); byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT); String ansValue = encodeValue.toString(); //displayValue.setText(ansValue); displayValue.setText(finalString); Log.d(finalString,"this is the String " + finalString); } }); SelectFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent getFile = new Intent(Intent.ACTION_GET_CONTENT); getFile.setType("*/*"); startActivityForResult(getFile,PICKFILE_RESULT_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { uri = data.getData(); uriString = uri.toString(); myFile = new File(uriString); ret = myFile.getAbsolutePath(); Fpath.setText(ret); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String path = ret; FileInputStream fis = new FileInputStream(new File(path)); byte[] buf = new byte[1024]; int n; while (-1 != (n = fis.read(buf))) baos.write(buf, 0, n); fileBytes = baos.toByteArray(); //Log.i("ByteArray" + path + ">><<" + ret, "----" + fileBytes.toString()); finalString = fileBytes.toString(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } 
6
  • What error are you getting? Commented Jul 25, 2018 at 23:50
  • not a single error..it get perfectly execute upto this line FileInputStream fis = new FileInputStream(new File(path)); then I get "fileBytes" = null. So "finalString=null".. This is What i get in Logcat.. /com.example.deepb.testingencodingapp E/Activity: onResume-Exception-e:Attempt to invoke interface method 'void android.app.applock.ILavaAppLockService.startLockMonitor(java.lang.String, java.lang.String)' on a null object reference /com.example.deepb.testingencodingapp E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length Commented Jul 26, 2018 at 14:12
  • hey @GinoMempin..May be problem is that file can not get read by FileInputStream..that's what I think.. can you please provide me any solution for this? What I am doing wrong or where I am going wrong? Commented Jul 26, 2018 at 21:03
  • Hmm. My initial understanding when you said "it goes up to this line" and "It does not go further." was that it stops running or throws an exception at new FileInputStream(new File(path));. So the actual problem is in reading the file. If "fileBytes = null" as you said, then you should be getting a NullPointerException at finalString = fileBytes.toString();. Is it really null or empty/zero? BTW, that logcat error you shared isn't related to the problem (it's a common error when using EditText). Commented Jul 26, 2018 at 23:39
  • Since what you really need are the file contents as String, try using BufferedReader to read it as String instead of bytes. Something like stackoverflow.com/questions/12910503/read-file-as-string/…. Commented Jul 26, 2018 at 23:44

1 Answer 1

4
public class DeppDemo extends AppCompatActivity { EditText fatchValue; TextView displayValue, Fpath; Button GetValue, SelectFile; String ret, uriString, finalString; File myFile; String line = null; private static final int PICKFILE_RESULT_CODE = 1; public static final int RESULT_OK = -1; Uri uri; byte[] fileBytes; StringBuilder total = new StringBuilder(); String[] permissions = new String[]{ android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermissions(); displayValue = findViewById(R.id.displayText); Fpath = findViewById(R.id.pathText); GetValue = findViewById(R.id.btn_go); SelectFile = findViewById(R.id.uploadFile); GetValue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; //String GotValue = fatchValue.getText().toString(); // byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT); // byte[] encodeValue = Base64.encode(fileBytes, Base64.DEFAULT); byte[] encodeValue = Base64.encode(total.toString().getBytes(), Base64.DEFAULT); //byte[] encodeValue = Base64.encode(s.getBytes(), Base64.DEFAULT); String ansValue = encodeValue.toString(); try { String text = new String(encodeValue, "UTF-8"); displayValue.setText(text); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //displayValue.setText(ansValue); Log.d(finalString, "this is the String " + finalString); } }); SelectFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent getFile = new Intent(Intent.ACTION_GET_CONTENT); getFile.setType("*/*"); startActivityForResult(getFile, PICKFILE_RESULT_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { uri = data.getData(); uriString = uri.toString(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String path = ret; InputStream in = getContentResolver().openInputStream(uri); InputStreamReader inputStreamReader = new InputStreamReader(in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { total.append(line).append('\n'); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); Log.d("error", "onActivityResult: " + e.toString()); } } } private boolean checkPermissions() { int result; List<String> listPermissionsNeeded = new ArrayList<>(); for (String p : permissions) { result = ContextCompat.checkSelfPermission(this, p); if (result != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(p); } } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100); return false; } return true; } 

}

its not covert proper base64 so try this one

 public class DeppDemo extends AppCompatActivity { EditText fatchValue; TextView displayValue, Fpath; Button GetValue, SelectFile; String ret, uriString, finalString; File myFile; String line = null; private static final int PICKFILE_RESULT_CODE = 1; public static final int RESULT_OK = -1; Uri uri; byte[] fileBytes; StringBuilder total = new StringBuilder(); byte[] bytes; ByteArrayOutputStream output; String[] permissions = new String[]{ android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermissions(); displayValue = findViewById(R.id.displayText); Fpath = findViewById(R.id.pathText); GetValue = findViewById(R.id.btn_go); SelectFile = findViewById(R.id.uploadFile); GetValue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // String s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; // //String GotValue = fatchValue.getText().toString(); // // byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT); // // byte[] encodeValue = Base64.encode(fileBytes, Base64.DEFAULT); // Log.d("image string", "onClick: "+total); // byte[] encodeValue = new byte[0]; // try { // encodeValue = Base64.encode(total.toString().getBytes("UTF-8"), Base64.DEFAULT); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // //byte[] encodeValue = Base64.encode(s.getBytes(), Base64.DEFAULT); // String ansValue = encodeValue.toString(); // try { // String text = new String(encodeValue, "UTF-8"); // //displayValue.setText(text); // Log.d("Base64", "onClick: "+text); // Log.d("Base64 byte", "onClick: "+encodeValue); // //String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT); // String encodedString = Base64.encodeToString(output.toByteArray(), Base64.DEFAULT); // Log.d("Base64 ==2", "onClick: "+encodedString); // // // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // //displayValue.setText(ansValue); // Log.d(finalString, "this is the String " + finalString); } }); SelectFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent getFile = new Intent(Intent.ACTION_GET_CONTENT); getFile.setType("*/*"); startActivityForResult(getFile, PICKFILE_RESULT_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { uri = data.getData(); uriString = uri.toString(); Log.d("data", "onActivityResult: uri"+uriString); // myFile = new File(uriString); // ret = myFile.getAbsolutePath(); //Fpath.setText(ret); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String path = ret; InputStream in = getContentResolver().openInputStream(uri); bytes=getBytes(in); Log.d("data", "onActivityResult: bytes size="+bytes.length); Log.d("data", "onActivityResult: Base64string="+Base64.encodeToString(bytes,Base64.DEFAULT)); // InputStreamReader inputStreamReader = new InputStreamReader(in); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // String line; // while ((line = bufferedReader.readLine()) != null) { // total.append(line); // } // // byte[] buffer = new byte[8192]; // int bytesRead; // output = new ByteArrayOutputStream(); // int count=0; // try { // while ((bytesRead = in.read(buffer)) != -1) { // output.write(buffer, 0, bytesRead); // count++; // } // } catch (IOException e) { // Log.d("error byte", "onActivityResult: " + e.toString()); // e.printStackTrace(); // } // bytes = output.toByteArray(); // // Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show(); // FileInputStream fis = new FileInputStream(new File(uri.getPath())); // byte[] buf = new byte[1024]; // int n; // while (-1 != (n = in.read(buf))) { // baos.write(buf, 0, n); // } // fileBytes = baos.toByteArray(); // //Log.i("ByteArray" + path + ">><<" + ret, "----" + fileBytes.toString()); // finalString = fileBytes.toString(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); Log.d("error", "onActivityResult: " + e.toString()); } } } public byte[] getBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } return byteBuffer.toByteArray(); } private boolean checkPermissions() { int result; List<String> listPermissionsNeeded = new ArrayList<>(); for (String p : permissions) { result = ContextCompat.checkSelfPermission(this, p); if (result != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(p); } } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100); return false; } return true; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sooo much..It is working for me. With all type of (Small)file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.