Android: click button to check existence and save file - android

I want the app can achieve follow functions
1.put file name into ediTtext
2.press a start button,
if the file exists, write into the file, if not, create the file
3.press stop button,
the process will be stopped and the content of editText will return to the file name.
I have finished the save file part, but don't know how to check existence :P, hope can get some code for reference!
Thanks!
Here is the code for saving file:
////////////////////////////////////
private String TAG = "MyActivity";
private WifiManager wifiManager;
List<ScanResult> list;
private Runnable runnable;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_list);
handler=new Handler();
runnable=new Runnable() {
#Override
public void run() {
init();
handler.postDelayed(this, 3000);
}
};
handler.post(runnable);
}
private void init() {
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
list = wifiManager.getScanResults();
ListView listView = (ListView) findViewById(R.id.listView);
String wifiInfo = "";
if (list == null) {
Toast.makeText(this, "wifi is closed!", Toast.LENGTH_LONG).show();
}else {
for (int i = 0; i<list.size();i++){
ScanResult scanResult = list.get(i);
String bssid = scanResult.BSSID;
String ssid = scanResult.SSID;
int strength = Math.abs(scanResult.level);
wifiInfo = wifiInfo + String.format("%25s,%20s,%5d\n", bssid,ssid,strength);
}
listView.setAdapter(new NewAdapter(this,list));
}
writeToFile(wifiInfo,"WifiList_Info.txt");
Toast toast = Toast.makeText(this, "new record", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
private void writeToFile(String data,String fileName){
File file = null;
OutputStream output = null;
byte buffer[] = null;
try{
File path = Environment.getExternalStorageDirectory();
file = new File(path,fileName);
if(!file.exists())
file.createNewFile();
output = new FileOutputStream(file, true);
buffer = data.getBytes();
output.write(buffer);
output.flush();
output.close();
}
catch(Exception e){ e.printStackTrace();
}
}
public void onClick_startEvent(View view) {
EditText editText = (EditText)findViewById(R.id.et1);
editText.setText("writing into the file", TextView.BufferType.NORMAL);
}
}

for checking file existance use :
File tempFile = null;
tempFile = new File(filePath);
if(!tempFile.exists())
//do your work

File myFile = new File(your_file_path);
if(myFile.exists())
{
// file exists
}
else
{
// file doesn't exists, so create a new file here.
}

Related

Android Toast did not show after open Gallery and pick image

I want to show Toast (or progress bar) when clicking on the button "btnSearchImg". If before upload image, button clicked say "first pick image from gallary" and if after upload image clicked say "waiting". the toast before uploading image work fine but after uploading didn't work fine! my entire Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_image);
Toasty.Config.getInstance().setTextSize(15).apply();
mSharedPreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putString(PREF_SKIP,null);
if(mSharedPreferences.contains(PREF_SKIP)){
Log.i("payment", "true");
} else {
try {
}catch (Exception e){
Toast.makeText(getApplicationContext(), "ERORR", Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
pbImgRetrvialProccess = (ProgressBar)findViewById(R.id.pbImgRetrvialProccess);
tvPermissionLoadImg = (TextView)findViewById(R.id.tvPermissionLoadImg);
tvPermissionLoadImg.setTypeface(Base.getIranSansFont());
TextView tvSearchImageToolBarText = (TextView) findViewById(R.id.tvSearchImageToolBarText);
tvSearchImageToolBarText.setTypeface(Base.getIranSansFont());
ivGalleryImgLoad = (ImageView) findViewById(R.id.ivGalleryImgLoad);
btnSearchImgLoad = (Button) findViewById(R.id.btnSearchImgLoad);
btnSearchImg = (Button) findViewById(R.id.btnSearchImg);
btnSearchImgLoad.setOnClickListener(this);
btnSearchImg.setOnClickListener(this);
}
public StringBuilder uniformQuantization( File filePath ){...}
private StringBuilder chHistogram( Mat newImage ){...}
private void CopyAssets(String filename){...}
private void copyFile(InputStream in, OutputStream out) throws IOException {...}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearchImgLoad:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);}
OpenGallery();
break;
case R.id.btnSearchImg:
Toasty.success(getBaseContext(), "Waiting...", Toast.LENGTH_LONG).show();
FindSimilarRequestedImage();
break;
}
}
private void OpenGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE && data != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);
} else {
selectedImageUri = data.getData();
ivGalleryImgLoad.setImageURI(selectedImageUri);
tvPermissionLoadImg.setVisibility(View.INVISIBLE);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void dateiLesenStringBuilder() {
FEATURE_PATH = context.getCacheDir().getPath() + "/" + FEATURE_NAME;
try {
FileOutputStream out = new FileOutputStream(FEATURE_PATH);
InputStream in = context.getAssets().open("coins/"+FEATURE_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0){
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
final File featureList = new File(FEATURE_PATH);
Runnable runner = new Runnable() {
BufferedReader in = null;
#Override
public void run() {
try {
String sCurrentLine;
int lines = 0;
BufferedReader newbw = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
while (newbw.readLine() != null)
lines++;
in = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
ArrayList<Double> nDistVal = new ArrayList<Double>();
ArrayList<String> nImagePath = new ArrayList<String>();
int count = 0;
while ((sCurrentLine = in.readLine()) != null) {
String[] featX = sCurrentLine.split(";")[1].split(" ");
nImagePath.add(sCurrentLine.split(";")[0]);
nDistVal.add(Distance.distL2(featX, queryFeatureX.toString().split(" ")));
count++;
}
ArrayList<Double> nstore = new ArrayList<Double>(nDistVal); // may need to be new ArrayList(nfit)
double maxDistVal = Collections.max(nDistVal);
Collections.sort(nDistVal);
sortedNImagePath = new ArrayList<String>();
for (int n = 0; n < nDistVal.size(); n++) {
int index = nstore.indexOf(nDistVal.get(n));
sortedNImagePath.add(nImagePath.get(index));
sortedNImageDistanceValues.add(String.valueOf(nDistVal.get(n) / maxDistVal));
String filePath = sortedNImagePath.get(0);
String minDistanceImg = sortedNImageDistanceValues.get(n);
FileNameFromPath = filePath.substring(filePath.lastIndexOf("/") + 1);
System.out.println("Distance values -> " + FileNameFromPath.toString());
System.out.println("Distance values -> " + minDistanceImg.toString());
}
} catch (Exception ex) {
String x = ex.getMessage();
System.out.println("ERORR" + x);
}
if (in != null) try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
Intent imgSearchedCoinNameIntent = new Intent(SearchByImageActivity.this, ImageSearchedCoinActivity.class);
imgSearchedCoinNameIntent.putExtra("imgSearchedCoinName", FileNameFromPath);
startActivity(imgSearchedCoinNameIntent);
}
}
};
Thread t = new Thread(runner, "Code Executer");
t.start();
}
}
If I put the "Waiting..." Toast after the FindSimilarRequestedImage() the toast will show up, but I need the toast show immediately after clicking on the btnSearchImg.
NOTE: Also in the dateiLesenStringBuilder() I removed the thread t that this part of code runs in normal flow and serial, but nothing changes!
Instead of toast use logcat to see if they run sequentially or not, maybe toast takes time to run
I solved this problem by putting the part of code in delay like below:
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
pbImgRetrvialProccess.setVisibility(View.VISIBLE);
Toasty.success(getBaseContext(), "Waiting ...", Toast.LENGTH_LONG).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
}
}, 5000);
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
Now before destroying activity throw functions, I first show the toast, then run other functions!

