Not able to share a file (via Gmail or Google Drive) - android

I have the following code to share a file.
It all seems to work fine,
Gmail opens with the attachment attached,
but when I click SEND Gmail stops and gives an error Unfortunately Gmail has stopped
The same with Google Drive, all seems to work fine but in the end I get:
Upload failed by Google drive.
Any help very much appreciated!!!
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fileuri=Utility.downloadDb(MainActivity.this);
if(fileuri!=null){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_STREAM, fileuri);
startActivity(sharingIntent);
}
}
});
Where Utility.downloadDb(MainActivity.this);
is:
public static Uri downloadDb(Context context) {
DatabaseHandler db= new DatabaseHandler(context);
ArrayList<Word> list=new ArrayList<Word>();
Uri fileuri=null;
list.clear();
list.addAll(db.getAllWords());
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "db.csv");
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// Make sure the Pictures directory exists.
path.mkdirs();
FileWriter outFile = new FileWriter(file);
PrintWriter out = new PrintWriter(outFile);
out.print("PICTURE NAME");
out.print(",");
out.print("WORD NUMBER");
out.print(",");
out.print("LEFT");
out.print(",");
out.print("TOP");
out.print(",");
out.print("RIGHT");
out.print(",");
out.println("BOTTOM");
for(int i=0;i<list.size();i++){
out.print(list.get(i).pic);
out.print(",");
out.print(Integer.toString(list.get(i).wordno));
out.print(",");
out.print(Integer.toString(list.get(i).beginx));
out.print(",");
out.print(Integer.toString(list.get(i).beginy));
out.print(",");
out.print(Integer.toString(list.get(i).endx));
out.print(",");
out.println(Integer.toString(list.get(i).endy));
}
out.close();
Toast.makeText(context, "SAVED TO: " +file.getAbsolutePath(), Toast.LENGTH_LONG).show();
fileuri=Uri.parse(file.getAbsolutePath());
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.e("ExternalStorage", "Error writing " + file, e);
}
return fileuri;
}

Solution found!!!!
I think this might be useful for other people as well!!!
to get the URI use:
fileuri=Uri.fromFile(file);
NOT
fileuri=Uri.parse(file.getAbsolutePath());

Related

Programmatically Downloading and Installing APK [duplicate]

