Receiver not asking user to accept file - android

I am having some difficulty sending files over Bluetooth. After it attempts to send the file, it will list the transfer as having 'failed' with an 'unknown file' error. I have double-checked my file path but am still having this problem. Do you guys see anything that I am missing? The target phone that is supposed to receive the file isn't showing the incoming file notification that asks the user to accept it or not. I believe this is where the failure is. Do you guys know how to pass the 'permission asking' (I guess we can call it that) to the target device?
//some code used from
// http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
package com.project.BluetoothTransfer_v1000;
import java.io.File;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("DefaultLocale")
public class TransferFragment extends Fragment{
private TextView filePathTextView;
private Button startTransferButton;
private ImageView bluetoothImage;
ProgressDialog transferDialog;
Handler updateBarHandler;
private static final int REQUEST_BLUETOOTH = 1;
private static final int DISCOVER_DURATION = 300;
Context context;
ArrayAdapter mArrayAdapter;
long timeCheckStart = 0;
long timeCheckEnd = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set the user interface layout for this activity
setRetainInstance(false);
View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);
context = this.getActivity();
filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
bluetoothImage.setClickable(true);
startTransferButton.setOnClickListener(new View.OnClickListener() {
//start transfer processes
#Override
public void onClick(View v){
//check to make sure the file path text view != null
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = -1;
//ensure the device being used has bluetooth capability
if (filePathTextView.getText().toString().length() > 4 && btAdapter != null){
//check-enable bluetooth
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//make the device discoverable and check to make sure device isn't already discoverable
if (timeCheckStart == 0 || System.currentTimeMillis() - 60000 > timeCheckStart){
timeCheckStart = System.currentTimeMillis();
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60);
startActivity(discoverableIntent);
}
// /storage/emulated/0/Test.jpg
// /storage/extSdCard/Test.jpg
String filePath = filePathTextView.getText().toString();
Toast.makeText(context, filePath, Toast.LENGTH_LONG);
String fileType = filePath.substring(filePath.length()-3,filePath.length()).toLowerCase();
//handles the sending of different file types
//################## where im having trouble ######################################
switch (fileType){
case "jpg": //allow to fall through to png
case "png": Intent pictureIntent = new Intent(Intent.ACTION_SEND);
pictureIntent.setType("image/*");
pictureIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(pictureIntent, "Send Image"));
break;
case "mp3": Intent audioIntent = new Intent(Intent.ACTION_SEND);
audioIntent.setType("audio/*");
audioIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(audioIntent, "Send Audio"));
break;
case "txt": Intent textIntent = new Intent(Intent.ACTION_SEND);
textIntent.setType("text/*");
textIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(textIntent, "Send Text"));
break;
default: new AlertDialog.Builder(context).setTitle("Alert")
.setMessage("The file type submitted is not supported: ("+fileType+")")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show(); break;
}//end fileType switch
}//if text view null (if)
else {
//alert user to input file path
new AlertDialog.Builder(context).setTitle("Error")
.setMessage("Please insert a filename to send and be sure to include the type extension.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}//bt equipped/text view null check (else)
}//end anon class
});
bluetoothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//display dialog showing program specs and creators
new AlertDialog.Builder(context).setTitle("About")
.setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
.setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
});
return v;
}
}