Adding Progress Bar or Progress Dialogue for sending and receiving file

I have implemented a file sharing project. I am able to Send and Receive File but want to add progress bar or progress dialogue but I have no clue where to add progress bar to it.
Receiver Activity
public class ReceiverActivity extends AppCompatActivity {
FileReceiver fileReceiver;
ImageButton ibt;
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
/* case FileReceiver.CODE :
tvCode.setText((int)msg.obj + "");
break;
*/
case FileReceiver.LISTENING :
Toast.makeText(ReceiverActivity.this,"Listening...",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.CONNECTED:
Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.RECEIVING_FILE :
Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.FILE_RECEIVED :
File file = (File) msg.obj;
Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
fileReceiver.close();
break;
case FileReceiver.RECEIVE_ERROR :
Toast.makeText(ReceiverActivity.this,"Error occured : " + (String)msg.obj,Toast.LENGTH_SHORT).show();
fileReceiver.close();
break;
}
}
};
public void getFile(View view) {
fileReceiver = new FileReceiver(this,mHandler);
fileReceiver.getFile();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
ibt= (ImageButton) findViewById(R.id.imgbtn);
ibt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ReceiverActivity.this, Selection_Activity.class);
startActivity(i);
}
});
}
}
Receiver Thread
public class ReceiverThread extends Thread {
private int port;
private Messenger messenger;
private ServerSocket listenerSocket;
private Socket communicationSocket;
private int PKT_SIZE = 60*1024;
ProgressDialog dialog;
public ReceiverThread(int port,Messenger messenger){
//
this.port = port;
this.messenger = messenger;
File folder = new File(Environment.getExternalStorageDirectory() + "/FileSharer/");
folder.mkdirs();
}
#Override
public void run() {
Message message;
try {
listenerSocket = new ServerSocket(port);
message = Message.obtain();
message.what = FileReceiver.CODE;
message.obj = port;
messenger.send(message);
message = Message.obtain();
message.what = FileReceiver.LISTENING;
message.obj = "";
messenger.send(message);
communicationSocket = listenerSocket.accept();
message = Message.obtain();
message.what = FileReceiver.CONNECTED;
message.obj = "";
messenger.send(message);
DataInputStream in = new DataInputStream(communicationSocket.getInputStream());
message = Message.obtain();
message.what = FileReceiver.RECEIVING_FILE;
message.obj = "";
messenger.send(message);
// Read File Name and create Output Stream
String fileName = in.readUTF();
File receiveFile = new File(Environment.getExternalStorageDirectory() + "/FileSharer/" + fileName);
DataOutputStream dout = new DataOutputStream(new FileOutputStream(receiveFile,true));
// Read File Size
long fileSize = in.readLong();
int totalLength = 0;
int length = 0;
byte[] receiveData = new byte[PKT_SIZE];
long startTime = System.currentTimeMillis();
// Get the file data
while( fileSize>0 && ( ( length = in.read( receiveData,0,(int) Math.min(receiveData.length,fileSize) ))!= -1) )
{
dout.write(receiveData, 0, length);
totalLength += length;
fileSize -= length;
}
long stopTime = System.currentTimeMillis();
dout.close();
double time = (stopTime - startTime) / 1000.0;
double speed = (totalLength / time) / 1048576.0;
message = Message.obtain();
message.what = FileReceiver.FILE_RECEIVED;
message.obj = receiveFile;
messenger.send(message);
} catch (Exception e){
e.printStackTrace();
message = Message.obtain();
message.what = FileReceiver.RECEIVE_ERROR;
message.obj = e.toString();
try {
messenger.send(message);
} catch (RemoteException re) {
Log.e("ReceiverThread","Error in sending an error message! Error : " + re.toString());
re.printStackTrace();
}
} finally {
try {
if(communicationSocket!=null)
communicationSocket.close();
if(listenerSocket!=null)
listenerSocket.close();
} catch (IOException ioe) {
Log.e("ReceiverThread","Error in closing sockets. Error : " + ioe.toString());
ioe.printStackTrace();
}
}
}
}
Receiver Service
public class ReceiverService extends Service {
private final String PORT = "PORT";
private final String MESSENGER = "MESSENGER";
private int port;
private Messenger messenger;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b = intent.getExtras();
port = (int) b.get(PORT);
messenger = (Messenger) b.get(MESSENGER);
ReceiverThread receiverThread = new ReceiverThread(port,messenger);
receiverThread.start();
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
File Receiver
public class FileReceiver {
private final boolean mDebug = true;
// private final int MIN_PORT_NUMBER = 1024;
// private final int MAX_PORT_NUMBER = 65536;
private final String PORT = "PORT";
private final String MESSENGER = "MESSENGER";
// Constants start from 2001
public static final int CODE = 2001;
public static final int LISTENING = 2002;
public static final int CONNECTED = 2003;
public static final int RECEIVING_FILE = 2004;
public static final int FILE_RECEIVED = 2005;
public static final int RECEIVE_ERROR = 2006;
private Context context;
private Handler mHandler;
private Intent i;
public FileReceiver(Context context, Handler mHandler) {
this.context = context;
this.mHandler = mHandler;
}
/* private boolean isPortAvailable(int port) {
boolean available;
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid port: " + port);
}
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
available = true;
} catch (IOException e) {
available = false;
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
}
}
}
return available;
}
*/
private int getRandomPort() {
//int port = 1001;
int port = 40500;
//do{
// port = (int) (MIN_PORT_NUMBER + 1 + Math.floor(Math.random()*(MAX_PORT_NUMBER - MIN_PORT_NUMBER-1)));
if(mDebug)
Log.i("FileReceiver","Trying port : " + port);
// }while(!isPortAvailable(port));
return port;
// return port;
}
public void getFile(){
int port = getRandomPort();
if(mDebug)
Log.i("FileReceiver","Port : " + port);
i = new Intent(context,ReceiverService.class);
i.putExtra(PORT,port);
i.putExtra(MESSENGER,new Messenger(mHandler));
context.startService(i);
}
public void close() {
context.stopService(i);
}
}
You can add a simple ProgressDialog box from your activity.
Something like :
// global variable
ProgressDialog mProgressDialog;
...
...
// inside onCreate
mProgressDialog = new ProgressDialog(ReceiveActivity.this);
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage("Downloading file ..");
...
...
// before file downloads
mProgressDialog.show();
...
...
// when file is downloaded
mProgressDialog.dismiss();
Edit :
In case of the given questions, this can be done as :
// assuming mProgressDialog is already initialised and configured.
case FileReceiver.CONNECTED:
Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
/******** Show the dialog box *********/
mProgressDialog.show(); // make sure that the file receiving starts immediately
// after the receiver is connected and that it do not
// require any action (like button click) after is connected
break;
case FileReceiver.RECEIVING_FILE :
Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();
/******** Dismiss the dialog box *********/
mProgressDialog.dismiss();
break;
case FileReceiver.FILE_RECEIVED :
File file = (File) msg.obj;
Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
fileReceiver.close();
/******** Dismiss the dialog box *********/
mProgressDialog.dismiss();
break;
You can also have a dialog box with progress percentage. Have a look into the ProgressDialog documentation.
There are methods like setProgressStyle(int style) with values like STYLE_HORIZONTAL. And then there are incrementProgressBy(int diff) that can be used to get a horizontal bar there.

How do I get installing apps package name?

I have a list of apk files in SDcard. It shows its' name and icon; everything works fine.
This app shows a list of uninstall apk files which are in Sdcrd, when user install any Apk from this list its' package name will save on database so when user goes to another screen that will show only that application which area install from SD card.
How do I get the name of apk file which the user clicks to install from list?
This is my code:
public class SdcardAPkMgr extends ListActivity {
private List<FileInformation> files_list;
private ProgressDialog mLoadDialog;
private Handler handler;
private static final int SCAN_APK_START = 101;
private static final int SCAN_APK_COMLETED = 102;
private boolean mJustCreate = true;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.apk_list);
files_list = new ArrayList<FileInformation>();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setupBatchHandler();
if (mJustCreate) {
thread.start();
}
mJustCreate = false;
}
private void setupBatchHandler() {
// TODO Auto-generated method stub
handler = new Handler() {
// #Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SCAN_APK_START: {
mLoadDialog =
ProgressDialog.show(SdcardAPkMgr.this, "",
getString(R.string.scan_apk_info));
mLoadDialog.setCancelable(false);
break;
}
case SCAN_APK_COMLETED: {
ApkListAdapter adapter = new ApkListAdapter(
SdcardAPkMgr.this, files_list);
SdcardAPkMgr.this.setListAdapter(adapter);
mLoadDialog.dismiss();
break;
}
default:
break;
}
super.handleMessage(msg);
}
};
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(SCAN_APK_START);
getAllApkFiles(new File("/sdcard"));
handler.sendEmptyMessage(SCAN_APK_COMLETED);
}
});
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
FileInformation information = files_list.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(information.getPath())),
"application/" +
"vnd.android.package-archive");
this.startActivity(intent);
}
public Drawable getAPKDrawable(String filePath) {
Drawable dr = null;
if (filePath != null) {
String PATH_PackageParser = "android.content.pm.PackageParser";
String PATH_AssetManager = "android.content.res.AssetManager";
try {
Class pkgParserCls = Class.forName(PATH_PackageParser);
Class[] typeArgs = new Class[1];
typeArgs[0] = String.class;
Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
Object[] valueArgs = new Object[1];
valueArgs[0] = filePath;
Object pkgParser = pkgParserCt.newInstance(valueArgs);
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo =
// packageParser.parsePackage(new
// File(apkPath), apkPath,
// metrics, 0);
typeArgs = new Class[4];
typeArgs[0] = File.class;
typeArgs[1] = String.class;
typeArgs[2] = DisplayMetrics.class;
typeArgs[3] = Integer.TYPE;
Method pkgParser_parsePackageMtd = pkgParserCls
.getDeclaredMethod("parsePackage",
typeArgs);
valueArgs = new Object[4];
valueArgs[0] = new File(filePath);
valueArgs[1] = filePath;
valueArgs[2] = metrics;
valueArgs[3] = 0;
Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(
pkgParser, valueArgs);
Field appInfoFld =
pkgParserPkg.getClass().getDeclaredField(
"applicationInfo");
ApplicationInfo info = (ApplicationInfo) appInfoFld
.get(pkgParserPkg);
Class assetMagCls = Class.forName(PATH_AssetManager);
Constructor assetMagCt = assetMagCls
.getConstructor((Class[]) null);
Object assetMag = assetMagCt.newInstance((Object[]) null);
typeArgs = new Class[1];
typeArgs[0] = String.class;
Method assetMag_addAssetPathMtd = assetMagCls
.getDeclaredMethod("addAssetPath", typeArgs);
valueArgs = new Object[1];
valueArgs[0] = filePath;
assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
Resources res = getResources();
typeArgs = new Class[3];
typeArgs[0] = assetMag.getClass();
typeArgs[1] = res.getDisplayMetrics().getClass();
typeArgs[2] = res.getConfiguration().getClass();
Constructor resCt =
Resources.class.getConstructor(typeArgs);
valueArgs = new Object[3];
valueArgs[0] = assetMag;
valueArgs[1] = res.getDisplayMetrics();
valueArgs[2] = res.getConfiguration();
res = (Resources) resCt.newInstance(valueArgs);
CharSequence label = null;
if (info.labelRes != 0) {
label = res.getText(info.labelRes);
}
if (info.icon != 0) {
dr = res.getDrawable(info.icon);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (dr == null) {
dr = getResources().getDrawable(R.drawable.default_apk_icon);
}
return dr;
}
private void getAllApkFiles(File root) {
File files[] = root.listFiles();
if (files != null)
for (File f : files) {
if (f.isDirectory()) {
getAllApkFiles(f);
} else {
if (f.getName().indexOf(".apk") > 0) {
// this.list.add(f);
String path = f.toString();
String name =
path.substring(path.lastIndexOf("/") + 1,
path.length());
this.files_list.add(new
FileInformation(name, path,
getAPKDrawable(path)));
}
}
}
}
}
APK is actually a zip file so you can just open it and read the package name from AndroidManifest.xml
Be aware the file is not plain and decoded somehow, but it's there

Reading a Bluetooth data stream from an Arduino with Android

The Situation
I'm trying to write an application that does one very simple task: when an NFC tag is detected with the appropriate AAR and URI it launches the application, uses data in the tag to connect to a specified Bluetooth radio (specified by the NFC tag) and waits to accept a data stream, which it converts to a string and displays on the screen.
When I run the application currently it simply exits immediately with three runtime exceptions. I would like it to wait passively instead of closing, and I do not understand the runtime exceptions.
The Exceptions
Unable to resume activity; NullPointerException
ParseTag(); exception line 127
onResume(); exception line 83
The Code
public class BlueNF extends Activity {
private BluetoothDevice mBluetoothDevice = null;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mBluetoothSocket = null;
private NfcAdapter mNfcAdapter = null;
private NdefMessage dashTag = null;
private static final int REQUEST_ENABLE_BT = 3;
private static final UUID SerialPortServiceClass_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream iStream = null;
public static String iValue = null;
public final static String EXTRA_MESSAGE = "com.yogafarts.hackpsuproject.BlueNF.iValue";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the content view
setContentView(R.layout.activity_blue_nf);
//Check for NFC
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//Check for Bluetooth
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void onResume() {
super.onResume();
//IntentFilter ndefTag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
//Get the current intent
Intent dashTagIntent = getIntent();
//Read extra intent data into tag object (Really just reading the NdefMessage into the dashTag object
dashTag = dashTagIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//Create a byte array of bluetooth hardware ID using ParseTag
byte[] mBluetoothInfo = ParseTag(dashTag);
//Create a bluetooth adapter object
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mBluetoothInfo);//Should be 0013EF00061A
try {
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(SerialPortServiceClass_UUID);
}
catch ( IOException e ) {
Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
}
//Cancel discovery because it's resource intensive (if it's active)
mBluetoothAdapter.cancelDiscovery();
//Connect to the device
try {
mBluetoothSocket.connect();
iStream = mBluetoothSocket.getInputStream();
//System.out.println(iStream);
//OutputStream oStream = mBluetoothSocket.getOutputStream();
}
catch ( IOException e ) {
try { mBluetoothSocket.close();
}
catch ( IOException e2 ) {
Log.e( "Bluetooth Socket", "IO Exception" );
}
}
iValue = iStream.toString();
viewMessage();
}
public byte[] ParseTag(NdefMessage ndef) {
NdefRecord[] mNdef = ndef.getRecords();
return mNdef[2].getPayload();
}
public void viewMessage() {
Intent intent = new Intent(this, DisplayMessage.class);
//TextView text = (TextView) findViewById(R.id.tv);
String message = iValue;//text.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.blue_n, menu);
return true;
}
}
And the activity that displays the text after the stream is read...
public class DisplayMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
TextView text = (TextView) findViewById(R.id.tv);
text.setText(com.yogafarts.hackpsuproject.BlueNF.iValue);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
}

