Bitmap saved as black image sometimes for same bitmap - android

I know this was a common issue, but I have tried different suggestion, and still no solution.
My issue is that the bitmap is being displayed correctly, however SOMETIMES it saves as a black bitmap, while other times it saves correctly.
Can anyone see what I have done and tell me where I can be going wrong?
I have looked at most of the other StackOverflow questions.
The following is my code, which encodes the clip board text into a QR code and attempts to save the qr code generated.
Thank you!
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//import android.content.ClipboardManager;
public class BarcodeWriter extends AppCompatActivity {
ImageLoader imgLoader;
ImageView qrImg;
String copiedStr;
TextView qrTxt;
ClipboardManager clipboard;
String BASE_QR_URL = "http://chart.apis.google.com/chart?cht=qr&chs=400x400&chld=M&choe=UTF-8&chl=";
String fullUrl = BASE_QR_URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_writer);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
imgLoader = ImageLoader.getInstance(); // Do it on Application start
imgLoader.init(config);
qrImg = (ImageView)findViewById(R.id.qrImg);
qrTxt = (TextView)findViewById(R.id.qrTxt);
clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
/*
* clipboard.getText() is now deprecated. But I am going to use it here
* because the new way of doing the same thing only works on API lvl 11+
* Since I want this application to support API lvl 4+ we have to use
* the old method.
*/
CharSequence clipTxt = clipboard.getText();
//This is the new, non-deprecated way of getting text from the Clipboard.
//CharSequence clipTxt = clipboard.getPrimaryClip().getItemAt(0).getText();
//If the clipboard has text, and it is more than 0 characters.
if((null != clipTxt) && (clipTxt.length() > 0)){
try {
qrTxt.setText(clipTxt);
copiedStr = clipTxt.toString();
fullUrl += URLEncoder.encode(copiedStr, "UTF-8");
//imgLoader.displayImage(fullUrl, qrImg);
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions); // Incoming options will be used
qrImg.setDrawingCacheEnabled(true);
qrImg.measure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
qrImg.layout(0, 0, qrImg.getMeasuredWidth(), qrImg.getMeasuredHeight());
qrImg.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(qrImg.getDrawingCache());
qrImg.setDrawingCacheEnabled(false); // clear drawing cache
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/DCIM/QR codes");
myDir.mkdirs();
String fname = clipTxt+".png";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
Toast.makeText(BarcodeWriter.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
Toast.makeText(this,"QR Code showing "+clipTxt,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{ //If no text display a dialog.
Toast.makeText(this,"No text in clipboard",Toast.LENGTH_SHORT).show();
}
}
}

Your code seems to be fine, the only thing that I saw is that you are getting you Bitmap from and external URL with Universal Image Loader instantly after calling displayImage. So is possible that for some delay in the network sometimes your ImageView still doesn't have the entire image and can make your bitmap saved as black.
Please try moving your all code bellow ImageLoader.getInstance().displayImage inside the onLoadingComplete like this:
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions, new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions,null);
qrImg.setDrawingCacheEnabled(true);
...
catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
});
Hope this help!!

Related

why is pdf from internal storage not showing in webview

