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>
Related
Can anyone help me with this error. My app is running properly but when clicking activity button, it crashes and this error logcat appears. Anyway, my .so files are in jniLibs folder.
12-26 12:02:12.393 22612-22612/com.project.voicechanger
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.project.voicechanger, PID: 22612 java.lang.UnsatisfiedLinkError:
dalvik.system.PathClassLoader[DexPathList[[zip file
"/data/app/com.project.voicechanger-2/base.apk"],nativeLibraryDirectories=[/data/app/com.prject.voicechanger-2/lib/arm64,
/data/app/com.project.voicechanger-2/base.apk!/lib/arm64-v8a,
/vendor/lib64, /system/lib64]]] couldn't find "libbass.so"
at java.lang.Runtime.loadLibrary(Runtime.java:367)
at java.lang.System.loadLibrary(System.java:1076)
at com.un4seen.bass.BASS.(BASS.java:695)
at com.ypyproductions.voicechanger.EffectActivity.onInitAudioDevice(EffectActivity.java:384)
at com.ypyproductions.voicechanger.EffectActivity.setupInfo(EffectActivity.java:119)
at com.ypyproductions.voicechanger.EffectActivity.onCreate(EffectActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6323)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
This is the EffectActivity.java appeared on the error:
package com.ypyproductions.voicechanger;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.un4seen.bass.BASS;
import com.ypyproductions.materialdialogs.MaterialDialog;
import com.ypyproductions.voicechanger.adapter.EffectAdapter;
import com.ypyproductions.voicechanger.basseffect.DBMediaPlayer;
import com.ypyproductions.voicechanger.basseffect.IDBMediaListener;
import com.ypyproductions.voicechanger.dataMng.JsonParsingUtils;
import com.ypyproductions.voicechanger.dataMng.TotalDataManager;
import com.ypyproductions.voicechanger.object.EffectObject;
import com.ypyproductions.voicechanger.soundMng.SoundManager;
import com.ypyproductions.voicechanger.task.DBTask;
import com.ypyproductions.voicechanger.task.IDBCallback;
import com.ypyproductions.voicechanger.task.IDBTaskListener;
import com.ypyproductions.voicechanger.utils.ApplicationUtils;
import com.ypyproductions.voicechanger.utils.DBLog;
import com.ypyproductions.voicechanger.utils.DirectionUtils;
import com.ypyproductions.voicechanger.utils.IOUtils;
import com.ypyproductions.voicechanger.utils.StringUtils;
import java.io.File;
import java.util.ArrayList;
/**
*
*
* #author:YPY Productions
* #Skype: baopfiev_k50
* #Mobile : +84 983 028 786
* #Email: dotrungbao#gmail.com
* #Website: www.ypyproductions.com
* #Project:TemplateChangeTheme
* #Date:Aug 4, 2015
*
*/
public class EffectActivity extends DBFragmentActivity implements OnClickListener, EffectAdapter.OnEffectListener {
public static final String TAG = EffectActivity.class.getSimpleName();
private ListView mListViewEffects;
private ArrayList<EffectObject> mListEffectObjects;
private EffectAdapter mEffectApdater;
private String mPathAudio;
private TextView mTvHeader;
private boolean isInit;
private DBMediaPlayer mDBMedia;
private String mNameExportVoice;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_effects);
Intent mIntent = getIntent();
if (mIntent != null) {
mPathAudio = mIntent.getStringExtra(KEY_PATH_AUDIO);
}
mListViewEffects = (ListView) findViewById(R.id.list_effects);
mTvHeader = (TextView) findViewById(R.id.tv_header);
mTvHeader.setTypeface(mTypefaceLogo);
setUpBlurLayout();
setupLayoutAdmob();
if (!StringUtils.isEmptyString(mPathAudio)) {
File mFile = new File(mPathAudio);
if (mFile.exists() && mFile.isFile()) {
setupInfo();
}
else {
showToast("File not found exception");
backToHome();
}
}
else {
backToHome();
}
}
private void setupInfo(){
mListEffectObjects = TotalDataManager.getInstance().getListEffectObjects();
if (mListEffectObjects != null && mListEffectObjects.size() > 0) {
mEffectApdater = new EffectAdapter(this, mListEffectObjects, mTypefaceAvenir);
mEffectApdater.setOnEffectListener(this);
mListViewEffects.setAdapter(mEffectApdater);
onInitAudioDevice();
createDBMedia();
}
else{
startLoad(new IDBCallback() {
#Override
public void onAction() {
setupInfo();
}
});
}
}
private void startLoad(final IDBCallback mCallback){
DBTask mDBTask = new DBTask(new IDBTaskListener() {
public ArrayList<EffectObject> mListEffects;
#Override
public void onPreExcute() {
showProgressDialog();
}
#Override
public void onDoInBackground() {
String data = IOUtils.readStringFromAssets(EffectActivity.this, "effects.dat");
mListEffects = JsonParsingUtils.parsingListEffectObject(data);
DBLog.d(TAG, "===============>Size=" + mListEffects.size());
if (mListEffects != null && mListEffects.size() > 0) {
mTotalMng.setListEffectObjects(mListEffects);
}
}
#Override
public void onPostExcute() {
dimissProgressDialog();
if (mListEffects == null || mListEffects.size() == 0) {
backToHome();
return;
}
if(mCallback!=null){
mCallback.onAction();
}
}
});
mDBTask.execute();
}
private void setupLayoutAdmob() {
boolean b=SHOW_ADVERTISEMENT;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_ad);
if (ApplicationUtils.isOnline(this) && b) {
adView = new AdView(this);
adView.setAdUnitId(ADMOB_ID_BANNER);
adView.setAdSize(AdSize.SMART_BANNER);
layout.addView(adView);
AdRequest mAdRequest = new AdRequest.Builder().addTestDevice("51F0A3F4C13F05DD49DE0D71F2B369FB").build();
adView.loadAd(mAdRequest);
return;
}
layout.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
mSoundMng.play(this, R.raw.click);
backToHome();
break;
case R.id.btn_gallery:
mSoundMng.play(this, R.raw.click);
deleteMainFile();
onDestroyMedia();
Intent mIntent = new Intent(this, GalleryActivity.class);
DirectionUtils.changeActivity(this, R.anim.slide_in_from_right, R.anim.slide_out_to_left, true, mIntent);
break;
default:
break;
}
}
private void deleteMainFile() {
if (!StringUtils.isEmptyString(mPathAudio)) {
try {
File file = new File(mPathAudio);
file.delete();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private void onDestroyMedia(){
try{
if (mDBMedia != null) {
mDBMedia.releaseAudio();
}
BASS.BASS_PluginFree(0);
BASS.BASS_Free();
TotalDataManager.getInstance().onResetState();
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
backToHome();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void backToHome() {
deleteMainFile();
onDestroyMedia();
Intent mIntent = new Intent(this, RecordActivity.class);
DirectionUtils.changeActivity(this, R.anim.slide_in_from_left, R.anim.slide_out_to_right, true, mIntent);
}
#Override
public void onPlayEffect(EffectObject mEffectObject) {
boolean isPlaying = mEffectObject.isPlaying();
if (isPlaying) {
mEffectObject.setPlaying(false);
if (mDBMedia != null) {
mDBMedia.pauseAudio();
}
}
else {
TotalDataManager.getInstance().onResetState();
mEffectObject.setPlaying(true);
if (mDBMedia != null) {
mDBMedia.setReverse(mEffectObject.isReverse());
mDBMedia.setAudioPitch(mEffectObject.getPitch());
mDBMedia.setAudioRate(mEffectObject.getRate());
mDBMedia.setAudioReverb(mEffectObject.getReverb());
mDBMedia.setAudioEQ(mEffectObject.getEq());
mDBMedia.setFlangerEffect(mEffectObject.isFlanger());
mDBMedia.setAudioEcho(mEffectObject.isEcho());
if (mDBMedia.isPlaying()) {
if(!mEffectObject.isReverse()){
mDBMedia.seekTo(0);
}
else{
mDBMedia.seekTo(mDBMedia.getDuration());
}
}
mDBMedia.startAudio();
}
}
mEffectApdater.notifyDataSetChanged();
}
#Override
protected void onPause() {
super.onPause();
if (mDBMedia != null) {
resetStateAudio();
}
}
#Override
public void onShareEffect(final EffectObject mEffectObject) {
if(mDBMedia!=null){
resetStateAudio();
}
SoundManager.getInstance().play(this, R.raw.click);
mNameExportVoice=String.format(FORMAT_NAME_VOICE, String.valueOf(System.currentTimeMillis()/1000));
showDialogEnterName(new IDBCallback() {
#Override
public void onAction() {
if (mDBMedia != null) {
startSaveEffect(mEffectObject, new IDBCallback() {
#Override
public void onAction() {
File file = new File(mPathAudio);
File mDir = file.getParentFile();
final File mOutPutFile = new File(mDir, mNameExportVoice);
if (mOutPutFile.exists() && mOutPutFile.isFile()) {
String mInfoSave = String.format(getString(R.string.info_save_voice), mOutPutFile.getAbsolutePath());
showToast(mInfoSave);
showDiaglogShare(mEffectObject);
}
}
});
}
}
});
}
private void resetStateAudio() {
TotalDataManager.getInstance().onResetState();
if (mEffectApdater != null) {
mEffectApdater.notifyDataSetChanged();
}
if (mDBMedia!=null && mDBMedia.isPlaying()) {
mDBMedia.pauseAudio();
}
}
private void startSaveEffect(final EffectObject mEffectObject, final IDBCallback mDBCallback) {
File file = new File(mPathAudio);
final File mDir = file.getParentFile();
final File mTempOutPutFile = new File(mDir, mNameExportVoice);
final DBMediaPlayer mDBExportMedia = new DBMediaPlayer(mPathAudio);
DBTask mDBTask = new DBTask(new IDBTaskListener() {
#Override
public void onPreExcute() {
showProgressDialog();
}
#Override
public void onDoInBackground() {
if (mDBExportMedia != null) {
boolean b = mDBExportMedia.initMediaToSave();
if (b) {
mDBExportMedia.setReverse(mEffectObject.isReverse());
mDBExportMedia.setAudioPitch(mEffectObject.getPitch());
mDBExportMedia.setAudioRate(mEffectObject.getRate());
mDBExportMedia.setAudioReverb(mEffectObject.getReverb());
mDBExportMedia.setFlangerEffect(mEffectObject.isFlanger());
mDBExportMedia.setAudioEcho(mEffectObject.isEcho());
mDBExportMedia.setAudioEQ(mEffectObject.getEq());
mDBExportMedia.saveToFile(mTempOutPutFile.getAbsolutePath());
mDBExportMedia.releaseAudio();
}
}
}
#Override
public void onPostExcute() {
dimissProgressDialog();
if (mDBCallback != null) {
mDBCallback.onAction();
}
}
});
mDBTask.execute();
}
public void onInitAudioDevice() {
if (!isInit) {
isInit = true;
if (!BASS.BASS_Init(-1, 44100, 0)) {
new Exception(TAG + " Can't initialize device").printStackTrace();
this.isInit = false;
return;
}
String libpath = getApplicationInfo().nativeLibraryDir;
try{
BASS.BASS_PluginLoad(libpath + "/libbass_fx.so", 0);
BASS.BASS_PluginLoad(libpath + "/libbassenc.so", 0);
BASS.BASS_PluginLoad(libpath + "/libbassmix.so", 0);
BASS.BASS_PluginLoad(libpath + "/libbasswv.so", 0);
}
catch(Exception e){
e.printStackTrace();
}
}
}
private void createDBMedia() {
if (!StringUtils.isEmptyString(mPathAudio)) {
mDBMedia = new DBMediaPlayer(mPathAudio);
mDBMedia.prepareAudio();
mDBMedia.setOnDBMediaListener(new IDBMediaListener() {
#Override
public void onMediaError() {
}
#Override
public void onMediaCompletion() {
TotalDataManager.getInstance().onResetState();
mEffectApdater.notifyDataSetChanged();
}
});
}
}
private void showDiaglogShare(final EffectObject mEffectObject) {
MaterialDialog.Builder mBuilder = new MaterialDialog.Builder(this);
mBuilder.backgroundColor(getResources().getColor(R.color.white));
mBuilder.title(R.string.title_options);
mBuilder.titleColor(getResources().getColor(R.color.black_text));
mBuilder.items(R.array.list_options);
mBuilder.contentColor(getResources().getColor(R.color.black_text));
mBuilder.positiveColor(getResources().getColor(R.color.pink));
mBuilder.negativeColor(getResources().getColor(R.color.black_secondary_text));
mBuilder.positiveText(R.string.title_cancel);
mBuilder.autoDismiss(true);
mBuilder.typeface(mTypefaceBold, mTypefaceLight);
mBuilder.itemsCallback(new MaterialDialog.ListCallback() {
#Override
public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
if (which == 0) {
shareFile();
}
else if (which == 1) {
saveAsRingtone();
}
else if (which == 2) {
saveAsNotification();
}
}
});
mBuilder.build().show();
}
private void shareFile() {
File file = new File(mPathAudio);
File mDir = file.getParentFile();
final File mOutPutFile = new File(mDir, mNameExportVoice);
if (mOutPutFile.exists() && mOutPutFile.isFile()) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
if(mNameExportVoice.endsWith(AUDIO_RECORDER_FILE_EXT_MP3)){
shareIntent.setType("audio/mp3");
}
else{
shareIntent.setType("audio/*");
}
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mOutPutFile));
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
}
private void saveAsRingtone() {
File file = new File(mPathAudio);
File mDir = file.getParentFile();
final File mOutPutFile = new File(mDir, mNameExportVoice);
if (mOutPutFile != null && mOutPutFile.isFile()) {
Uri mUri=null;
ContentValues values = new ContentValues();
values.put(MediaColumns.DATA, mOutPutFile.getAbsolutePath());
values.put(MediaColumns.TITLE, mNameExportVoice.replaceAll(AUDIO_RECORDER_FILE_EXT_WAV, ""));
values.put(MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
String id=getIdFromContentUri(mOutPutFile.getAbsolutePath());
if(StringUtils.isEmptyString(id)){
mUri = this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(mOutPutFile.getAbsolutePath()), values);
}
else{
this.getContentResolver().update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
, values, MediaColumns._ID+" = ?", new String[]{id});
mUri=Uri.parse(String.format(FORMAT_URI, id));
}
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, mUri);
showToast(R.string.info_set_ringtone_successfully);
}
}
private void saveAsNotification() {
File file = new File(mPathAudio);
File mDir = file.getParentFile();
final File mOutPutFile = new File(mDir, mNameExportVoice);
if (mOutPutFile != null && mOutPutFile.isFile()) {
Uri mUri=null;
ContentValues values = new ContentValues();
values.put(MediaColumns.DATA, mOutPutFile.getAbsolutePath());
values.put(MediaColumns.TITLE, mNameExportVoice.replaceAll(AUDIO_RECORDER_FILE_EXT_WAV, ""));
values.put(MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
String id=getIdFromContentUri(mOutPutFile.getAbsolutePath());
if(StringUtils.isEmptyString(id)){
mUri = this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(mOutPutFile.getAbsolutePath()), values);
}
else{
this.getContentResolver().update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
, values, MediaColumns._ID+" = ?", new String[]{id});
mUri=Uri.parse(String.format(FORMAT_URI, id));
}
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, mUri);
showToast(R.string.info_set_notification_successfully);
}
}
private String getIdFromContentUri(String path) {
try {
if(path!=null){
String id;
String[] filePathColumn = {MediaColumns._ID};
String[] selectionArgs = {path};
Cursor cursor = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
filePathColumn, MediaColumns.DATA+" = ?", selectionArgs, null);
if(cursor!=null && cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
id = cursor.getString(columnIndex);
cursor.close();
return id;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void showDialogEnterName(final IDBCallback mDCallback) {
final EditText mEdName = new EditText(this);
mEdName.setSingleLine(true);
Builder builder = new Builder(this).setTitle(getString(R.string.title_enter_name)).setView(mEdName)
.setPositiveButton(getString(R.string.title_ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ApplicationUtils.hiddenVirtualKeyboard(EffectActivity.this, mEdName);
String mNewName = mEdName.getText().toString();
if(!StringUtils.isEmptyString(mNewName)){
if(StringUtils.isContainsSpecialCharacter(mNewName)){
showToast(R.string.info_your_name_error);
return;
}
mNameExportVoice=mNewName+".wav";
}
if(mDCallback!=null){
mDCallback.onAction();
}
}
}).setNegativeButton(getString(R.string.title_skip), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mDCallback!=null){
mDCallback.onAction();
}
}
});
AlertDialog mDialogEnterPass = builder.create();
mDialogEnterPass.show();
}
}
This is the app gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '28.0.3'
dexOptions {
javaMaxHeapSize "4g"
}
defaultConfig {
applicationId "com.ypyproductions.voicechanger"
minSdkVersion 15
targetSdkVersion 27
versionCode 20181
versionName "1.0"
multiDexEnabled true
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':nineOldLibrary')
implementation project(':materialDialog')
implementation 'com.android.support:support-fragment:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-media-compat:27.1.1'
implementation 'com.android.support:support-compat:27.1.1'
implementation 'com.android.support:customtabs:27.1.1'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.google.android.gms:play-services-identity:16.0.0'
implementation 'com.google.android.gms:play-services-gcm:16.0.0'
}
I am using Android Studio and Windows 10 laptop.
From un4seen.com forum:
1 mkdir lib, then, copy armeabi to lib, the tree should bee lib/armeeabi/libbass.so
2 zip lib directory: $zip -r libbass.zip lib
3 rename: $mv libbass.zip libbass.jar
4 copy libbass.jar to YourProject/Youproject/src/main/libs, "YourProject/Youproject/src/main/" includes AndroidManifests.xml, res, java, libs
5 add this line:
compile fileTree(dir: 'libs', include: '*.jar')
to your build.gradle---->dependencies
I am trying to send an image file through android using a server socket. I have used AsyncTask class on the client side and created a TransferFile class to send the file. I am getting a NO SUCH FILE OR DIRECTORY exception while creating the file on client's side. The code is attached below.
Permissions.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
TransferFile class.
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class TransferFile extends IntentService{
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.apposite.wifip2p.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public TransferFile(){
super("TransferFile");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
Toast.makeText(this, "Client Socket Intent Handled.", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
Toast.makeText(context, "inside ACTION_SEND_FILE.", Toast.LENGTH_SHORT).show();
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Toast.makeText(context, "Client Socket Connected: "+socket.isConnected(), Toast.LENGTH_SHORT).show();
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
}
catch (FileNotFoundException e) {
}
MainActivity.copyFile(is, stream);
} catch (IOException e) {
Toast.makeText(context, "File can't be copied to client.", Toast.LENGTH_SHORT).show();
} finally {
if(socket.isConnected()){
try {
socket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
}
}
MainActivity class
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener{
WifiP2pManager wifi;
private WifiP2pInfo info;
ListView listViewPeer;
WifiP2pManager.Channel channel;
IntentFilter intentFilter = new IntentFilter();
Button discover, send;
List<WifiP2pDevice> peersList;
List<String> peersNameList;
BroadcastReceiver receiver = null;
ProgressDialog progressDialog = null;
boolean isConnected = false;
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
Intent serviceIntent;
boolean isHost = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
listViewPeer = (ListView) findViewById(R.id.ListViewPeer);
discover = (Button) findViewById(R.id.btnDiscover);
send = (Button) findViewById(R.id.btnGallery);
wifi = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifi.initialize(this, getMainLooper(), null);
receiver = new WifiP2pBroadcastReceiver(wifi, channel, this);
peersList = new ArrayList<>();
peersNameList = new ArrayList<>();
discover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(MainActivity.this, "Press back to cancel", "finding peers", false,
true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if(peersList.size()==0)
Toast.makeText(MainActivity.this, "Peer Not Found.", Toast.LENGTH_SHORT).show();
}
});
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 15000);
wifi.discoverPeers(channel, new WifiP2pManager.ActionListener(){
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Peer Discovery failed.", Toast.LENGTH_SHORT).show();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
});
refreshList();
listViewPeer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!isConnected)
connect(position);
else
disconnect();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
if(!isConnected)
send.setVisibility(View.GONE);
else
send.setVisibility(View.VISIBLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
serviceIntent = new Intent(this, TransferFile.class);
serviceIntent.setAction(TransferFile.ACTION_SEND_FILE);
serviceIntent.putExtra(TransferFile.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(TransferFile.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(TransferFile.EXTRAS_GROUP_OWNER_PORT, 8988);
this.startService(serviceIntent);
Toast.makeText(this, "TransferFile should start.", Toast.LENGTH_SHORT).show();
}
public void connect(int position) {
final WifiP2pDevice device = peersList.get(position);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifi.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
}
});
}
public void disconnect() {
send.setVisibility(View.GONE);
wifi.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onFailure(int reasonCode) {
Toast.makeText(MainActivity.this, "Device disconnecting failed.", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess() {
}
});
}
#Override
public void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);
send.setVisibility(View.GONE);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onDestroy() {
super.onStop();
if(isHost)
stopService(serviceIntent);
}
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
peersList.clear();
peersList.addAll(peers.getDeviceList());
refreshList();
}
public void refreshList(){
peersNameList.clear();
if(peersList.size()!=0){
for(int i=0;i<peersList.size();i++){
peersNameList.add(i, peersList.get(i).deviceName);
}
}
else
send.setVisibility(View.GONE);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, peersNameList);
listViewPeer.setAdapter(arrayAdapter);
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
this.info = info;
if(!isConnected){
Toast.makeText(MainActivity.this, "Device Connected.", Toast.LENGTH_SHORT).show();
isConnected = true;
if (info.groupFormed && info.isGroupOwner) {
isHost = false;
new FileServerAsyncTask(this).execute();
}
else if(info.groupFormed)
send.setVisibility(View.VISIBLE);
else
Toast.makeText(MainActivity.this, "Nothing matters", Toast.LENGTH_SHORT).show();
}
}
public void reset(){
if(isConnected){
Toast.makeText(MainActivity.this, "Device Disconnected.", Toast.LENGTH_SHORT).show();
isConnected = false;
send.setVisibility(View.GONE);
}
}
public class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
Context context;
FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
// Here
// is
// the
// ERROR
f.createNewFile();
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "inside post execute." + result, Toast.LENGTH_SHORT).show();
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "Opening a server socket", Toast.LENGTH_SHORT).show();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
return false;
}
return true;
}
}
And this is my FileServerAsycTask class
public class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
Context context;
FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
// Here
// is
// the
// ERROR
f.createNewFile();
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "inside post execute." + result, Toast.LENGTH_SHORT).show();
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "Opening a server socket", Toast.LENGTH_SHORT).show();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
return false;
}
return true;
}
When on the client side, I try to create a new file using f.createNewFile(), it gives me an error "No such file or directory".
W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
W/System.err: at java.io.File.createNewFile(File.java:939)
W/System.err: at com.apposite.wifip2p.MainActivity$FileServerAsyncTask.doInBackground(MainActivity.java:360)
W/System.err: at com.apposite.wifip2p.MainActivity$FileServerAsyncTask.doInBackground(MainActivity.java:310)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at java.io.File.createNewFile(File.java:932)
W/System.err: ... 8 more
The file's name is...
/storage/emulated/0/com.apposite.wifip2pwifip2pshared-1489935211585.jpg
Please help me how to resolve it!
When creating your Intent to pass the Uri over to the service:
Put in in the data facet of the Intent (setData(), not putExtra()), and
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the Intent before calling startService()
Your activity has access to this content; without these changes, your service will not have access to the content.
Also, if your targetSdkVersion is 23 or higher, and you are running on Android 6.0+, you need to handle runtime permissions.
I am android developer .I have face issue ANR when multiple image send in background using intent service.I have call service on Resume() method.I have update UI when step by step image upload finish .My all code in service .But i don't understand why my UI hang.I have created ResultReceiver class for Update UI. Please tell me what is wrong i am doing.
public class UploadImageService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "UploadImageService";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";
private String threadType, toUser, chatThreadId, gcmRegistrationId, openCloseChatWindowType, recipientName, threadTopicName, attachmentID, attachmentType, currentChunks, originalBase64Img, dateTime, classType, loginUserId;
// Declare Web services variable
private MultipartEntity multipartEntityBuilder;
Database database;
Bundle bundle;
ResultReceiver receiver;
public UploadImageService() {
super(UploadImageService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
//initialize database
database = new Database(UploadImageService.this, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
Log.d(TAG, "Service Started!");
receiver = intent.getParcelableExtra("receiver");
try {
bundle = new Bundle();
/* Update UI: upload Service is Running */
//receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
/* new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
}
}).start();*/
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Service Stopping!");
//this.stopSelf();
}
private class UploadThumbImageAsync extends AsyncTask<String, Void, String> {
/*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
String toUser, comTypeId, threadType, chatThreadId, threadTopicName, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUserName, recipientName, originalBase64Image, originalFilePath;
#Override
protected void onPreExecute() {
super.onPreExecute();
//showProgressDialog();
}
/*starts the loading of the data in background in doInBackground() method */
#Override
protected String doInBackground(String... params) {
try {
toUser = params[0];
comTypeId = params[1];
threadType = params[2];
chatThreadId = params[3];
threadTopicName = params[4];
chatAttachmentType = params[5];
chatMessage = params[6];
thumbBase64AttachmentPath = params[7];
loginUserName = params[8];
recipientName = params[9];
originalBase64Image = params[10];
originalFilePath = params[11];
String url;
if (!TextUtils.isEmpty(threadType) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
url = WS.URL.concat(WS.SAVE_CHAT);
} else {
url = WS.URL.concat(WS.GROUP_SAVE_CHAT);
}
Log.e(TAG, "url_" + chatMessage + " = " + url);
String response = HttpClientExecuteMethod.executeMultipartPostMethod(url, multipartEntityBuilder);
//Log.e(TAG, "save_chat_history_response_" + threadType + "_" + chatMessage + " =" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*This method is called after the background computation finishes.
The result of background process in passed in this method as parameters
and now you can dismiss progress dialog
and get the result and display on onPostExecute() method
*/
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// Log.e(TAG, "chatAttachmentType = " + chatAttachmentType);
updateCounter();
if (result != null) {
JSONObject jo = new JSONObject(result);
String success = null;
final int storeLimit = SharedPreference.getLimit(UploadImageService.this);
if (jo.has(WS.SUCCESS)) {
success = jo.getString(WS.SUCCESS);
if (!TextUtils.isEmpty(success) && success.equals("0")) {
return;
}
if (!TextUtils.isEmpty(success) && success.equals("100")) {
callWsSaveChat(chatAttachmentType, chatMessage, thumbBase64AttachmentPath, originalBase64Image, originalFilePath);
updateRecentChatAndThreadList();
return;
}
if (!TextUtils.isEmpty(success) && success.equals("99")) {
updateRecentChatAndThreadList();
return;
}
}
try {
ArrayList<Chat> saveChatArrayList = null;
if (!TextUtils.isEmpty(success) && success.equals("1")) {
saveChatArrayList = new Chat().getChatHistory(UploadImageService.this, result, TAG, "");
// Log.e(TAG, "onPostExecute_saveChatArrayList.size = " + saveChatArrayList);
ArrayList<Chat> chatHistoryWithoutMsgId = database.getWithoutMsgIdChatHistory(chatThreadId, "#");
//Log.e(TAG, "onPostExecute_chatHistoryWithoutMsgId.size = " + chatHistoryWithoutMsgId.size());
if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {
for (int i = 0; i < saveChatArrayList.size(); i++) {
final Chat apiChat = saveChatArrayList.get(i);
String apiMsg = apiChat.getMessage();
String apiThumb = null;
if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
apiThumb = apiChat.getAttachment_thumb().concat("$");
}
if (chatHistoryWithoutMsgId != null && !chatHistoryWithoutMsgId.isEmpty() && chatHistoryWithoutMsgId.size() > 0) {
for (int j = 0; j < chatHistoryWithoutMsgId.size(); j++) {
Chat dbChat = chatHistoryWithoutMsgId.get(j);
final String db_message = dbChat.getMessage();
final String db_thumb = dbChat.getAttachment_thumb();
if (apiThumb.equals(db_thumb)) {
database.updateChatList(apiChat, result, "#", db_message, db_thumb, loginUserId, toUser, chatThreadId, threadType);
bundle.putString(RESULT, UPLOAD_IMAGE);
receiver.send(STATUS_FINISHED, bundle);
if (!TextUtils.isEmpty(chatAttachmentType) && chatAttachmentType.equals(getResources().getString(R.string.Image))) {
originalBase64Image = getBase64Image(originalFilePath);
}
int subLength = 1024 * 256;
//Log.e(TAG, "upload_subLength = " + subLength);
int index = 0;
int totalChunks = 0;
if (!TextUtils.isEmpty(originalBase64Image)) {
for (int k = 0; index < originalBase64Image.length(); k++) {
index = index + subLength;
totalChunks++;
}
database.insertOriginalUploadImageList(apiChat.getAttachment_id(), totalChunks, 0, originalFilePath, chatThreadId, apiChat.getDt_sender_created(), chatAttachmentType);
// database.deleteAttachmentImageList(originalBase64Image);
database.deleteAttachmentImageList(originalFilePath);
UploadOriginalImageList(apiChat.getAttachment_id());
}
break;
} else {
// Log.e(TAG, "onPostExecute_not_equal_image");
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Util.showAlertDialog(mContext, mContext.getResources().getString(R.string.No_internet_connection_available));
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error = " + e.getMessage());
}
}
There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
Now your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="#+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
of course, include the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
And voilà. Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like
Can anyone tell me how to connect a mobile and a printer via bluetooth to print a text file in android?
That is,if i click the print button from the android application,the printer has to print that corresponding file.As per my knowledge i have searched for it in Google, but i couldn't find any good samples to do it.Has anyone have at-least one sample android program to do this, it will be better to clear my chaos.
Suggestions please.
Thanks for your precious time!..
Bluetooth Printer Android Example
Create a new android project BlueToothPrinterApp in your editor.
Step 1:
Create main activity like below
com.example.BlueToothPrinterApp / BlueToothPrinterApp.java
package com.example.BlueToothPrinterApp;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BlueToothPrinterApp extends Activity {
/** Called when the activity is first created. */
EditText message;
Button printbtn;
byte FONT_TYPE;
private static BluetoothSocket btsocket;
private static OutputStream btoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (EditText) findViewById(R.id.message);
printbtn = (Button) findViewById(R.id.printButton);
printbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
protected void connect() {
if (btsocket == null) {
Intent BTIntent = new Intent(getApplicationContext(), BTDeviceList.class);
this.startActivityForResult(BTIntent, BTDeviceList.REQUEST_CONNECT_BT);
} else {
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
btoutputstream = opstream;
print_bt();
}
}
private void print_bt() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btoutputstream = btsocket.getOutputStream();
byte[] printformat = {
0x1B,
0× 21,
FONT_TYPE
};
btoutputstream.write(printformat);
String msg = message.getText().toString();
btoutputstream.write(msg.getBytes());
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (btsocket != null) {
btoutputstream.close();
btsocket.close();
btsocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
btsocket = BTDeviceList.getSocket();
if (btsocket != null) {
print_bt();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 2:
com.example.BlueToothPrinterApp / BTDeviceList.java
package com.example.BlueToothPrinterApp;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BTDeviceList extends ListActivity {
static public final int REQUEST_CONNECT_BT = 0× 2300;
static private final int REQUEST_ENABLE_BT = 0× 1000;
static private BluetoothAdapter mBluetoothAdapter = null;
static private ArrayAdapter < String > mArrayAdapter = null;
static private ArrayAdapter < BluetoothDevice > btDevices = null;
private static final UUID SPP_UUID = UUID
.fromString(“8 ce255c0 - 200 a - 11e0 - ac64 - 0800200 c9a66″);
// UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
static private BluetoothSocket mbtSocket = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(“Bluetooth Devices”);
try {
if (initDevicesList() != 0) {
this.finish();
return;
}
} catch (Exception ex) {
this.finish();
return;
}
IntentFilter btIntentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mBTReceiver, btIntentFilter);
}
public static BluetoothSocket getSocket() {
return mbtSocket;
}
private void flushData() {
try {
if (mbtSocket != null) {
mbtSocket.close();
mbtSocket = null;
}
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
if (btDevices != null) {
btDevices.clear();
btDevices = null;
}
if (mArrayAdapter != null) {
mArrayAdapter.clear();
mArrayAdapter.notifyDataSetChanged();
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter = null;
}
finalize();
} catch (Exception ex) {} catch (Throwable e) {}
}
private int initDevicesList() {
flushData();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), “Bluetooth not supported!!”, Toast.LENGTH_LONG).show();
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mArrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1);
setListAdapter(mArrayAdapter);
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
Toast.makeText(getApplicationContext(), “Getting all available Bluetooth Devices”, Toast.LENGTH_SHORT)
.show();
return 0;
}
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
Set < BluetoothDevice > btDeviceList = mBluetoothAdapter
.getBondedDevices();
try {
if (btDeviceList.size() > 0) {
for (BluetoothDevice device: btDeviceList) {
if (btDeviceList.contains(device) == false) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress());
mArrayAdapter.notifyDataSetInvalidated();
}
}
}
} catch (Exception ex) {}
}
break;
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
if (btDevices == null) {
btDevices = new ArrayAdapter < BluetoothDevice > (
getApplicationContext(), android.R.id.text1);
}
if (btDevices.getPosition(device) < 0) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress() + “\n”);
mArrayAdapter.notifyDataSetInvalidated();
}
} catch (Exception ex) {
// ex.fillInStackTrace();
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, final int position,
long id) {
super.onListItemClick(l, v, position, id);
if (mBluetoothAdapter == null) {
return;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
Toast.makeText(
getApplicationContext(), “Connecting to” + btDevices.getItem(position).getName() + “, ”
+btDevices.getItem(position).getAddress(),
Toast.LENGTH_SHORT).show();
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), “Cannot establish connection”, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, Menu.FIRST, Menu.NONE, “Refresh Scanning”);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Menu.FIRST:
initDevicesList();
break;
}
return true;
}
}
Step 3:
Edit your main.xml file and paste below code.
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:id="#+id/msgtextlbl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Your Message : "/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_below="#+id/msgtextlbl"
android:text=""/>
<Button
android:id="#+id/printButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:text="Print"/>
</RelativeLayout>
Step 4:
Now edit your AndroidManifest.xml
Add bluetooth permission and admin permission.
AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest
xmlns:android=”http://schemas.android.com/apk/res/android
package=”com.example.BlueToothPrinterApp”
android:versionCode=”1″
android:versionName=”1.0″>
<uses-sdk android:minSdkVersion=”14″ />
<uses-permission android:name=”android.permission.BLUETOOTH”></uses-permission>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”></uses-permission>
<application
android:label=”#string/app_name”
android:icon=”#drawable/ic_launcher”>
<activity
android:name=”BlueToothPrinterApp”
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=”BTDeviceList”></activity>
</application>
</manifest>
Compile and run this application. Enter message and press print button.
You will see list of bluetooth devices. Select bluettoth printer.
Check print on your bluetooth printer.
here is the CODE Reference...
You can use this awesome lib, you can connect to any printer and print easily,
https://github.com/mazenrashed/Printooth
you can download it by:
implementation 'com.github.mazenrashed:Printooth:${LAST_VERSION}'
and use it like:
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World")
printables.add(printable)
BluetoothPrinter.printer().print(printables)
I am unable to fetch the image from the database, please look at my databasehelper (that is my fetchimg(String i) and MainActivity (that is showmeth(View w)) class.
What I am actually doing here is firstly capturing the image with camera, then it is temporary pasted on 1st ImageView and after i click on save button it gets saved in the database(No problem yet). But when i click show button then it must show the image in a 2nd ImageView by taking reference id as a textview's id but it is not showing the image, that is showmeth(View w) unable to fetch the image from database.
My MainActivity
package com.example.expnewbutton;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Uri fileUri;
Bitmap img;
TextView t1;
databasehelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView) findViewById(R.id.text);
helper = new databasehelper(this);
}
public void cammethod(View w) {
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
// fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.", Toast.LENGTH_LONG)
.show();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
} else {
// The picture was returned
Bundle extras = intent.getExtras();
img = (Bitmap) extras.get("data");
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
public void insertimg(View w) {
long a = 0;
String id = t1.getText().toString();
try {
helper.deleterecord(id);
a = helper.insert(id, img);
if (a >= 1) {
Toast.makeText(getBaseContext(),
a + "Record Successfully Saved", 30).show();
} else {
Toast.makeText(getBaseContext(), "Not Saved", 30).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "there is error", 5).show();
}
}
public void showmeth(View w) {
String i = null;
boolean flag = false;
i = t1.getText().toString();
try {
flag = helper.fetchimg(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "database exception", 10).show();
}
if (flag == true) {
Toast.makeText(getBaseContext(),
"Here your image save on imageview", 10).show();
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setImageBitmap(helper.bmp);
} else {
Toast.makeText(getBaseContext(), "Add a Pic first", 50).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My Database File:
package com.example.expnewbutton;
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class databasehelper extends SQLiteOpenHelper {
final static String databasename = "Image";
final static int databaseversion = 1;
Bitmap bmp = null;
public databasehelper(Context ctx) {
super(ctx, databasename, null, databaseversion);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d("tag4545", "database");
db.execSQL("create table mypic(id text,pic BLOB)");
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if Exists mypic");
// db.execSQL("drop table if Exists emer");
onCreate(db);
}
public long insert(String id, Bitmap img) {
SQLiteDatabase base = getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value = new ContentValues();
value.put("id", id);
value.put("pic", data);
long a = base.insert("mypic", null, value);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public boolean fetchimg(String i) {
SQLiteDatabase base = getReadableDatabase();
Cursor cs = null;
try {
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { "i" }, null, null, null);
/*
* String qu= "select pic from mypic where id"+i;
*
* Cursor cs=null; try{ cs =base.rawQuery(qu, null); }
* catch(Exception e) { return false; }
*/
if (cs != null) {
cs.moveToFirst();
byte[] imgbyte = cs.getBlob(0);
cs.close();
bmp = BitmapFactory.decodeByteArray(imgbyte, 0, imgbyte.length);
return true;
}
else {
return false;
}
}
catch (Exception e) {
return false;
}
}
public void deleterecord(String pe_id) {
SQLiteDatabase base = getWritableDatabase();
base.delete("mypic", "id=?", new String[] { pe_id });
}
}
My xml file:
<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:background="#drawable/gb2"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_toRightOf="#+id/textView2"
android:onClick="cammethod"
android:text="Cam" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="46dp"
android:layout_toRightOf="#+id/button1"
android:onClick="insertimg"
android:text="Save" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Photo"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/imageView1"
android:onClick="showmeth"
android:text="show" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView1" />
</RelativeLayout>
Please help me in code, I need it soon. Thank you.
So the problem may be with database query(I tried query with both methods which i hidden or which is not hidden) or may be with using BLOB in my code. Please help me to find error
You are passing the string "i" where you need to pass the value of i.
You should change your query to:
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { String.valueOf(i) }, null, null, null);