I have problem when trying to download PDF file and save it in internal storage or Shared-preferences and read it. Is it possible to download it in internal storage? I have followed several tutorials from internet but it doesn't work. could someone guide me how to do it? Thanks a lot.
package com.icul.downloadinternal;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
Button download, read;
ImageView pdf;
String url = "https://www.cdc.gov/eval/guide/cdcevalmanual.pdf";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download = (Button) findViewById(R.id.button);
read = (Button) findViewById(R.id.button2);
pdf = (ImageView) findViewById(R.id.image);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
downloadFileSync(url);
} catch (Exception e) {
e.printStackTrace();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String previouslyEncodedImage = shre.getString("pdf_data", "");
if( !previouslyEncodedImage.equalsIgnoreCase("") ){
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0 , b.length);
pdf.setImageBitmap(bitmap);
}
else {
Toast.makeText(getApplicationContext(),"No File", Toast.LENGTH_LONG).show();
}
}
});
}
public void downloadFileSync(String downloadUrl) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(downloadUrl).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Failed to download file: " + response);
}
String encodedImage = Base64.encodeToString(response.body().bytes(), Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("pdf_data", encodedImage);
edit.commit();
}
}