finish() method not finishing the activity - java

I am trying to come back to the Main Activity after taking a picture.
However, the finish() method is not taking me back to the Main Activity. Here is my code.
protected void takePicture() {
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
picture = bytes;
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(bytes);
} finally {
if (null != output) {
output.close();
}
}
}
};
} catch (CameraAccessException e) {
e.printStackTrace();
}
while(picture == null);
sendImage(picture);
finish();
}
private void sendImage(byte[] bytes) {
Intent i = new Intent();
i.putExtra("picture", bytes);
setResult(1, i);
}
If I run this code, the result picture is not null, but the Activity does not finish. If I comment out the line with
while(picture == null);
the resulting picture is null but the activity finishes at the end of the method. I want to have both the picture not be null and the Activity to finish. Any help would be greatly appreciated;

Related

download image from unformatted url [duplicate]

This question already has answers here:
How to download and save an image in Android
(10 answers)
Closed 3 years ago.
I want to download an image from url. if the url does not have an image format at the end of the link? Example of url:
https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1937530436393797&height=200&width=200&ext=1579152762&hash=AeQEq164H_oXIMjx
Try this code :
Create LocalImageSaver.java :
public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {
private final SaveCompletionInterface saveCompletionInterface;
private final String originalImageUrl;
private final Context context;
private String savedImagePath;
private String fUrl;
public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
this.context = context;
this.saveCompletionInterface = saveCompletionInterface;
this.originalImageUrl = originalImageUrl;
}
/**
* Downloading file in background thread
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Boolean doInBackground(Void... f_url) {
this.fUrl = originalImageUrl;
FileOutputStream output = null;
InputStream is = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fUrl);
HttpContext context = new BasicHttpContext();
HttpResponse response = client.execute(get, context);
is = response.getEntity().getContent();
int status = response.getStatusLine().getStatusCode();
if (status == 200 && is != null) {
String imageNameToSave;
String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
if (extension.contains("mp4")) {
extension = "mp4";
}
String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("/") + 1); // Without dot jpg, png
fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
imageNameToSave = fileName;
Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
savedImagePath = savedImagePathUri.getPath();
// Output stream to write file
output = new FileOutputStream(savedImagePathUri.getPath());
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
// flushing output
output.flush();
// closing streams
output.close();
is.close();
return true;
}
} catch (ClientProtocolException e) {
Lg.printStackTrace(e);
} catch (IOException e) {
Lg.printStackTrace(e);
} catch (Exception e) {
Lg.printStackTrace(e);
} finally {
// flushing output
try {
if (output != null) {
output.flush();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
saveCompletionInterface.onSaved(result, savedImagePath);
}
public interface SaveCompletionInterface {
public void onSaved(boolean result, String imageNameToSave);
}
}
and call this :
LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
#Override
public void onSaved(boolean result, String savedImagePath) {
if (result) {
//showToast(getActivity(), (R.string.image_save_succesfull));
// refresh gallery
try {
MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}
} else {
//showToast(getActivity(), (R.string.error_saving_image));
}
}
});
localImageSaver.execute();

Using Java itextPdf pdf file is not being printed in android

I am writing a mobil application which contains Dynamic Report part. I'm making it with Java ItextPdf Library but when I sent it to printer printer don't accept my file and giving a notification "File Type is not supported by this device." But When I send normal pdf file which is created by pc it is printing.
Printing Class
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
File path = context.getFilesDir();
File file = new File(path,"ss.pdf");
FileOutputStream os = null;
FileInputStream is = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Adisyon a = new Adisyon(os);
a.createFile();
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
printManager.print(jobName, new printAdapter(Siparis.this,is),
PrintAdapter Class
#TargetApi(Build.VERSION_CODES.KITKAT)
public class printAdapter extends PrintDocumentAdapter
{
Context context;
InputStream input;
public printAdapter(Context context,FileInputStream input)
{
this.context = context;
this.input = input;
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
OutputStream output = null;
try {
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("deneme.txt").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
}
Itext Class
public class Adisyon {
FileOutputStream stream;
Context appContext = LoginActivity.getContextOfApplication();
public Adisyon(FileOutputStream stream) {
this.stream = stream;
}
public void createFile() {
try {
Document document = new Document();
PdfWriter.getInstance(document, stream);
document.open();
//addMetaData(document);
//addTitlePage(document);
//addContent(document);
createAdisyon(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
...

trying to write to read and write to a text file in eclipse

I am trying to write and read to a text file name students but I am having all kinds of hassles I am very new to android programming so I am trying this out for the first time. I have looked at code here and there to try and figure out what I am doing wrong but I cant find one specific thing to help, this question has probably been asked a couple of times, so I am sorry for asking it again. Please see my different .xml and .java files below. The actual question is to be able to write data to a textfile and from the main screen click on a textfield which will take you to the edit screen, where you get to edit that specific field and save it to a text file (this however has not been done yet as I am still struggling to figure out why my writing and reading to the textfile is not working, I hope my poor attempt at coding will shed some light on the matter.
Please don't crucify me for my bad coding I am super new to android
/////////////////////////////add screen.java///////////////////////////////
public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText;
EditText Modules;
EditText Types;
#Override
protected void onCreate(Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.add);
txtText = (TextView)findViewById(R.id.textView1);
Modules = (EditText)findViewById(R.id.etMod);
Types = (EditText)findViewById(R.id.etType);
Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(AddNew.this, MainActivity.class));
}
}); //end back Button
//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();
txtText.setText("TEST");
Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
try {
writeToFile(Modules.getText().toString(),
Types.getText().toString(),dobStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void writeToFile(String Mod, String AsType, String dobDate) throws
IOException {
// TODO Auto-generated method stub
//String textTofile;
StringBuilder sbText = new StringBuilder();
sbText.append(Mod + "," + dobStr + "," + AsType);
//textTofile=sbText.toString();
String fileName = "student";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName,
true));
printWriter.write(newLine ); //+textTofile);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
}); //end back Button
}
}
`public class MainActivity extends Activity {
TextView fDisplay;
TextView fTest;
int numItems=0; //use it later to keep track of the number of items.
String inText; //use this variable for the information read in from the textfile.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.btnAdd);
but1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, AddNew.class));
}
}); //end but1
Button but2 = (Button)findViewById(R.id.btnEditCur);
but2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, EditCur.class));
}
}); //end of button 2
fDisplay = (TextView)findViewById(R.id.tvAssign1);
try {
readFromFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readFromFile() throws IOException {
// TODO Auto-generated method stub
// String ret="";
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("student");
br = new BufferedReader(fr);
String line = br.readLine();
while (null != line) {
fDisplay.append(line);
fDisplay.append("\n");
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
`
For writting on a file I have used this
String filename;
String content;
filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write(myString.toString());
out.flush();
out.close();
And for reading I have this function:
public static String readFileAsString() {
String result = "";
String filename;
filename = "PATH_AND_FILE";
File file = new File(filename);
if ( file.exists() ) {
FileInputStream fis = null;
try { fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
// System.out.println("DEBUG Exception String :"+ e.toString());
} finally {
if (fis != null)
{ try {
fis.close();
} catch (IOException ignored) {
}}
else {// System.out.println("DEBUG Exception String NULL");
}
}
return result;
}
else
{
return "DEFAULT CONTENT";
}
}
In Android, the file' directory is different then that on a PC, like :the files are stored in a directory related to your App, the accessing permissions are different.
This link might be helpful:
How To Read/Write String From A File In Android
Two simple functions (Java) to read and write:
private static void writeToFile(String path, String text) {
PrintWriter writer;
try {
writer = new PrintWriter(path, "UTF-8");
writer.print(text);
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFileContent(String filename){
String everything = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
everything = sb.toString();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return everything;
}

getting blank pdf on implementing pdf reader in project

i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");

Why on double click android client received data?

When I click the first time on login button, data send to server and server received data in return on first click data not show on android client screen. When I pressed login button again it again send data and then it show data on client screen... plz help me. Why data is received on secind click i want my data recived on my first click?
Here is the code :
Client tcpip code...
public class SockProg {
private Socket socket;
DataOutputStream dataOutputStream;
DataInputStream dataInputStream;
String data;
String serverip = "192.168.1.7";
int serverport = 4444;
public void connetToServer(){
try {
socket = new Socket(serverip, serverport);
Log.i("AsyncTank", "doInBackgoung: Created Socket");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (socket.isConnected()) {
try {
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeToStream(String message) {
try {
if (socket.isConnected()){
dataOutputStream.writeUTF(message.toString());
} else {
Log.i("AsynkTask", "writeToStream : Cannot write to stream, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
}
public String readFromStream() {
String ret = null;
try {
if (socket.isConnected()) {
Log.i("AsynkTask", "readFromStream : Reading message");
ret=dataInputStream.readUTF();
Log.i("AsynkTask", "readFromStream : read "+ret);
} else {
Log.i("AsynkTask", "readFromStream : Cannot Read, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "readFromStream : Reading failed"+e.getClass());
}
return ret;
}
public void CloseSockets(){
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
here is the code of sychronized thread
public class TCP implements Runnable {
String data;
SockProg sp;
Thread thh;
private static String rdata;
public TCP(SockProg spr, String val) {
sp = spr;
data = val;
thh = new Thread(this);
thh.start();
}
#Override
public void run() {
synchronized(sp) { // synchronized block
//rdata= sp.DataSendRecive(data);
sp.connetToServer();
sp.writeToStream(data);
rdata=sp.readFromStream();
sp.CloseSockets();
}
}
public static String getData(){
return rdata;
}
}
here is code of Login Activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
msg = (TextView) findViewById(R.id.msg_log);
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// try{
txtph = (EditText) findViewById(R.id.txt_phnum);
txtpass = (EditText) findViewById(R.id.txt_pass);
ph = txtph.getText().toString();
pass = txtpass.getText().toString();
int ch = 0;
if (ph.equals("") || ph == null) {
msg.setText("Please Enter Mobile Number....\n");
ch++;
}
if (pass.equals("") || pass == null) {
if (ch == 0) {
msg.setText("Please Enter your Password....\n");
} else {
msg.append("Please Enter your Password....\n");
}
ch++;
}
if (ch == 0) {
ArrayList<String> ph_pass = new ArrayList<String>();
ph_pass.add(0, "LoginAccount");
ph_pass.add(1, ph);
ph_pass.add(2, pass);
SockProg sp=new SockProg();
TCP t=new TCP(sp, ph_pass.toString());
data=t.getData();
msg.setText(data);
}
}
});
}
This looks like a classic case of asynchronous coding delay. The TCP class is a runnable and therefor when it is called the first time (the first click on the login button) it starts running, but the Thread does not have enough time to finish
rdata=sp.readFromStream();
in the run() method, therefor data=t.getData(); does not return anything useful. The second click, provides the runnable with enough time populate the rdata with some data and therefor your program works.
When working with asynchrounous code, you need a better way to wait for code to complete what it is doing.
Why is rdata a static type? Make it non-static and then change the getData() method like this:
public synchronized String getData()

Categories