Transferring files from usb to internal memory?

I am making a android app when I plug a flash drive into my tablet or phone via OTG usb, it will transfer the files off of it to a specified location. Now, it will transfer if I specify a file name, but how can I get it to transfer all the files without having to specify a name? I am using fileinput/fileoutput with byte array.
#SuppressLint("SdCardPath")
public class filetransfer extends Activity {
Button btnsend;
String extstorage = Environment.getExternalStorageDirectory().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityfiletransfer);
btnsend = (Button) findViewById(R.id.button1);
final Runtime runtime = Runtime.getRuntime();
try
{
runtime.exec("su -c");
}
catch(Exception e)
{
}
btnsend.setOnClickListener(new View.OnClickListener()
{
Context context = getApplicationContext();
CharSequence scs = "Folder Doesn't Exist, Creating now, Checking for Flash Drive....";
CharSequence mvng = "Folder already exist, checking now for flash drive....";
CharSequence chk1 = "Flash Drive detected, transferring files now.";
CharSequence chk2 = "Flash Drive Is Not Detected";
int duration = Toast.LENGTH_SHORT;
Toast bldng = Toast.makeText(context, scs, duration);
Toast mvfldr = Toast.makeText(context, mvng, duration);
Toast chkffd = Toast.makeText(context, chk1, duration);
Toast chkffd2 = Toast.makeText(context, chk2, duration);
#Override
public void onClick(View arg0)
{
File src = new File(extstorage + "/FILEBACKUP");
File usbdrive = new File(extstorage + "/usbStorage/sda1");
if(!src.exists())
{
src.mkdirs();
bldng.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
else
{
mvfldr.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
}
private void copyfiles()
{
String pathofd = "/sdcard/usbStorage/sda1";
String internalpath = "/sdcard/FILEBACKUP";
File dir = new File(pathofd);
File[] files = dir.listFiles();
for (File afile : files)
{
if(afile.isFile())
{
copyFile(afile.getAbsolutePath(), internalpath, afile.getName());
}
}
try
{
}
/*OutputStream myoutput = new FileOutputStream("/sdcard/FILEBACKUP");
InputStream myinput = new FileInputStream("/sdcard/usbStorage/");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer);
}
myoutput.flush();
myoutput.close();
myinput.close();
}*/
catch(Exception e)
{
}
}
private void copyFile(String absolutePath, String internalpath,
String name) {
// TODO Auto-generated method stub
try
{
OutputStream myoutput = new FileOutputStream(extstorage + "/FILEBACKUP/");
InputStream myinput = new FileInputStream(extstorage + "/usbStorage/sda1");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer, 0, length);
}
myoutput.flush();
myoutput.close();
myinput.close();
}
catch(Exception e)
{
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activityfiletransfer,
menu);
return true;
}
}
Just list the files in the directory:
String pathOfFlashDrive = <path of flash drive goes here>;
String internalPath = <internal destination path goes here>;
File dir = new File( pathOfFlashDrive );
File[] files = dir.listFiles();
for( File aFile : files ) {
if( aFile.isFile() ) {
copyFile( aFile.getAbsolutePath(), internalPath + aFile.getName() );
}
}

Categories

Resources