How store data from Firebase to native GearVR Framework? - android

I want to load different cubemaps from database. Following code I used, but it is not working. It crashes every time.
I can t get the path to the primary external storage in Android. Does anyone know how I can store Data from Database to the native GearVR Framework?
public class SampleActivity extends GVRActivity {
final File externalFilesDir = getExternalFilesDir(null);
private SampleMain main;
private long lastDownTime = 0;
//ref to storage firebase
private StorageReference cubemap_ref;
#Override
protected void onCreate(Bundle icicle) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
cubemap_ref = storageRef.child("cubemaps/cubemap_example.zip");
final long TEN_MEGABYTE = 1024 * 1024 * 10;
cubemap_ref.getBytes(TEN_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
File file = new File(externalFilesDir.getAbsolutePath(), "cubemap.zip");
try {
OutputStream os = new FileOutputStream(file);
os.write(bytes);
os.close();
} catch (IOException e) {
android.util.Log.w("ExternalStorage", "Error writing " + file, e);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Handle any errors
}
});
super.onCreate(icicle);
main = new SampleMain(this);
setMain(main, "gvr.xml");
}
}
Thanks in advance.

I don t know why, but this code works now.

Related

how to read pdf file file in android studio

I'm a beginner in android development , I want to make android app that can read pdf files. the pdf files that i have is with large contests (each pdf file around 60 mb) , as i searched i need to store the files in the server like website or something ( i don't know exactly is that what i need ) if i will store the files on server how can i make the users read the pdf files without downloading them into their phones? .
i found that i need to use web view but i'm not sure if this is the right way . and if what i'm thinking is wrong way please tell me what is the right way .i hope someone will help me because i'm searching for this and i'm not finding any specific answer .thank you
You can view a pdf file in an android project in different ways. I will describe some of them here-
1. Using Library:
Steps are below:
Installation
Add to build.gradle:
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
ProGuard
If you are using ProGuard, add following rule to proguard config file:
-keep class com.shockwave.**
Include PDFView in your layout
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Further link is here
2. Load pdf url into webview:
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename = file_url_with_name;
webview.loadUrl(file_url + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
3. Manually show PDF file into Imageview
// Example for creating manual PDF viewer into imageview used butterknife view binding<br/>
public class PdfRenderActivity extends AppCompatActivity {
#BindView(R.id.pdf_image) ImageView imageViewPdf;
#BindView(R.id.button_pre_doc) FloatingActionButton prePageButton;
#BindView(R.id.button_next_doc) FloatingActionButton nextPageButton;
private static final String FILENAME = "report.pdf";
private int pageIndex;
private PdfRenderer pdfRenderer;
private PdfRenderer.Page currentPage;
private ParcelFileDescriptor parcelFileDescriptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_render);
ButterKnife.bind(this);
pageIndex = 0;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onStart() {
super.onStart();
try {
openRenderer(getApplicationContext());
showPage(pageIndex);
} catch (IOException e) {
e.printStackTrace();
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onStop() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onStop();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#OnClick(R.id.button_pre_doc)
public void onPreviousDocClick(){
showPage(currentPage.getIndex() - 1);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#OnClick(R.id.button_next_doc)
public void onNextDocClick(){
showPage(currentPage.getIndex() + 1);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void openRenderer(Context context) throws IOException {
// In this sample, we read a PDF from the assets directory.
File file = new File(context.getCacheDir(), FILENAME);
if (!file.exists()) {
// Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
if (parcelFileDescriptor != null) {
pdfRenderer = new PdfRenderer(parcelFileDescriptor);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void closeRenderer() throws IOException {
if (null != currentPage) {
currentPage.close();
}
pdfRenderer.close();
parcelFileDescriptor.close();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void showPage(int index) {
if (pdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != currentPage) {
currentPage.close();
}
// Use `openPage` to open a specific page in PDF.
currentPage = pdfRenderer.openPage(index);
// Important: the destination bitmap must be ARGB (not RGB).
Bitmap bitmap = Bitmap.createBitmap(currentPage.getWidth(), currentPage.getHeight(),
Bitmap.Config.ARGB_8888);
// Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// We are ready to show the Bitmap to user.
imageViewPdf.setImageBitmap(bitmap);
updateUi();
}
/**
* Updates the state of 2 control buttons in response to the current page index.
*/
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void updateUi() {
int index = currentPage.getIndex();
int pageCount = pdfRenderer.getPageCount();
prePageButton.setEnabled(0 != index);
nextPageButton.setEnabled(index + 1 < pageCount);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int getPageCount() {
return pdfRenderer.getPageCount();
}
}
Doc is here

How to fix "download file store on google drive" error in android

I've made an app for downloading a pdf file from direct link to internal storage. When I try to download a direct link of google drive link it works fine, if the file is less than 3MB. But if the file is more than 3MB, it is not downloaded. Here is my code below:
public class MainActivity extends AppCompatActivity {
private final String Pdf_LINK =
("https://drive.google.com/uc?export=download&id=13mE9gCyTGmLrFOZqu6Lz-yz0mcfjGoJc");
private final String My_PDF ="my100.pdf";
private AppCompatSeekBar seekBar;
private PDFView pdfView;
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView = findViewById(R.id.pdfView);
txtView = findViewById(R.id.txtView);
initSeekar();
downloadpdf(My_PDF);
}
private void initSeekar(){
seekBar = findViewById(R.id.seeBar);
seekBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.RED,PorterDuff.Mode.SRC_IN);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int val = (progress * (seekBar.getWidth() - 3 * seekBar.getThumbOffset())) / seekBar.getMax();
txtView.setText("" + progress);
txtView.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void downloadpdf(final String fileName) {
new AsyncTask<Void, Integer, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {return downloadpdf();}
#Nullable
private Boolean downloadpdf() {
try {
File file = getFileStreamPath(fileName);
if (file.exists())
return true;
try {
FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
URL u = new URL(Pdf_LINK);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
InputStream input = new BufferedInputStream(u.openStream());
byte data[] = new byte[contentLength];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / contentLength));
fileOutputStream.write(data, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
input.close();
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
seekBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
openPdf(fileName);
} else {
Toast.makeText(MainActivity.this, "Unable to download this file", Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
private void openPdf(String fileName) {
try {
File file = getFileStreamPath(fileName);
Log.e("file", "file: " + file.getAbsolutePath());
seekBar.setVisibility(View.GONE);
pdfView.setVisibility(View.VISIBLE);
pdfView.fromFile(file)
.enableSwipe(true)
.swipeHorizontal(false)
.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is the error in this code? How can I solve this? If I try to download a pdf file from another site, it works well. But the problem is only, when trying to download from google drive. please help me.
I was able to download large public shareable files from google drive.
Use the URL:
https://drive.google.com/uc?id=<FILE_ID>&export=download
Replace <FILE_ID> with your shareable file ID.
I used the code in 'private class DownloadTask'
in this solution:
Download a file with Android, and showing the progress in a ProgressDialog
The code inside the doInBackground function works, I modified it for my own needs, used ProgressBar instead. I am not posting my code since it's too long.
Hope you can solve your problem.

Compare a file in the device with one in firebase

My app download html files from the database the first time the app is opened.
When a button is clicked I want to check every html file and download an "updated" html version (Only if the html in the device is different from the one in the database)
How can I do that kind of comparison?
My main activity onCreate with a boolean to check if is the first time the app is opened then a function getFiles() is called to download every html file.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_horarios = (Button)findViewById(R.id.btn_horarios);
Boolean isrunfirst = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("first", true);
if(isrunfirst){
getFiles();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("first", false).apply();
} else {
}
}
getFiles function with a loop used to "loop" through a String array containing the name of the files, with the name the file is retrieved from the database and finally the file is saved using a function saveFile()
public void getFiles(){
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final String[] grupos = getResources().getStringArray(R.array.array_grupos);
for(int i = 0; i < 97; i += 1) {
final int finalI = i;
StorageReference htmlRef = storageRef.child("grupos/" + grupos[finalI] + ".html");
final long ONE_MEGABYTE = 1024 * 1024;
htmlRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
saveFile(grupos[finalI] + ".html", bytes);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
}
saveFile() takes the file name and the bytes, the bytes are converted into a string an saved.
private void saveFile(String file, byte[] bytes) {
try {
String text = new String(bytes, "UTF-8");
FileOutputStream fis = openFileOutput(file, Context.MODE_PRIVATE);
fis.write(text.getBytes());
fis.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}

How to return a value after onSuccess is finished?

I'm having a little trouble, im executing a method in my doinBackground task, so I'm getting a crash because im accesing to another class without finishing this method first, so i want to add a return or something to let the method know when it needs to launch the other activity. I have searched and I can't return a boolean, true or false into Firebase asynctask method. This is the method I use to download a file and replace it into internal memory, but when im doing this , the other activity I need to launch after this launches and i get a crash, so i need to first execute this download task and then if something is true launch my other activity
This is where I want to put a boolean or something that tells me that the download finished.
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
Log.e("NombreArchivo",""+xFile);
try {
FileOutputStream fos = context.openFileOutput("pictos.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(xFile.getAbsolutePath()).getBytes());
Log.e("xFILEDESCARGARPAIS",""+getStringFromFile(xFile.getAbsolutePath()));
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
The method is not an asyncTask, is an async but from Firebase, this is the method:
public boolean DescargarArchivosPais(String locale){
File rootPath = new File(context.getCacheDir(),"MY_FILES");
if(!rootPath.exists()) {
rootPath.mkdirs();//si no existe el directorio lo creamos
}
StorageReference mStorageRef2 = FirebaseStorage.getInstance().getReference().child("Files/y/" + "y_" + locale + "." + "txt");
StorageReference mStorageRef1 = FirebaseStorage.getInstance().getReference().child("Files/x/" + "x_" + locale + "." + "txt");
Log.e("REFERENCIAx",""+ mStorageRef1);
Log.e("REFERENCIAy",""+ mStorageRef2);
final File xFile = new File(rootPath, "x.txt");
final File yFile = new File(rootPath, "y.txt");
mStorageRef1.getFile(xFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
Log.e("NombreArchivo",""+xFile);
try {
FileOutputStream fos = context.openFileOutput("x.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(xFile.getAbsolutePath()).getBytes());
Log.e("LOG",""+getStringFromFile(xFile.getAbsolutePath()));
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
mStorageRef2.getFile(yFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
Log.e("NombreArchivo",""+yFile);
try {
FileOutputStream fos = context.openFileOutput("y.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(gruposFile.getAbsolutePath()).getBytes());
Log.e("LOG2",""+getStringFromFile(gruposFile.getAbsolutePath()));
fos.close();
fSuccess = true;
} catch (Exception e) {
e.printStackTrace();
Log.e("printStackTrace",""+e.toString());
fSuccess = false;
}
fSuccess = true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
fSuccess=false;
Log.e("printStackTrace",""+e.toString());
}
});
return fSuccess;
}
Updated with following comment (replace Activity reference and introduce interface instead):
You can definitively do things like that with AsyncTask. Please have a look at the following minimalist code:
public class MyTask extends AsyncTask<Void, Void, Boolean> {
private IMyCallbackContext context;
public MyTask(IMyCallbackContext context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// Here you are still on the MainThread
// Do Stuff
}
#Override
protected Boolean doInBackground(Void... params) {
// Here you are not on the MainThread
// Do Stuff
return isSuccess;
}
#Override
protected void onPostExecute(Boolean isSuccess) {
// Here you are again on the MainThread
if (isSuccess) {
context.onTaskSuccessDoStuff();
} else {
context.onTaskFailureDoStuff();
}
}
}
public interface IMyCallbackContext {
void onTaskSuccessDoStuff();
void onTaskFailureDoStuff();
}
public class MyActivity extends Activity implements IMyCallbackContext {
private void launchTask() {
MyTask myTask = new MyTask(this);
myTask.execute();
}
public void onTaskSuccessDoStuff() {
// Do stuff after the task has completed
}
public void onTaskFailureDoStuff() {
// Do stuff after the task has failed
}
}
Edit: sorry I thought you had an AsyncTask
onSuccess() method has an asynchronous behaviour. This means that in order to use the data that you are getting from Firebase Storage, you need to wait for it. So to do that, there is no need to use an AsyncTask, you can simply create your own custom callback.
To make this happen, please see the last part for my answer from this post. As Mohammed Atif mentioned in his comment, never use the Activity reference directly because it will cause memory leaks. So the way I mentioned above, is the simplest and safest way in which you can achieve this.

getting images from firebase storage in android

In my Activity I use FireBase to download pics of my game from the storage.
If I run this code on my Activity it works but if I use it in my level class as a method, it just returns null.
This is my Activity:
pic = null;
answer = null;
option = null;
picture = null;
try {
answer = File.createTempFile("buttonanswer", "png");
StorageReference storageRef = storage.getReferenceFromUrl("gs://yougotit-8ce92.appspot.com");
StorageReference levelDifficultRef = storageRef.child("easy");
final StorageReference levelRef = levelDifficultRef.child(Game.LEVEL + 1);
StorageReference levelAnswerRef = levelRef.child("pic" + "." + "jpg");
levelAnswerRef.getFile(answer).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
answerV = new ImageView(getApplicationContext());
Bitmap myBitmap = BitmapFactory.decodeFile(answer.getPath());
answerV.setImageBitmap(myBitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
maingameLinarLayout.addView(answerV);
}
});
}
});
}
catch (IOException e) {
e.printStackTrace();
}
In the level class this my code that doesn't work and returns null.
This is my level class:
public class Level {
public static final String ANSWER="answer";
public static final String OPTION="ops";
public static final String PICTURE="pic";
public static final String QUESTION="question";
public static final String PNG = "png";
public static final String JPG = "jpg";
private File mainPicture,fadedPicture,opt1,opt2,opt3,answer,question;
private int flag;//in easy level when reach to 6 it indicate that that level is ready //in medium and hard level when reach to 7
private StorageReference storageRef;
private String difficult;
private Game game;
public Level(Game game,FirebaseStorage storageIns,String difficult,int level) {
flag = 0 ;
this.game = game;
this.difficult = difficult;
this.storageRef = storageIns.getReferenceFromUrl("gs://yougotit-8ce92.appspot.com");
StorageReference levelDifficultRef = storageRef.child(difficult);
final StorageReference levelRef = levelDifficultRef.child(Game.LEVEL+level);
if(difficult.equals(Game.LEVEL_HARD) ) {
}
if(difficult.equals(Game.LEVEL_MEDIUM) ) {
}
else {
downloadPicture(levelRef, mainPicture, PICTURE, JPG);
downloadPicture(levelRef, answer, ANSWER, PNG);
downloadPicture(levelRef, opt1, OPTION + 1, PNG);
downloadPicture(levelRef, opt2, OPTION + 2, PNG);
downloadPicture(levelRef, opt3, OPTION + 3, PNG);
}
}
private void downloadPicture(StorageReference levelRef,File f,String picName,String picFormat) {
StorageReference pictureRef = levelRef.child(picName+"."+picFormat);
f = null;
try {
f = File.createTempFile(picName,picFormat);
pictureRef.getFile(f).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
flag++;
if(flag == 5) {
activeCallBack();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please help me figuring out what's going wrong?
You are downloading different references in your Level class so this looks like an apples to orange comparison.
Try adding a addOnFailure in addition to addOnSuccess as I suspect that you are getting 404's for these other files.

Categories

Resources