Maybe this answer can help you:
https://stackoverflow.com/a/19618432/3743093
In short: you can't pass an URI created with
Uri uri = Uri.parse(String);
as in
pictureIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
beacuse it lacks info like TITLE and MIME_TYPE.
That's the reason why file type is unknown (missing) and throws this error.
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/*");
Uri uri = getContentResolver().insert(Uri.parse(filename),
values);
pictureIntent.putExtra(Intent.EXTRA_STREAM, uri);
Hope this helps.

Related

Bluetooth app made with library (https://github.com/OmarAflak/Bluetooth-Library) crashes

I'm working on a simple app, essentially to send data over Bluetooth.
My MainActivity:
package in.justrobotics.jrbluetoothcontrol;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import me.aflak.bluetooth.Bluetooth;
import me.aflak.bluetooth.BluetoothCallback;
import me.aflak.bluetooth.DiscoveryCallback;
public class MainActivity extends AppCompatActivity {
Bluetooth bluetooth;
private ArrayAdapter<String> mBTArrayAdapter;
String address,name;
public void composeEmail(String message) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "shlokj#gmail.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, "Would like to get in touch");
intent.putExtra(Intent.EXTRA_TEXT, message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
public void sendEmail () {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Send a message: ");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Message = input.getText().toString();
composeEmail(Message);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothOn();
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
bluetooth = new Bluetooth(getApplicationContext());
if (bluetooth==null){
Toast.makeText(getApplicationContext(),"Bluetooth null",Toast.LENGTH_SHORT).show();
}
if (bluetooth!=null){
Toast.makeText(getApplicationContext(),"Bluetooth not null",Toast.LENGTH_SHORT).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
Button openController = (Button) findViewById(R.id.open_controller);
openController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startController = new Intent(MainActivity.this,ControllerActivity.class);
//startController.putExtra("BLUETOOTH_CONNECTED_THREAD",mConnectedThread);
startActivity(startController);
}
});
Button openAccelController = (Button) findViewById(R.id.open_accel_controller);
openAccelController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startControllerAccel = new Intent(MainActivity.this,AccelerometerControl.class);
startActivity(startControllerAccel);
}
});
bluetooth.setBluetoothCallback(new BluetoothCallback() {
#Override
public void onBluetoothTurningOn() {
}
#Override
public void onBluetoothOn() {
}
#Override
public void onBluetoothTurningOff() {
}
#Override
public void onBluetoothOff() {
}
#Override
public void onUserDeniedActivation() {
}
});
bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
#Override public void onDiscoveryStarted() {}
#Override public void onDiscoveryFinished() {}
#Override public void onDeviceFound(BluetoothDevice device) {}
#Override public void onDevicePaired(BluetoothDevice device) {}
#Override public void onDeviceUnpaired(BluetoothDevice device) {}
#Override public void onError(String message) {}
});
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_btdevices, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select your device");
alertDialog.setMessage("A JR Bluetooth device name is of the form JR_X");
ListView devicesListView = (ListView) convertView.findViewById(R.id.mDevicesListView);
devicesListView.setAdapter(mBTArrayAdapter);
devicesListView.setOnItemClickListener(mDeviceClickListener);
alertDialog.show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String connectStatus="";
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
//mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
name = info.substring(0, info.length() - 17);
if (bluetooth.isConnected()){
connectStatus="Connected";
}
if (!bluetooth.isConnected()){
connectStatus="Not connected";
}
Toast.makeText(getBaseContext(), connectStatus, Toast.LENGTH_SHORT).show();
bluetooth.connectToAddress(address);
Toast.makeText(getBaseContext(), "Connected (hopefully)", Toast.LENGTH_SHORT).show();
bluetooth.send("test");
Toast.makeText(getBaseContext(), "Sent data (hopefully)", Toast.LENGTH_SHORT).show();
}};
#Override
protected void onStart() {
super.onStart();
bluetooth.onStart();
bluetooth.enable();
}
#Override
protected void onStop() {
super.onStop();
bluetooth.onStop();
}
private void bluetoothOn(){
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
//mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
}
Stack traces:
2019-04-09 20:16:48.222 23737-23737/in.justrobotics.jrbluetoothcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.justrobotics.jrbluetoothcontrol, PID: 23737
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:185)
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:201)
at in.justrobotics.jrbluetoothcontrol.MainActivity$7.onItemClick(MainActivity.java:197)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1164)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3154)
at android.widget.AbsListView$3.run(AbsListView.java:4097)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
The custom Bluetooth class: https://github.com/OmarAflak/Bluetooth-Library/blob/master/bluetooth/src/main/java/me/aflak/bluetooth/Bluetooth.java
My code is crashing at the line bluetooth.send("test"); with a NullPointerException, and I can't see why. I'm a beginner with Bluetooth on Android; help will be appreciated.
The final outcome I hope I will be able to get is to simply connect to a device and send data, and even that isn't happening.
Edit: I'm facing another problem as well now. I pass the String address to the second activity (https://gist.github.com/shlokj/12c4e2c62ca0f5284c5c3c041775654f) from the first activity (https://gist.github.com/shlokj/f80d0902ad1a366ab03e178164968cfb) through an intent. There, I try to connect at line 163 (bluetoothObject.connectToAddress(address);), and it crashes with a NullPointerException. I have no idea why, because I check that the Bluetooth object and address are not null with an if statement. Stack traces: https://gist.github.com/shlokj/56e3c9e311dea6f77a1acd8953a317c8 Whole repository: https://github.com/shlokj/JR-Bluetooth-Control.
So, in a nutshell, I now need to be also able to connect properly, leave alone sending data.
I just went through the library link you provided and it seems someone else faced the similar issue given here:
https://github.com/OmarAflak/Bluetooth-Library/issues/16
And it turned out be the connection wasn't established yet,so before calling send please check if the device is connected by using isConnected() function.
You shouldn't call send before the connection is established properly.you can set callback for the same using setDiscoveryCallback and do work inside most probable after you get confirmation in void onDevicePaired(BluetoothDevice device).
Edit 1: from the comments.
Are you sure it is in onDevicePaired() that I am supposed to send
data?
Maybe not,I think i misunderstood the example given by library author,now i think you should do it on onDeviceConnected.
Is there any other method that gets called when it is connected?
Yes,you can set a callback for that using following:
bluetooth.setDeviceCallback(new DeviceCallback() {
#Override
public void onDeviceConnected(BluetoothDevice device) {
// do your work here.
}
#Override
public void onDeviceDisconnected(BluetoothDevice device, String message) {
}
#Override
public void onMessage(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void onConnectError(BluetoothDevice device, String message) {
}
});
Edit 2:
There, I try to connect at line
163(bluetoothObject.connectToAddress(address);), and it crashes with a
NullPointerException.
This crash happens because BluetoothAdapter isn't initialized yet,so when you call bluetoothObject.connectToAddress(address) it throws NullPointerException.
You need to initialize that before connecting as following:
bluetoothObject = new Bluetooth(getApplicationContext());
bluetoothObject.onStart();//this is the line that initializes adapter.
bluetoothObject.enable();

android -How to update application inside application

I've seen this in some application , the application size is about 6 mb but it download a file about 100kb and update the application .
it's very interesting , I've searched alot but I couldn't find any way to do it .
How can I do so ?
thanks
I do it using the below class, but it does require downloading the new APK, so it may not be exactly what you need. It is done this way because we do not use the play store.
If there is an update available, start the Runnable class.
It starts the download, and when the download is completed it asks if you want to update, then starts the update.
All you need to do is figure out how to host the APK file. I use a windows server and IIS7, with a mime setup so it is recognized by android as an installable APK.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.AlertDialog;
import android.app.DownloadManager;
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.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class GetUpdate implements Runnable{
Context cxt;
String line;
String filepath = "";
int continueornot=0;
ProgressBar progBar;
Button buttOk;
DownloadManager mgr=null;
long lastDownload=-1L;
public GetUpdate(Context contextIn, String lineIn, ProgressBar progressBar,Button okButtIn){
cxt = contextIn;
line = lineIn;
this.progBar = progressBar;
this.buttOk = okButtIn;
}
#Override
public void run() {
filepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the download?");
// Set an EditText view to get user input
//final EditText serverURL = new EditText(cxt);
//alert.setView(serverURL);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String tempFilepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
File myExternalFile = new File(filepath);
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null){
for(int x=0;x<sdDirList.length;x++){
String fileNameString = sdDirList[x].toString();
System.out.println("File: " + sdDirList[x].toString());
if(fileNameString.trim().equalsIgnoreCase("podcodes.txt")
||fileNameString.trim().equalsIgnoreCase("vehiclesTrailers.txt")
||fileNameString.trim().equalsIgnoreCase("checks.txt")
||sdDirList[x].toString().endsWith(".apk")){
sdDirList[x].delete();
}
}
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the update?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(cxt.getApplicationContext(), "Updating!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
String lastDownloaded = mgr.getUriForDownloadedFile(lastDownload).toString();
//String lastDownloadFileName = lastDownloaded.substring(lastDownloaded.lastIndexOf("/")+1);
intent.setDataAndType(Uri.parse(lastDownloaded), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cxt.startActivity(intent);
Globals.setExit(true);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
});
alert.show();
}
};
mgr=(DownloadManager)cxt.getSystemService(Context.DOWNLOAD_SERVICE);
cxt.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
BroadcastReceiver onNotificationClick=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "Downloading InCab Update!", Toast.LENGTH_LONG).show();
}
};
cxt.registerReceiver(onNotificationClick,
new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
Uri uri=Uri.parse(Globals.getServerURL()+"/LatestAndroid/"+line.trim());
//Environment
// .getExternalStoragePublicDirectory("MyFileStorage/"+line.trim())
// .mkdirs();
lastDownload=
mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true)
.setTitle(line.trim())
.setDescription("Incab Update.")
.setDestinationInExternalFilesDir(cxt,"MyFileStorage", line.trim()));
Toast.makeText(cxt.getApplicationContext(), "Downloading!", Toast.LENGTH_LONG).show();
continueornot=1;
progBar.setVisibility(View.VISIBLE);
buttOk.setVisibility(View.VISIBLE);
buttOk.setText("Downloading..");
buttOk.setEnabled(false);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
continueornot=2;
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
//cancel(true);
}
});
alert.show();
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
}

registerReceiver(...) getting passed ClickListener

I am having some difficulty passing the right information to set up Bluetooth discovery and pairing. I have been following the Android developer example documents pretty closely and have not been able to figure out what I need to pass to this method. This is the site I have been using, for reference.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
TransferFragment:
//some code used from
// http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
package com.project.BluetoothTransfer_v1000;
import java.util.Set;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TransferFragment extends Fragment{
private TextView filePathTextView;
private Button startTransferButton;
private ImageView bluetoothImage;
ProgressDialog transferDialog;
Handler updateBarHandler;
private static final int REQUEST_BLUETOOTH = 1;
private static final int DISCOVER_DURATION = 300;
Context context;
ArrayAdapter mArrayAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set the user interface layout for this activity
setRetainInstance(false);
View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);
context = this.getActivity();
filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
bluetoothImage.setClickable(true);
startTransferButton.setOnClickListener(new View.OnClickListener() {
//start transfer processes
#SuppressWarnings("unchecked")
#Override
public void onClick(View v){
//check to make sure the file path text view != null
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = -1;
//ensure the device being used has bluetooth capability
if (btAdapter != null){
//check-enable bluetooth
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//ensure the textview isn't empty
//check if filepath is null
if (filePathTextView.getText().toString().length() != 0){
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
//check if there are paired devices
if (pairedDevices.size() > 0){
//loop through paired devices
for (BluetoothDevice device: pairedDevices){
//add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}//end found paired devices if
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//COMPILER ERROR BELOW ######################################################
//"This method registerReceiver(BroadcastReceiver, IntentFilter)
//is undefined for type new View.OnClickListener
registerReceiver(mReceiver, filter);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
btAdapter.cancelDiscovery();
}//
else {
//alert user to input file path
new AlertDialog.Builder(context).setTitle("Error")
.setMessage("Please insert a filename to send.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}//ifnull (else)
}//bt equipped check
}//end anon class
});
bluetoothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//display dialog showing program specs and creators
new AlertDialog.Builder(context).setTitle("About")
.setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
.setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
});
return v;
}
}
TransferActivity:
package com.project.BluetoothTransfer_v1000;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class TransferActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
TransferFragment fragment = new TransferFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
}
Try:
TransferFragment.this.getActivity().registerReceiver(mReceiver, filter);
Instead of:
registerReceiver(mReceiver, filter);
Because the method registerReceiver is part of the Activity and not the OnClickListener. This is why the error message complains about not found method in OnClickListener:
This method registerReceiver(BroadcastReceiver, IntentFilter)
is undefined for type new View.OnClickListener

Android app crashing (shared preferences)

I am building an android game that uses saves. That means that a user can open up to 5 unique saves on the game. to create a new save, im using SharedPreferences to let the user enter a save name and store it in my SharedPreferences folder, and then redirect the user to the main game Activity with an Intent Extra that tells the game activity what save to open.
In the design it all sounds ok, but for some reason my application just keeps Force closing.
I dont have any code errors inside eclipse, and even LogCat shows no error. I dont know what
is going on...
Here is my code:
package ent.com;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Saves extends ListActivity{
String saves[] = { "Empty save", "Empty save", "Empty save", "Empty save", "Empty save"};
public static String filename = "SharedData";
SharedPreferences someData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
someData = getSharedPreferences(filename, 0);
String save1 = someData.getString("0", "Empty save");
String save2 = someData.getString("1", "Empty save");
String save3 = someData.getString("2", "Empty save");
String save4 = someData.getString("3", "Empty save");
String save5 = someData.getString("4", "Empty save");
saves[0] = save1;
saves[1] = save2;
saves[2] = save3;
saves[3] = save4;
saves[4] = save5;
setListAdapter(new ArrayAdapter<String>(Saves.this, android.R.layout.simple_list_item_1, saves));
}
#Override
protected void onListItemClick(ListView l, View v,int position, long id) {
final String clicked = saves[position];
final String pos = getString(position);
super.onListItemClick(l, v, position, id);
if(clicked=="Empty save"){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Input name");
alert.setMessage("Give your team a name:");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString(pos, value);
editor.commit();
try{
Class Joe = Class.forName("ent.com.TestActivity");
Intent Joey = new Intent(Saves.this, Joe);
Joey.putExtra("save", clicked);
startActivity(Joey);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent back = new Intent("ent.com.MENU");
startActivity(back);
}
});
alert.show();
}else{
try{
Class ourClass = Class.forName("ent.com.TestActivity");
Intent ourIntent = new Intent(Saves.this, ourClass);
ourIntent.putExtra("save", clicked);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
}
Thanks for any help.
So far all I see that is a big problem is this :
if (clicked=="Empty save")
== is for numbers and reference comparison. you're looking for:
if (clicked.equals("Empty save"))
which will actually compare the strings in question

Android PayPal OnClickListener is not working

I am trying to connect the PayPal to my app. Basically my app will have one Scan button and one PayPal Button on the screen. Scan button calls the ZXing library and scan the barcodes. However, I still cannot connect with PayPal button yet because OnClickListener and getApplicationContext() is not working. I have read PayPal documentation , StackOverflow and still couldn't work out. I am wondering what is wrong with my code? Any Suggestions please?Thank you for your help :)
package thet.mon.aye;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalReceiverDetails;
import com.paypal.android.MEP.PayPalPayment;
import android.content.Context;
public class DevilscanActivity extends ListActivity implements onClickListener {
/** Called when the activity is first created. */
private static final int ACTIVITY_CREATE=0;
private BarcodeDBAdapter mDbHelper;
private Cursor mNotesCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbHelper = new BarcodeDBAdapter(this);
mDbHelper.open();
fillData();
PayPal ppObj = PayPal.getInstance();
final Button scanButton = (Button) findViewById(R.id.button);
scanButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent("com.google.zxing.client.android.SCAN");
intent1.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent1, 0);
}
});
CheckoutButton launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener((OnClickListener) this);
((RelativeLayout)findViewById(R.id.RelativeLayout01)).addView(launchPayPalButton);
}
static public PayPal initWithAppID(Context context, String appID, int server)
{
PayPal ppObj;
if (ppObj == null) {
try {
ppObj = PayPal.initWithAppID(getApplicationContext(),"", PayPal.ENV_NONE);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
ppObj.setShippingEnabled(false);
}
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{BarcodeDBAdapter.KEY_BARCODE_TYPE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.barcode_row, mNotesCursor, from, to);
setListAdapter(notes);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent1) {
//intent1 = new Intent("com.google.zxing.client.android.SCAN");
// intent1.putExtra("SCAN_MODE", "QR_CODE_MODE");
// startActivityForResult(intent1, 0);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent1.getStringExtra("SCAN_RESULT");
String format = intent1.getStringExtra("SCAN_RESULT_FORMAT");
mDbHelper.createNote(contents, format);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}

Categories

Resources