Main Java Activity:
TList tl = new TList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
public void AddmyCostumObj_buttonclik(View view) {
Intent intent = new Intent(this, AddActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle T = data.getExtras();
String new_myCostumObj_s = myCostumObj.myCostumObj_getString("ret");
myCostumObj new1 = new myCostumObj();
new1.string_to_myCostumObj(new_myCostumObj_s);
tl.add_myCostumObj(new1);
}
}
#Override
protected void onStart() {
super.onStart();
FileInputStream fis;
try {
fis = openFileInput("data_tasks");
ObjectInputStream ois = new ObjectInputStream(fis);
tl = (TList) ois.readObject();
if (tl == null) tl = new TList(); // it sometimes gave nullPointer
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
FileOutputStream fos;
try {
fos = openFileOutput("data_tasks", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tl);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Add Java Activity:
// creates a new myCostumObj
public void add_buttonclick(View view){
Intent intent = new Intent();
Bundle T = new Bundle();
T.putString("ret", myCostumObj.myCostumObj_toString());
intent.putExtras(T);
setResult(RESULT_OK, intent);
finish();
}
What does the main activity do first on restart? Does it do the expected thing and read form the file the tl and than add the myCostumObj from the bundle? If so, than what am I doing wrong, because the tl is always appearing empty.
Related
I want to make an application that allows me to choose a file from SDcard (.apk file), then send it by HTTP Post to a web service.
The problem is that even if I can choose the file, I can't convert it in a byte array because my application is looking for it in its private folders, not in SDcard.
I used Intent to access to FileManager and choose a file from storage. Then, a toast notification shows me its path.
public class MainActivity extends AppCompatActivity {
Button button1;
Intent intent;
String PathHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
PathHolder = data.getData().getPath();
File file = new File(PathHolder);
String FileName = file.getName();
Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
try {
byte[] bArray = new byte[(int) file.length()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
}
After
FileInputStream inputStream = new FileInputStream(f);
My application throws an Exception and the response is :
File Not Found
The variable f, on which you are constructing the FileInputStream of is never assigned or am I wrong? I think you should change f to file.
I am using this two functions to open the image gallery and to choose a picture. I have the uri of the picture and the picture itself in "inputStream".
My question is how can I move the picture or to copy it in the folder drawable from android studio ?
public void onImageGalleryClicked(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY_REQUEST)
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
} catch (FileNotFoundException e) {
e.printStackTrace()
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
I would have done it like below:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
Long tsLong = System.currentTimeMillis();
String now = tsLong.toString();
String destitaion =folderPath+"/"+now+".jpg";
savefile(imageUri.getPath(),destitaion);
}
}
}
void savefile(String sourceFilename,String destinationFilename)
{
//String sourceFilename= sourceuri.getPath();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
boolean exp_occuered=false;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
exp_occuered=true;
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!exp_occuered)
{
//the image has been saved properly
}
}
New in Android and
Working on an app like This
At the end got the problem java.io.FileNotFoundException: /document/86: open failed: ENOENT (No such file or directory)
Now I'm working on the solution that
"That how to use ContentResolver and openInputStream()"
Anyone help me how to do this, please
if you trying to make an app that read a file from Phone
Try This
Try this may help
private InputStream getResources(String s) {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, 7);
Log.v("###", "parent " + getParent());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri PathHolder = data.getData();
Log.v("###", "yo " + PathHolder);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setContentView(R.layout.activity_main);
try {
InputStream inputStream = getContentResolver().openInputStream(PathHolder);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String mLine;
while ((mLine = r.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
After I take a picture I store the picture into ImageView, So if anyone has an idea or suggestion in how to store the picture after it shown on the ImageView into phone stage without user interaction
Thanks in advance
public class MainActivity extends Activity {
ImageView viewpict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpict=(ImageView) findViewById(R.id.pict_result);
Button btn= (Button)findViewById(R.id.camera);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent (getApplicationContext(),MainActivity2.class);
//startActivity(intent);
startActivityForResult(intent,0);
}
});
}
protected void onActivityResult( int requestCode, int resultCode,Intent data)
{
if (requestCode==0)
{
Bitmap theimage = (Bitmap) data.getExtras().get("data");
viewpict.setImageBitmap(theimage);
}
}
}
Try:
viewpict.buildDrawingCache();
Bitmap bm=viewpict.getDrawingCache();
And save:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
And permission in AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My toast doesn't show up and I am confused because I think I made it correctly, I don't understand. As you can see its a program that shows three buttons, the first one activates a download which is supposed to open the PDFs file automatically - if there is no pdf reader a toast should pop up saying there isn't a reader. the other buttons take to a new screen and operate as a back button.
public class myactivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mProgressDialog = new ProgressDialog(myactivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button Section = (Button) findViewById(R.id.Section);
Section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent Section = new Intent(view.getContext(),
Section.class);
startActivity(Section);
}
});
Button Back = (Button) findViewById(R.id.Back);
Back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
startBtn = (Button) findViewById(R.id.Search);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/document.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
The above code show toast only if you have not declared the activity in your manifeast file but not when the pdf is not present. You must use FileNotFoundException for your requirement.
Updated:::
try{
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}