I have a .pdf file (which can change content daily, so must be downloaded daily) on my server which is downloaded to the device using Volley. The api uses authentication tokens.
I can successfully call the web service and write the pdf (byte[]) to my app's internal storage by using context.getExternalFilesDir.
The problem i am having is once the pdf is saved and i contruct the path, the webView will not show the pdf. The webView is working fine as i have done a test by placing a test html in the project's raw directory. The webView can display this fine.
The following does not load the pdf.
webView.loadUrl("file://" + f2.getAbsolutePath());
f2 path on my device is
f2.getAbsolutePath() = /storage/emulated/0/Android/data/com.xxxx.rrx/files/careplans/careplan.pdf
There seems to be no error but the pdf does not load.
What i have tried:
i've tried changing the webSettings for the webView to allow file access.
WebSettings webViewSettings = webView.getSettings();
// Setting this off for security. Off by default for SDK versions >= 16.
webViewSettings.setAllowFileAccessFromFileURLs(true);
// Off by default, deprecated for SDK versions >= 30.
webViewSettings.setAllowUniversalAccessFromFileURLs(true);
// Keeping these off is less critical but still a good idea, especially if your app is not
// using file:// or content:// URLs.
webViewSettings.setAllowFileAccess(true);
webViewSettings.setAllowContentAccess(true);
Does anyone have any ideas why the webview does not show the pdf when it is stored in the app's own storage?
here is my complete class.
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.VolleyError;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
public class DownloadCarePlanActivity extends AppCompatActivity {
private static final String TAG = DownloadCarePlanActivity.class.getSimpleName();
DownloadManager manager;
long reference;
String url;
Context context;
String fileName;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.downloadcareplan_activity);
Log.e(TAG, "inside onCreate" );
context = getApplicationContext();
webView = (WebView)findViewById(R.id.webViewCareplan);
url = "https://xxx/api/xxx/careplan/1";
WebServicesForWebApi webServices = new WebServicesForWebApi(DownloadCarePlanActivity.this, new WebServicesForWebApi.IResultForFile() {
#Override
public void notifySuccess(byte[] response, String responseString) {
//responseString = responseString.replace('\\', ' ');
Log.e(TAG, "formatted result for pdf webservice = " + response);
byte[] result;
if(response != null){
try {
byte[] bytes = response;
saveToFile(bytes, "careplan.pdf");
}catch (Exception e){
Toast.makeText(DownloadCarePlanActivity.this, "Error downloading pdf and saving it", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void notifyError(VolleyError error) {
Toast.makeText(DownloadCarePlanActivity.this, "There was a problem in sendFireBaseTokenToServerWAPI", Toast.LENGTH_LONG).show();
}
});
JSONObject js = new JSONObject();
/*try {
js.put("carerId", "0");
js.put("phoneId", fireBaseToken);
} catch (JSONException e) {
e.printStackTrace();
}*/
webServices.makeWebApiPostForFile(url, js);
}//end of onCreate
public void saveToFile(byte[] byteArray, String pFileName){
//File f = new File(Environment.getExternalStorageDirectory() + "/careplans");
File f = getAbsoluteFile("/careplans", context);
Log.e(TAG, "f.path = " + f.getAbsolutePath());
if(f.isDirectory()){
f.delete();
}
if (!f.isDirectory()) {
f.mkdir();
}
//String fileName = Environment.getExternalStorageDirectory() + "/careplans/" + pFileName;
fileName = f.getAbsolutePath() + "/" + pFileName;
Log.e(TAG, "String fileName = " + fileName);
try {
FileOutputStream fPdf = new FileOutputStream(fileName);
fPdf.write(byteArray);
fPdf.flush();
fPdf.close();
Toast.makeText(this, "File successfully saved", Toast.LENGTH_LONG).show();
try {
File f2 = new File(fileName);
Log.e(TAG, "f2.getAbsolutePath() = " + f2.getAbsolutePath());
Log.e(TAG, "f2.getCanonicalPath() = " + f2.getCanonicalPath());
Log.e(TAG, "loading file in webview" );
WebSettings webViewSettings = webView.getSettings();
// Setting this off for security. Off by default for SDK versions >= 16.
webViewSettings.setAllowFileAccessFromFileURLs(true);
// Off by default, deprecated for SDK versions >= 30.
webViewSettings.setAllowUniversalAccessFromFileURLs(true);
// Keeping these off is less critical but still a good idea, especially if your app is not
// using file:// or content:// URLs.
webViewSettings.setAllowFileAccess(true);
webViewSettings.setAllowContentAccess(true);
webView.loadUrl("file://" + f2.getAbsolutePath());
//webView.loadUrl("file:///android_res/raw/index.html");
Log.e(TAG, "finished loading file in webview" );
}catch(Exception e){
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
String stacktrace = result.toString();
printWriter.close();
Log.e(TAG, "stack = " + stacktrace);
}
} catch (FileNotFoundException e) {
Toast.makeText(this, "File create error", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this, "File write error", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
private File getAbsoluteFile(String relativePath, Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return new File(context.getExternalFilesDir(null), relativePath);
} else {
return new File(context.getFilesDir(), relativePath);
}
}
}
well, WebView is designed to open web pages, PDF isn't such content type... yeah, desktop browser can do it, even some mobile ones, but this is additional feature. not available in WebView, you have to handle such file by yourself (e.g. using PdfRenderer). another way is to use some library, first example from search engine: AndroidPdfViewer on GitHub
edit: just realised that your PDF is local only, so below probably isn't an option for you...
way simpler would be to use some web application, which can read PDF and show it as a web page, readable by WebView. for example try to load below URL
String pdfUrl = "https://docs.google.com/gview?embedded=true&url=" + realPdfUrl;

Create, write and display PDF file in android app

I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file. I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7
package com.example.sweetiean.androidpdfdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button createPDF , openPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createPDF = (Button)findViewById(R.id.button1);
createPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();
}
});
openPDF = (Button)findViewById(R.id.button2);
openPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPdf();
}
});
}
public void createPDF()
{
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "demo.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
/* Create Paragraph and S`enter code here`et Font */
Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");
/* Create Set Font and its Size */
Font paraFont= new Font(Font.HELVETICA);
paraFont.setSize(16);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
/* You can also SET FONT and SIZE like this */
Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
/* Inserting Image in PDF */
/*ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);*/
//set footer
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
void openPdf()
{
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the main activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="100dp"
android:text="Open PDF" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="44dp"
android:text="Generate PDF" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/hello_world" />
Do it this way:
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
Also check these links. They will help you to fulfill your requirement.
http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx
https://github.com/JoanZapata/android-pdfview
How to create PDFs in an Android app?
Render a PDF file using Java on Android
you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.
For this you'll need to add the jar of iTextG to your project:
OR
if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.
For Simple Create and Open pdf:
// Method for creating a pdf file from text, saving it then opening it for display
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "mypdffile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.FontFamily.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("mypdffile.pdf", "PDF");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}
Check this link,it requires you to download a jar file.(more description in the link).Here is a part of code to generate pdf.
package com.cete.androidexamples.dynamicpdf.helloworld;
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}

Taking screenshot crashes app

I tried creating a screenshot app, but somehow I can not get the root content.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
public class Screenshot extends Activity {
public final String TAG = "Screen";
String output;
public String takeScreen(String savepathname) {
Log.e(TAG, "TAKESCREEN 01");
//View content = findViewById(R.id.button1);
//View content = findViewById(R.id.layoutroot);
//View content = getWindow().getDecorView().findViewById(android.R.id.content);
Log.e(TAG, "TAKESCREEN 01.5");
content.setDrawingCacheEnabled(true);
Log.e(TAG, "TAKESCREEN 02");
//View content = findViewById(R.id.layoutroot);
Bitmap bitmap = content.getDrawingCache();
File file = new File( Environment.getExternalStorageDirectory() + savepathname);
Log.e(TAG, "TAKESCREEN 03");
try{
Log.e(TAG, "TAKESCREEN 04");
file.createNewFile();
Log.e(TAG, "TAKESCREEN 05");
FileOutputStream ostream = new FileOutputStream(file);
Log.e(TAG, "TAKESCREEN 06");
bitmap.compress(CompressFormat.PNG, 100, ostream);
Log.e(TAG, "TAKESCREEN 07");
ostream.close();
output = "Successfully saved -> "+savepathname;
}catch (Exception e) {
e.printStackTrace();
output = "Screenshot.java -> "+e;
}
return output;
}
}
If I use findViewbyId, I only get this error: "layoutroot cannot be resolved or is not a field".
While using "getWindow().getDecorView().findViewById(android.R.id.content);" works, but then the app crashes in that part.
Could someone help me with that, please?
Did you implement this part too? If you didn't, place it inside your Screen class. By the way, I strongly believe that going over this activity lifecycle tutorial will help you.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Assuming that button1 and layoutroot are properly described within activity_main.xml

Sceenshot View have some error: Layout cannot be found

i try to sceenshot View but R.id.layout cannot be resolved or is not a field
and i try to import com.example.mye_card.R; then clean up but not work
btnsave.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View v2 = findViewById(R.id.layout);
v2.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(v2.getDrawingCache());
v2.setDrawingCacheEnabled(false);
try {
Date d = new Date();
String filename = (String)DateFormat.format("kkmmss-MMddyyyy"
, d.getTime());
File dir = new File(Environment.getExternalStorageDirectory(), "/Pictures/" + filename );
FileOutputStream out = new FileOutputStream(dir);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
out.write(bos.toByteArray());
Toast.makeText(getApplicationContext(), "Save card!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
error line
View v2 = findViewById(R.id.layout);
about import
package com.example.mye_card;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
The problem probably is because you can't find the ID at the point of the context inside a onClick event.
Go on the top of your .java file, just after the starting of your Class, you probably will see some variables, so create a new variable:
View vDrawing = null;
Then, search for your onCreate method, and declare your variable:
vDrawing = (View) findViewById(R.id.layout);
Now, remove your declaration findViewById() from your onClick event and just use your variable previously declared vDrawing instead of using your v2 variable.

Disable back button in Android(Not working)

package com.my.app ;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import com.my.app .R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageInfo extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImage = (ImageView) findViewById(R.id.camera_image);
//1
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
if(requestCode == CAMERA_PIC_REQUEST){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File("data/data/com.my.app /photo.jpg");
File myDir=new File("data/data/com.my.app /");
try {
String encodedPhotoImage;
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
deleteLatest() ;
byte[] photoImgBytes=readPhotoFile();
ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
Bitmap bitmapPhoto = BitmapFactory.decodeByteArray(photoImgBytes, 0, photoImgBytes.length);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100,bao1);
byte[] by = bao1.toByteArray();
String by1 = Base64.encodeToString(by, 0);
encodedPhotoImage = URLEncoder.encode(by1);
file.delete();
if (!myDir.exists()) {
myDir.mkdirs();
}
File encryptedFile=new File("data/data/com.my.app /photo.txt");
encryptedFile.createNewFile();
FileWriter writer = new FileWriter(encryptedFile);
writer.append(encodedPhotoImage);
writer.close();
//Base64.encodeToString(ba1, Base64.DEFAULT);
Intent intent=new Intent(ImageInfo.this,Info.class);
startActivity(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private byte[] readPhotoFile(){
String url="data/data/com.my.app /photo.jpg";
Log.e("","Image is"+url);
Bitmap bm = BitmapFactory.decodeFile(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return b;
}
#Override
public void onBackPressed() {
// do nothing.
}
private void deleteLatest() {
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
File [] files = f.listFiles();
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return 1;
} else {
return 0;
}
}
});
files[0].delete();
}
}
This is my java file. I have already disabled the back button using
public void onBackPressed() {
// do nothing.
}
But when back button is pressed in the app, the entire screen becomes black. Please find screen shot . The app hangs and the only way it can be accessed by terminating it through task manager and then restarting it.
try this code for disable back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
Capture Image from Camera and Display in Activity
I can't see a problem with your back button disabling. But there is another problem that may cause a part of this issue you are doing File IO in the UI Thread of your App.
Android has one UI Thread that does all the painting of your UI. If you block this thread through writing large files to the disk or reading bitmaps from the disk the phone UI will freeze and not react on user input until the heavy work is done.
I recommend to read this article on responsiveness to learn more about not blocking the UI Thread.
You can intercept the BackButton inside your own App, ONLY! As I see, you are starting some kind of CameraApp, that should pick a picture for you. You have NO control over the CameraActivity's BackButton. Your screen Has an ImageView, but you never set a Bitmap to it.
The disabling of the BackButton works, as you could NOT go out of your screen and have to "kill" it via a TaskManager. The BackButton has no functionality inside your Activity.

Categories

Resources