I am Newbie to Android.
I have tried all the posts in this forum. But could not get the success.
I am trying to share an mp3 file from asset folder to whatsapp.
Below is my code.
This is my Code in Main Activity:
package com.example.sharedemo;
import com.example.sharedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button sharebutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharebutton = (Button) findViewById(R.id.sharebutton1);
sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri theUri = Uri.parse("content://com.example.sharedemo.Assetsprovider/gotShocked.mp3");
Intent theIntent = new Intent(Intent.ACTION_SEND);
theIntent.setType("audio/mp3");
theIntent.setPackage("com.whatsapp");
theIntent.putExtra(Intent.EXTRA_STREAM,theUri);
startActivity(Intent.createChooser(theIntent,"Share using"));
}
});
}
}
Code in ContentProvider:
package com.example.sharedemo;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public class Assetsprovider extends ContentProvider {
#Override
public AssetFileDescriptor openAssetFile( Uri uri, String mode ) throws FileNotFoundException
{
AssetManager am = getContext( ).getAssets( );
String file_name = uri.getLastPathSegment( );
// String file_name = uri.getPath();
if( file_name == null )
throw new FileNotFoundException( );
AssetFileDescriptor afd = null;
try
{
afd = am.openFd(file_name);
}
catch(IOException e)
{
e.printStackTrace( );
}
return afd;//super.openAssetFile(uri, mode);
}
#Override
public String getType( Uri p1 )
{
// TODO: Implement this method
return null;
}
#Override
public int delete( Uri p1, String p2, String[] p3 )
{
// TODO: Implement this method
return 0;
}
#Override
public Cursor query( Uri p1, String[] p2, String p3, String[] p4, String p5 )
{
// TODO: Implement this method
return null;
}
/* #Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal )
{
// TODO: Implement this method
return super.query( uri, projection, selection, selectionArgs, sortOrder, cancellationSignal );
}*/
#Override
public Uri insert( Uri p1, ContentValues p2 )
{
// TODO: Implement this method
return null;
}
#Override
public boolean onCreate( )
{
// TODO: Implement this method
return false;
}
#Override
public int update( Uri p1, ContentValues p2, String p3, String[] p4 )
{
// TODO: Implement this method
return 0;
}
}
Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Assetsprovider"
android:label="#string/app_name" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.example.sharedemo.Assetsprovider"
android:authorities="com.example.sharedemo.Assetsprovider"
android:grantUriPermissions="true"
android:exported="true" />
</application>
</manifest>
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///"+mypath));
startActivity(Intent.createChooser(share, "Share Sound File"));
break;
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
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);
}
}```
Related
I want to run a Backgroundservice (FileObserver) that will look for any filechanges in the system (CREATE, DELETE, MOVE, ...).
When I start my application it works a few seconds and logs everything fine. For example at taking a picture by the camera it logs that. After a few seconds the service is still listed in Settings => Developer Options => Running Services but does not work and log anything anymore.
Android Version: 7.0
Device: Samsung Galaxy S7 Edge
I copied the code from Niza Siwale's answer here 1:1 and added only the Logs like that :
How to monitor folder for file changes in background?
#Override
public void onEvent(int event, final String path) {
if (event == FileObserver.OPEN) {
Log.v("Event: ", "Open" + path);
} else if (event == FileObserver.CREATE && (!path.equals(".probe"))) {
Log.v("Event: ", "Create" + path);
} else if (event == FileObserver.DELETE_SELF || event == FileObserver.DELETE) {
Log.v("Event: ", "Delete" + path);
} else if (event == FileObserver.MOVE_SELF || event == FileObserver.MOVED_FROM || event == FileObserver.MOVED_TO) {
Log.v("Event: ", "Move" + path);
}
}
Why is the service running in background (as I can see in Running Services) but not donig any logs, if something changes in the filesystem?
Full Code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spicysoftware.phonesaver">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!-- Adding the permission -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service
android:name=".FileSystemObserverService"
android:enabled="true"
android:exported="true" >
</service>
<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".StartupReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.spicysoftware.phonesaver;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String TAG = "Log: ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isReadStoragePermissionGranted()){
Intent myIntent = new Intent(this, FileSystemObserverService.class);
this.startService(myIntent);
}
}
public boolean isReadStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted1");
return true;
} else {
Log.v(TAG,"Permission is revoked1");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 3);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted1");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 3:
Log.d(TAG, "External storage1");
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
}else{
}
break;
}
}
}
FileSystemOberveService
package com.spicysoftware.phonesaver;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class FileSystemObserverService extends Service {
String externalPath = "";
String internalPath = "";
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
observe();
return super.onStartCommand(intent, flags, startId);
}
public File getInternalStoragePath() {
File parent = Environment.getExternalStorageDirectory().getParentFile();
File external = Environment.getExternalStorageDirectory();
File[] files = parent.listFiles();
File internal = null;
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].getName().toLowerCase().startsWith("sdcard") && !files[i].equals(external)) {
internal = files[i];
}
}
}
return internal;
}
public File getExtenerStoragePath() {
return Environment.getExternalStorageDirectory();
}
public void observe() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
//File[] listOfFiles = new File(path).listFiles();
File str = getInternalStoragePath();
if (str != null) {
internalPath = str.getAbsolutePath();
new Obsever(internalPath).startWatching();
}
str = getExtenerStoragePath();
if (str != null) {
externalPath = str.getAbsolutePath();
new Obsever(externalPath).startWatching();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
class Obsever extends FileObserver {
List<SingleFileObserver> mObservers;
String mPath;
int mMask;
public Obsever(String path) {
// TODO Auto-generated constructor stub
this(path, ALL_EVENTS);
}
public Obsever(String path, int mask) {
super(path, mask);
mPath = path;
mMask = mask;
// TODO Auto-generated constructor stub
}
#Override
public void startWatching() {
// TODO Auto-generated method stub
if (mObservers != null)
return;
mObservers = new ArrayList<SingleFileObserver>();
Stack<String> stack = new Stack<String>();
stack.push(mPath);
while (!stack.empty()) {
String parent = stack.pop();
mObservers.add(new SingleFileObserver(parent, mMask));
File path = new File(parent);
File[] files = path.listFiles();
if (files == null) continue;
for (int i = 0; i < files.length; ++i) {
if (files[i].isDirectory() && !files[i].getName().equals(".") && !files[i].getName().equals("..")) {
stack.push(files[i].getPath());
}
}
}
for (int i = 0; i < mObservers.size(); i++) {
mObservers.get(i).startWatching();
}
}
#Override
public void stopWatching() {
// TODO Auto-generated method stub
if (mObservers == null)
return;
for (int i = 0; i < mObservers.size(); ++i) {
mObservers.get(i).stopWatching();
}
mObservers.clear();
mObservers = null;
}
#Override
public void onEvent(int event, final String path) {
if (event == FileObserver.OPEN) {
Log.v("Event: ", "Open" + path);
// makeToast("Opened: "+path);
} else if (event == FileObserver.CREATE && (!path.equals(".probe"))) {
Log.v("Event: ", "Create" + path);
// makeToast("Created: "+path);
} else if (event == FileObserver.DELETE_SELF || event == FileObserver.DELETE) {
Log.v("Event: ", "Delete" + path);
// makeToast("Deleted: "+path);
} else if (event == FileObserver.MOVE_SELF || event == FileObserver.MOVED_FROM || event == FileObserver.MOVED_TO) {
Log.v("Event: ", "Move" + path);
// makeToast("Moved: "+path);
}
}
private class SingleFileObserver extends FileObserver {
private String mPath;
public SingleFileObserver(String path, int mask) {
super(path, mask);
// TODO Auto-generated constructor stub
mPath = path;
}
#Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
String newPath = mPath + "/" + path;
Obsever.this.onEvent(event, newPath);
}
}
}
/*
public void makeToast(final String strMessage){
//Let this be the code in your n'th level thread from main UI thread
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), strMessage, Toast.LENGTH_SHORT).show();
}
});
}
*/
}
StartupReceiver
package com.spicysoftware.phonesaver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, FileSystemObserverService.class);
context.startService(myIntent);
}
}
I am trying to integrate Dropbox with android application using Dropbox API using this tutorial. My code compiles fine with no error. But when I try to download the file from Dropbox, I only receive an empty file. To me it seems that its not interacting with dropbox. Could you please have a look at my code. I am posting all my files. Thank you so much.
APP : My Application
MainActivity.java file:
package com.tutorialspoint.myapplication;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AppKeyPair;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
public class MainActivity extends ActionBarActivity {
public static Button button1;
public static Button button2;
public static Button button3;
public static Button button4;
public static TextView textView;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AAA_DB_Tutorials/" ;
public static File Dir = new File(path);
public void onClickBut1(View v)
{
UploadToDropboxFromPath(path + "testfile.txt", "db_tutorial/uploadFileFromPath.txt");
}
public void onClickBut2(View v)
{
UploadToDropboxFromSelectedApp("db_tutorial/UploadFilesFromSelectedApp");
}
public void onClickBut3(View v)
{
UploadToDropboxFromFilemanager(path + "testfile.txt");
}
public void onClickBut4(View v)
{
DownloadFromDropboxFromPath(path + "downloadFileFromDrobboxkkk","db_tutorial/uploadFileFromPath.txt" );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button3 = (Button)findViewById(R.id.button3);
button4 = (Button)findViewById(R.id.button4);
textView = (TextView)findViewById(R.id.textView);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "xxxxxx";
private static final String APP_SECRET = "xxxx";
private static final String ACCESSTOKEN = "xxxxxx";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession()
{
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath (String uploadPathFrom, String uploadPathTo)
{
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable()
{
public void run()
{
File tmpFile = null;
try
{
tmpFile = new File(uploadPathF);
}
catch (Exception e) {e.printStackTrace();}
FileInputStream fis = null;
try
{
fis = new FileInputStream(tmpFile);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
}
catch (Exception e) {}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp (String uploadName)
{
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager (String uploadName)
{
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath (String downloadPathTo, String downloadPathFrom)
{
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
MainActivity.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == UploadFromFilemanager)
{
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable()
{
public void run()
{
getMain().runOnUiThread(new Runnable()
{
#Override
public void run()
{
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp)
{
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if(DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable(){
public void run() {
try
{
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener(){
#Override
public long progressInterval() {return 100;}
#Override
public void onProgress(long arg0, long arg1){}
});
getMain().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {e.printStackTrace();}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if(s!=null) {
cursor.close();
return s;
}
}
catch(Exception e){}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if(s!=null) {
cursor.close();
return s;
}
}
catch(Exception e){}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public MainActivity getMain()
{
return this;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.tutorialspoint.myapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hellppppppo World!"
android:id="#+id/textView"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD WITH FIXED PATH"
android:id="#+id/button1"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD FROM SELECTED APP"
android:id="#+id/button2"
android:layout_below="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD FROM FILE MANAGER"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:onClick="onClickBut3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOWNLOAD"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut4"/>
</RelativeLayout>
build.gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.tutorialspoint.myapplication"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile files ('libs/json_simple-1.1.jar')
compile files ('libs/dropbox-android-sdk-1.6.3.jar')
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm trying to connect my app to online database, i have all the php files working, but my app don't connect to the database. I have to do simple data insertion and data retrieve. I Keep getting null pointer exception.
RegOneActivity.java
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegOneActivity extends Activity {
Button okaBtn,regbtn;
EditText phno,password;
String phone,pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_one);
password = (EditText) findViewById(R.id.passwordedittext);
okaBtn =(Button) findViewById(R.id.okbtn);
phno = (EditText) findViewById(R.id.editTextpass1);
regbtn = (Button) findViewById(R.id.createbtn);
regbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(RegOneActivity.this, PasswordActivity.class);
startActivity(in);
}
});
okaBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
phone = phno.getText().toString();
pass = password.getText().toString();
String method = "login";
/*RegisterBackgroung backGround = new RegisterBackgroung(getApplicationContext());*/
RegisterBackgroung backGround = new RegisterBackgroung(RegOneActivity.this);
backGround.execute(method, phone, pass);
Intent in = new Intent(RegOneActivity.this, MapActivity.class);
startActivity(in);
RegOneActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reg_one, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PasswordActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PasswordActivity extends Activity {
Button btn;
EditText password1,password2,phone;
String pass1,pass2,phonenumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
btn =(Button) findViewById(R.id.proceed1act);
password1 = (EditText) findViewById(R.id.editTextpass1);
phone = (EditText) findViewById(R.id.phoneedt);
password2 = (EditText) findViewById(R.id.editTextpass2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pass1 = password1.getText().toString();
pass2 = password2.getText().toString();
phonenumber = phone.getText().toString();
String method= "register";
RegisterBackgroung backtask = new RegisterBackgroung(PasswordActivity.this);
backtask.execute(method,phonenumber,pass1);
Intent in = new Intent(PasswordActivity.this, RegOneActivity.class);
startActivity(in);
PasswordActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.password, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RegisterBackground.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.widget.Toast;
public class RegisterBackgroung extends AsyncTask<String, Void, String>{
Context ctx;
AlertDialog diag;
SharedPreferences sp;
Editor edt;
public RegisterBackgroung(Context ctx) {
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String urlregister = "http://www.locationsharing.16mb.com/register.php";
String login = "http://www.locationsharing.16mb.com/retrieve.php";
String method = params[0];
if(method.equals("register"))
{
String phone = params[1];
String pass = params[2];
try {
URL reg_url = new URL(urlregister);
HttpURLConnection httpUrlConnection = (HttpURLConnection) reg_url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream os = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("phonenumber", "UTF-8")+"="+URLEncoder.encode(phone, "UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream is = httpUrlConnection.getInputStream();
is.close();
return "Registration Successful!";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(method.equals("login")){
String phone = params[1];
String pass = params[2];
try {
URL url = new URL(login);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
OutputStream os = httpUrlConnection.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data = URLEncoder.encode("phonenumber", "UTF-8")+"="+URLEncoder.encode(phone, "UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(pass, "UTF-8");
bw.write(data);
bw.flush();
bw.close();
os.close();
InputStream is = httpUrlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
String response = "";
String line = "";
while((line = br.readLine())!=null)
{
response += line;
}
br.close();
is.close();
httpUrlConnection.disconnect();
return response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
diag.setTitle("Login Information");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("Registration Successful!"))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
diag.setMessage(result);
diag.show();
}
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lavisor.locationsharing2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="15" />
<permission
android:name="com.testing.svma.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.testing.svma.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RegOneActivity"
android:label="#string/title_activity_reg_one" >
</activity>
<activity
android:name=".PasswordActivity"
android:label="#string/title_activity_password" >
</activity>
<activity
android:name=".PassActivity"
android:label="#string/title_activity_pass" >
</activity>
<activity
android:name=".MapActivity"
android:label="#string/title_activity_map" >
</activity>
<activity
android:name=".SelectCircleActivity"
android:label="#string/title_activity_select_circle" >
</activity>
<activity
android:name=".ShareLocationActivity"
android:label="#string/title_activity_share_location" >
</activity>
<activity
android:name=".FavouritesActivity"
android:label="#string/title_activity_favourites" >
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAZx8eHxiQ5ZRgsDstuyseUKQ_PaH8rlps" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
</application>
</manifest>
I forgot to override OnProgressUpdate in the Async task :P and Now, it works perfectly..
developing an application to take a photo and draw GPS coordinates over it.
just gave a test for the drawtext() method, which isn't showing up.
GPS is working fine.
Camera is working fine.
Canvas is having problems.
code for mainactivity.java
package com.example.camera;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.Button;
import android.view.View;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
import android.os.Environment;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;
import android.widget.Toast;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
public class MainActivity extends Activity
{
double lat,lon;
private static final String TAG = "CallCamera";
private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;
private String photoUri=null;
Uri fileUri = null;
ImageView photoImage = null;
private File getOutputPhotoFile()
{
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getPackageName());
Log.d("directory check ", directory.toString());
if (!directory.exists())
{
if (!directory.mkdirs())
{
Log.e(TAG, "Failed to create storage directory.");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());
return new File(directory.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg");
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
photoImage = (ImageView) findViewById(R.id.photo_image);
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
catch(Exception e)
{
Log.d("GPS","Exception in location part-->"+e.toString());
}
Button callCameraButton = (Button)
findViewById(R.id.button_callcamera);
callCameraButton.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(getOutputPhotoFile());
i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ );
}
}
);
}
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
if (location != null)
{
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
lat=location.getLatitude();
lon=location.getLongitude();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ)
{
if (resultCode == RESULT_OK)
{
Uri photoUri = null;
if (data == null)
{
// A known bug here! The image should have saved in fileUri
Log.d("Image Code","Image Saved");
photoUri = fileUri;
}
else
{
photoUri = data.getData();
Log.d("Image Code","Image Saved at"+data.getData());
}
drawLatLong(photoUri.getPath());
}
else if (resultCode == RESULT_CANCELED)
{
Log.d("Image Code", "Cancled");
}
else
{
Log.d("Image Code", "Callout for image capture failed!");
}
}
}
/**
* takes the PhotoURI and draws the Latitude and longitude over it
* #param photoUri
*/
private void drawLatLong(String photoUri)
{
File imageFile = new File (photoUri);
if (imageFile.exists())
{
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// Resources res=getResources();
// BitmapDrawable drawable = new BitmapDrawable(res,bitmap);
try
{
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE); // Text Color
paint.setStrokeWidth(12); // Text Size
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
// some more settings...
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.drawText("Testing...", 10, 10, paint);
-
FileOutputStream fOut = new FileOutputStream(photoUri);
Log.d("Path"," "+photoUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
System.out.println(photoUri);
//bitmap.recycle();
// System.gc();
}
catch(Exception ex)
{
Log.d("Canvas Part", "Exception caused in canvas drawing-->"+ex.toString());
}
showPhoto(bitmap);
}
}
/**
* Takes the Bitmap from the drawLatLong() method and displays it over the image view.
* #param bitmapShow
*/
private void showPhoto(Bitmap bitmapShow)
{
try
{
Resources res=getResources();
BitmapDrawable drawable = new BitmapDrawable(res,bitmapShow);
photoImage.setImageDrawable(drawable);
photoImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
photoImage.setImageBitmap(bitmapShow);
}
catch(Exception ex)
{
Log.d("canvas","exception in canvas"+ex);
}
}
}
the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.camera.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The bitmap needs to be inMutable. set it with the following code.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(),options);
This section of the code is not needed as the canvas already has this bitmap.
//Not needed:
//canvas.drawBitmap(bitmap, 0, 0, paint);
Similar questions are already available. But in my case I checked both SHA1 and my scope, they are correct and the account is also available. But still it returns unknown GoogleAuthException. My code is :-
MainActivity.java
package com.simon.learn.accountgetter;
import java.io.IOException;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
public class MainActivity extends Activity {
AccountManager am;
Account[] accounts;
ArrayList<String> accNames = new ArrayList<String>();
Button signin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = AccountManager.get(getApplicationContext());
accounts = am.getAccountsByType("com.google");
// accounts=am.getAccounts();
signin = (Button) findViewById(R.id.signinBt);
signin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = AccountPicker.newChooseAccountIntent(null,
null, new String[] { "com.google" }, false, null, null,
null, null);
startActivityForResult(intent, 13);
}
});
}
private void getToken(String accountName) {
new GetTokenTask(MainActivity.this, accountName,
"oauth2:https://www.googleapis.com/auth/userinfo.profile")
.execute();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String token = null;
if (requestCode == 13) {
if (resultCode == RESULT_OK) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.e("simon", accountName);
Toast.makeText(getApplicationContext(), accountName,
Toast.LENGTH_LONG).show();
getToken(accountName);
// Toast.makeText(getApplicationContext(),
// "The token is : "+token, Toast.LENGTH_LONG).show();
}
}
}
public class GetTokenTask extends AsyncTask<Void, Void, String> {
Activity activity;
String scope;
String email;
public GetTokenTask(Activity activity, String email, String scope) {
this.activity = activity;
this.scope = scope;
this.email = email;
}
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
Log.e("simon","Scope : "+scope+ " email "+ email);
token = GoogleAuthUtil.getToken(activity, email, scope);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
Log.e("simon","UserRecoverableAuthException");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("simon","IOException");
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
Log.e("simon","GoogleAuthException : "+e.getMessage());
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Log.e("simon", "The Token is : " + result);
Toast.makeText(getApplicationContext(), "The Token is : " + result,
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
It is showing unknown GoogleAuthException. See my manifest file also
Manifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simon.learn.accountgetter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please help me. Thanks in advance