This question already has answers here:
Android: install .apk programmatically [duplicate]
(4 answers)
Closed 5 years ago.
I've seen a few answers related to this but can't quite seem to find what I'm looking for. Say I have a self hosted app. Now say I've made some changes to that app and would like to let the user know within the app that there is an update available. I can get the app to successfully download the apk file and begin installing it. After the installation is "finished" the app closes out. When I restart the app none of the changes I've made have been applied. So it appears the installation has failed, but there was no apparent crash. However, when I install the apk that was downloaded from the Downloads manager it installs just fine and the changes I have made are applied. Any ideas? Here is the section of code I use to download and install programmatically:
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "TheApp.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
String url = "myapplocation";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading necessary update files.");
request.setTitle("Updating The App");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivityForResult(install, 0);
unregisterReceiver(this);
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Get VersionName and VersionCode for current Running application.
code:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
Common.VersionName = pInfo.versionName;
Common.VersionCode = pInfo.versionCode;
Log.e("VersionCode", ">>>>>>>>>>" + Common.VersionCode + Common.VersionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
**Check the Version Names**
if (!Common.VersionName.equals(Common.VersionNamefromWebApi)) {
AlertDialogUpdate(MakeTransactionActivity.this, Common.AppUpdateTitle, "YokoYepi Version" + Common.VersionNamefromWebApi + " available.");
}
**Alert Dialog Box**
public void AlertDialogUpdate(Activity activity, String title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setCancelable(false);
if (title != null) builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new DownloadNewVersion().execute();
dialog.dismiss();
}
});
builder.show();
}
**Download and Install the .apk file from URL**
class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(MakeTransactionActivity.this);
bar.setCancelable(false);
bar.setMessage("Downloading...");
bar.setIndeterminate(true);
bar.setCanceledOnTouchOutside(false);
bar.show();
stoptimertask();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgress(progress[0]);
String msg = "";
if (progress[0] > 99) {
msg = "Finishing... ";
} else {
msg = "Downloading... " + progress[0] + "%";
}
bar.setMessage(msg);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
startTimer();
bar.dismiss();
if (result) {
Toast.makeText(getApplicationContext(), "Update Done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error: Try Again",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
try {
String PATH;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
PATH = Environment.getExternalStorageDirectory() + "/Download/";
} else {
PATH = Environment.getDataDirectory() + "/Download/";
}
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yokoyepi.apk");
if (outputFile.exists()) {
outputFile.delete();
}
// Download File from url
URL u = new URL(Common.AppUpdateURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
// Install dowloaded Apk file from Devive----------------
OpenNewVersion(PATH);
flag = true;
} catch (MalformedURLException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (IOException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (Exception e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(location + "yokoyepi.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// if your not install u should call the function in onResume().
// again it will check whether apk updated or not.

Use same method for all option menu in whole Application Android

I have 10 to 12 Activity, All Activity has Help Menu as an Option Menu.
I am succeed with following code to create it and showing help on click of them.
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(cacheDir, "HELP.pdf")),"application/pdf");
context.startActivity(intent);
But I want to Reduce this code for all Activity, and for that i have created one class and make one method but still i want to reduce code.
I have searched and found that onClick attribute is available in OptionMenu but I didn't get how to use it.
Please Help..
Create a class, for example call it Helper, where you put a method called handleMenu(int id) and where you do all the work. Then, in every activity you call that method from onOptionsItemSelected(), passing the id of the item selected.
I have created following Class for openFile:
public class OpenHelpFile {
File cacheDir;
Context context;
/* Constructor */
public OpenHelpFile(Context context) {
this.context = context;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "OOPS");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
try {
File helpFile = new File(cacheDir, "OOPS.pdf");
if (!helpFile.exists()) {
InputStream in = context.getAssets().open("OOPS.pdf");
OutputStream out = new FileOutputStream(helpFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(TAG, "File Copied...");
}
Log.d(TAG, "File exist...");
} catch (FileNotFoundException ex) {
Log.d(TAG, ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
public void openHelpFile() {
/* OPEN PDF File in Viewer */
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(cacheDir, "OOPS.pdf")), "application/pdf");
context.startActivity(intent);
}
}
and I have call it from every OptionMenu like this:
new OpenHelpFile(context).openHelpFile();

ftp file download result in black screen

I am downloading a file from ftp server. downloading code worked fine, however after download code screen doesn't show anything ,it gets black. Also download function is not returning true value, even the file is being saved in the specified directory.
public class FTPClass{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_player);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Intent intent = getIntent();
dirname = intent.getStringExtra("currentDirName");
MyFTPClient mftp = new MyFTPClient();
createPath = mftp.getAppRootPath().concat("/"+ dirname);
mftp.setCurrentDir(createPath);
System.out.println(mftp.ftpChangeDirectory(createPath));
FTPFile[] farr = mftp.ftpListAllFiles();
System.out.println(farr.length);
for(int i = 0; i<farr.length;i++){
System.out.println("SRC: "+createPath+"/"+farr[i].getName());
String src = createPath+"/"+farr[i].getName();
System.out.println("DEST: "+"/data/data/com.example.ftpplayer" + "/app_"+dirname);
String dest ="/data/data/com.example.ftpplayer" + "/app_"+dirname+"/"+farr[i].getName();
System.out.println(mftp.downloadFile(src,dest));
}
}
}
public class CallingIntent extends Activity{
System.out.println("In item click ");
Intent intent = new Intent(getApplicationContext(), FTPClass.class);
String dir = ((TextView) view).getText().toString();
intent.putExtra("currentDirName", dir);
startActivity(intent);
}
public class MyFTPClient{
public boolean downloadFile(String srcPath , String destPath){
try {
FileOutputStream fos = new FileOutputStream(destPath);
System.out.println(mftp.retrieveFile(srcPath, fos)); // retrieve file doesn't return true
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return false;
}
}
You need to run your code on the background thread, try using an asyncTask.

screenshot is blank on android

I'm taking a screenshot from a layout that have a videoview, I have this code to save it, and to capture it, but when I open it I have a blank image but not an empty the image have 1.5Kb, can you help me?
this is how I capture the screenshot
public void TakePic(View v){
buton = AnimationUtils.loadAnimation(this, R.anim.but);
v.startAnimation(buton);
if (vid!=null)
{
if(vid.getCurrentPosition()!=0)
{
popupc = (LinearLayout) findViewById(R.id.guardapic);
popupc.setVisibility(View.VISIBLE);
LinearLayout layout = (LinearLayout)findViewById(R.id.videopic);
layout.setDrawingCacheEnabled(true);
layout.setDrawingCacheQuality(LinearLayout.DRAWING_CACHE_QUALITY_HIGH);
layout.buildDrawingCache();
bitmap = layout.getDrawingCache();
im=(ImageView)findViewById(R.id.imgdown);
// im.setImageResource(R.drawable.play_amarelo);
im.setImageBitmap(bitmap);
}
else
{
Toast toast = Toast.makeText(ctx,"Video has stopped...Restart", Toast.LENGTH_SHORT);
toast.show();
}
}
else
{
Toast toast = Toast.makeText(ctx,"Start video first", Toast.LENGTH_SHORT);
toast.show();
}
}
this is the code to save it into the sdCard
public void PicOk(View v){
String pathpic=null;
String nomepic=null;
EditText path= (EditText)findViewById(R.id.picpath);
EditText pic= (EditText)findViewById(R.id.nomepic);
pathpic=path.getText().toString();
nomepic=pic.getText().toString();
File folder = new File(Environment.getExternalStorageDirectory() + "/"+pathpic);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (!success) {
Log.d("Lino"," Pasta nao criada");
} else {
FileOutputStream ostream;
try {
File file = new File(folder.toString() + "/"+nomepic+ ".png");
ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 95, ostream);
ostream.flush();
ostream.close();
// ((LinearLayout)findViewById(R.id.VV2)).destroyDrawingCache();
} catch (FileNotFoundException e) {
Log.d("Lino","erro"+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("lino","erro "+e.toString());
e.printStackTrace();
}
}
popupc = (LinearLayout) findViewById(R.id.guardapic);
popupc.setVisibility(View.GONE);
bitmap=null;
//tira foto
Toast toast = Toast.makeText(ctx,"pick taked", Toast.LENGTH_SHORT);
toast.show();
}
You know the video is actually Combination of Still Images. The moment when you take the picture the cross-ponding frame is blank. That is why screenshot appears to be black/blank.
So with this method you can't take the screen shot of a video. You need to adopt a different approach.
May be it helps you.

How to populate a test database in Android?

I have a test class that extends ProviderTestCase2<>.
I would like to populate this test class database with data from some .db files.
Is there some particular method to push some .db file into the Mock Context of a ProviderTestCase2?
Otherwise which way is the easier to populate the database from the .db file?!
Thank you very much!!
How about copying in a pre-existing .db file from the SD Card or something similar? This is a quick piece of code that will accomplish this for you:
private void importDBFile(File importDB) {
String dataDir = Environment.getDataDirectory().getPath();
String packageName = getPackageName();
File importDir = new File(dataDir + "/data/" + packageName + "/databases/");
if (!importDir.exists()) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
return;
}
File importFile = new File(importDir.getPath() + "/" + importDB.getName());
try {
importFile.createNewFile();
copyDB(importDB, importFile);
Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
}
}
private void copyDB(File from, File to) throws IOException {
FileChannel inChannel = new FileInputStream(from).getChannel();
FileChannel outChannel = new FileOutputStream(to).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Hopefully this will work for your scenario

Categories

Resources