In my code, after I run startDiscovery().
Nothing seems to happen and I don't know why.
As #Mitch suggest, I changed back to using button to do startDiscovery.
But now it seems worse as it crashes right after I press the button.
public class BTActivity extends AppCompatActivity{
private static final String TAG = "BTActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
private EcgView mEcgView;
//Create a BroadcastReceiver for
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BTAdapter.ACTION_STATE_CHANGED)){
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BTAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG,"onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG,"onReceive: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG,"onReceive: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG,"onReceive: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)){
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode){
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Enabled");
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Able to receive connection");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Not able to receive connection");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG,"mBroadcastReceiver2: Connecting");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG,"mBroadcastReceiver2: Connected");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3cases:
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDED");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDING");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE){
Log.d(TAG, "BroadcastReceiver: BOND_NONE");
}
}
}
};
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.enabledisable:
//if BT is enable, turn it off; if not then prompt user to enable BT;
if (!BTAdapter.getDefaultAdapter().isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(BTAdapter.getDefaultAdapter().isEnabled()) {
BTAdapter.getDefaultAdapter().disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
return true;
case R.id.enablediscoverable:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(BTAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2, intentFilter);
return true;
case R.id.discover:
Intent intent = new Intent(getApplicationContext(),SearchActivity.class);
startActivity(intent);
/*
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
*/
return true;
default:
return false;
}
}
/*
private void checkBTPermissions() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK Version < LOLLIPOP");
}
}
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,filter);
//lvNewDevices.setOnItemClickListener(BTActivity.this);
//Check if the phone support BT
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter == null) {
//System.exit(0);
}
//mConnectThread = new ConnectThread(mDevice);
//mConnectThread.start();
mEcgView = (EcgView) findViewById(R.id.ecgView);
}
public void toMainActivity(View view){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
So after the click on the Search Devices from the action bar, the app will go to another activity. But when I click on Start Searching in that activity, the app crashes. Don't know why as logic should be the same.
public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "SearchActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
lvNewDevices.setOnItemClickListener(SearchActivity.this);
}
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
public void btnDiscover(View view){
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
}
public void backToBT(View view){
Intent intent = new Intent(getApplicationContext(),BTActivity.class);
startActivity(intent);
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Cancel Discovery as it's costly
BTAdapter.cancelDiscovery();
Log.d(TAG,"onItemClick:Clicked a Device");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG,"onItemClick: Device Name: " + deviceName);
Log.d(TAG,"onItemClick: Device Address " + deviceAddress);
//Bonding
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
And the manifest is attached
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ted.pawan462">
<user-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<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>
<activity android:name=".BTActivity" />
<activity android:name=".SearchActivity"></activity>
</application>
</manifest>
This is the Logcat
1-07 21:40:39.633 32744-367/com.example.ted.pawan462 I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (Ia6c73e7530)
OpenGL ES Shader Compiler Version: E031.29.00.00
Build Date: 12/04/15 Fri
Local Branch: mybranch17080070
Remote Branch: quic/LA.BF.1.1.3_rb1.5
Local Patches: NONE
Reconstruct Branch: NOTHING
01-07 21:40:39.635 32744-367/com.example.ted.pawan462 I/OpenGLRenderer: Initialized EGL, version 1.4
01-07 21:40:41.786 32744-32744/com.example.ted.pawan462 I/ListPopupWindow: Could not find method setEpicenterBounds(Rect) on PopupWindow. Oh well.
01-07 21:40:41.812 32744-32744/com.example.ted.pawan462 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
01-07 21:43:54.309 32744-367/com.example.ted.pawan462 D/OpenGLRenderer: endAllStagingAnimators on 0x9db76280 (MenuPopupWindow$MenuDropDownListView) with handle 0x9d2784b0
01-07 21:43:55.320 32744-32744/com.example.ted.pawan462 D/SearchActivity: Looking for unpaired devices
01-07 21:43:55.327 32744-32744/com.example.ted.pawan462 D/AndroidRuntime: Shutting down VM
01-07 21:43:55.329 32744-32744/com.example.ted.pawan462 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ted.pawan462, PID: 32744
Theme: themes:{default=overlay:com.wsdeveloper.galaxys7, iconPack:com.wsdeveloper.galaxys7, fontPkg:com.wsdeveloper.galaxys7, com.android.systemui=overlay:com.wsdeveloper.galaxys7, com.android.systemui.navbar=overlay:com.wsdeveloper.galaxys7}
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isDiscovering()' on a null object reference
at com.example.ted.pawan462.SearchActivity.btnDiscover(SearchActivity.java:58)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
I think I might have made it worse.
The only thing that stands out to me is you have checkBTPermissions() commented out. But I'm assuming you've tried uncommenting that.
Also make sure that your other devices are set to "discoverable" or the phone won't be able to see them.
Other than that I think it looks pretty good. Maybe something weird going on because your using a menu? Not sure :(.
Related
Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
2021-06-26 05:10:29.573 24952-24952/c.bawp.securemessenger D/AndroidRuntime: Shutting down VM
2021-06-26 05:10:29.587 24952-24952/c.bawp.securemessenger E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.bawp.securemessenger, PID: 24952
android.content.ActivityNotFoundException: Unable to find explicit activity class {c.bawp.securemessenger/c.bawp.securemessenger.ChatController}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:574)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:560)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at c.bawp.securemessenger.ChooseActivity$1.onClick(ChooseActivity.java:26)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2021-06-26 05:10:29.657 24952-24952/c.bawp.securemessenger I/Process: Sending signal. PID: 24952 SIG: 9
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}
Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}
I'm attempting to sign in or sign up using fragments, and after a successful sign-in/sign up, the HomeActivity supposed to load. The issue is that when I click the sign-in/sign up button, it returns to the same fragment instead of going to the HomeActivity.class. The app's initialization page is called LoginRegistrationActivity.class where it will call the SignIn fragment. I confirmed that Sign in/Sign Up is working well, but I am unable to navigate to the HomeActivity.class after successful authentication. I'm not sure if there is an issue with the AndroidManifest.xml file.
I got this logcat error after I clicked sign in:
java.lang.ClassCastException: com.fyp.selfzen.fragments.O_LoginRegistration.SignIn cannot be cast to java.util.concurrent.Executor
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn.login(SignIn.java:124)
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn$1.onClick(SignIn.java:87)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
SignIn.java fragment
public class SignIn extends Fragment{
private EditText editText_email, editText_password;
private String email, password;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
LoginRegisrationActivity loginRegistration;
public SignIn(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
}
public static SignIn newInstance(LoginRegisrationActivity loginRegistration) {
SignIn fragment = new SignIn(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_email = view.findViewById(R.id.editText_email_login_activity);
editText_password = view.findViewById(R.id.editText_password_login_activity);
TextView button_login = view.findViewById(R.id.button_login_activity);
TextView textView_signup_login = view.findViewById(R.id.textView_signup_login);
final SmoothCheckBox checkBox = view.findViewById(R.id.checkbox_login_activity);
checkBox.setChecked(false);
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = editText_email.getText().toString();
password = editText_password.getText().toString();
editText_email.clearFocus();
editText_password.clearFocus();
login(email, password);
}
});
textView_signup_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignUp f2 = SignUp.newInstance(loginRegistration);
loginRegistration.loadFrag(f2, getResources().getString(R.string.regis));
}
});
return view;
}
public void login(String email, String password) {
editText_email.setError(null);
editText_password.setError(null);
if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if(password.isEmpty()){
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else {
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Successfully sign in!", Toast.LENGTH_LONG).show();
// Intent i = new Intent(loginRegistration, HomeActivity.class); //First try to go to HomeActivity
Intent i = new Intent(getContext(), HomeActivity.class); //Second try
startActivity(i);
//loginRegistration.finish();
} else {
Toast.makeText(getContext(), "Sign in failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
} //onComplete
}); // firebaseAuth
}// else
} // login end
}
SignUp.java fragments
public class SignUp extends Fragment{
private EditText editText_name, editText_email, editText_password, editText_phoneNo;
private String name, email, password, phoneNo;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
LoginRegisrationActivity loginRegistration;
public SignUp(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
// Required empty public constructor
}
public static SignUp newInstance(LoginRegisrationActivity loginRegistration) {
SignUp fragment = new SignUp(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_name = view.findViewById(R.id.editText_name_register);
editText_email = view.findViewById(R.id.editText_email_register);
editText_password = view.findViewById(R.id.editText_password_register);
editText_phoneNo = view.findViewById(R.id.editText_phoneNo_register);
TextView button_submit = view.findViewById(R.id.button_submit);
TextView textView_login = view.findViewById(R.id.textView_login_register);
// Go to login page
textView_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn f1 = SignIn.newInstance(loginRegistration);
loginRegistration.loadFrag(f1, getResources().getString(R.string.login));
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText_name.getText().toString();
email = editText_email.getText().toString();
password = editText_password.getText().toString();
phoneNo = editText_phoneNo.getText().toString();
form();
}
});
return view;
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void form() {
editText_name.setError(null);
editText_email.setError(null);
editText_password.setError(null);
editText_phoneNo.setError(null);
if (name.equals("") || name.isEmpty()) {
editText_name.requestFocus();
editText_name.setError(getResources().getString(R.string.please_enter_name));
}
else if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if (password.equals("") || password.isEmpty()) {
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else if (phoneNo.equals("") || phoneNo.isEmpty()) {
editText_phoneNo.requestFocus();
editText_phoneNo.setError(getResources().getString(R.string.please_enter_phone));
}
else {
editText_name.clearFocus();
editText_email.clearFocus();
editText_password.clearFocus();
editText_phoneNo.clearFocus();
}
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Successfully registered!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(loginRegistration, HomeActivity.class);
Intent i = new Intent(getActivity(), HomeActivity.class);
startActivity(i);
//loginRegistration.finish();
}
else{
Toast.makeText(getContext(), "Sign up failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
} // end of form
}
LoginRegistrationActivity.class
public class LoginRegisrationActivity extends AppCompatActivity {
private String curent;
VideoView vide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_regisration);
vide = findViewById(R.id.vide);
String video_url = "android.resource://" + getPackageName() + "/" + R.raw.login_video;
Uri videoUri = Uri.parse(video_url);
vide.setVideoURI(videoUri);
vide.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
vide.requestFocus();
vide.start();
}
});
SignIn f1 = SignIn.newInstance(this);
loadFrag(f1, getResources().getString(R.string.login));
}
public void loadFrag(Fragment f1, String name) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(!name.equals(curent)){
curent =name;
ft.replace(R.id.frame_layout, f1, name);
}
ft.commitAllowingStateLoss();
}
}
AndroidManifest.xml
<activity
android:name="com.fyp.selfzen.activities.LoginRegisrationActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.fyp.selfzen.activities.HomeActivity"
android:label="#string/title_activity_home"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Have you solved your problem yet?
I ran into a similar but different issue when trying to use Fragments with FirebaseAuth. All of the documentation I found only referenced using Activities. Changing .addOnCompleteListener to .addOnSuccessListener and adding an .addOnFailureListener made my app work as expected. My app was originally crashing because of the Executor even though it would successfully authenticate users; the success/failure listeners fixed my issue.
My original code (written with help from Firebase Docs):
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( (java.util.concurrent.Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
FragmentFactory.startAdminFragment((MainActivity) getActivity());
} else
Toast.makeText( getContext(), "Authentication failed.", Toast.LENGTH_SHORT ).show();
}
});
}
Current/Working code:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener( new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FragmentFactory.startAdminFragment((MainActivity) getActivity());
}
})
.addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// If sign in fails, display a message to the user.
Log.d(TAG, "signInWithEmail:failure");
Toast.makeText( getContext(), e.getMessage(), Toast.LENGTH_LONG ).show();
}
} );
}
Note:
I only have 1 Activity so I was able to login and continue to my desired Fragment but you should be able to modify my code (FragmentFactory.startAdminFragment((MainActivity) getActivity());) to continue to your HomeActivity.class
This video helped a lot: https://www.youtube.com/watch?v=fPhy1PKR1Wg
I hope this helps.
In SignIn.java and SignUp.java fragment you add addOnCompleteListener() for firebaseAuth. So, pass arguments in it,
Instead of,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {}
To,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(getContext(), new OnCompleteListener<AuthResult>() {}
IF, getContext() not work then try to write getActivity().
I pass an integer value (guide) to the next class(activity) like this:
in different activities.. first:
public void onClick(View v) {
Intent intent002a = new Intent(getApplicationContext(), GameOver002a.class);
intent002a.putExtra("guide", 11001001);
startActivity(intent002a);
}
second:
public void onClick(View v) {
Intent intent003a = new Intent(getApplicationContext(), GameOver002a.class);
intent003a.putExtra("guide", 11002001);
startActivity(intent003a);
}
and so on..
Then I receive the intent:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game_over002a);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
super.onStart();
UnityAds.changeActivity(this);
UnityAds.init( this, "*******", this);
UnityAds.setDebugMode(true);
UnityAds.setTestMode(true);
TextView neinTextView = (TextView) findViewById(R.id.nein_textview002a);
if (neinTextView != null) {
neinTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
});
}
TextView jatextview = (TextView) findViewById(R.id.ja_textview002a);
if (jatextview != null) {
jatextview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(GameOver002a.this)
.setMessage("Watch a short ad to continue at the last checkpoint?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
if (UnityAds.setZone("rewardedVideo") && UnityAds.canShow()) {
UnityAds.show();
}}
}).create().show();
}
});
}
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(R.string.zurück_zum_menü_frage)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
}).create().show();
}
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onVideoStarted() {
}
#Override
public void onVideoCompleted(String s, boolean b) {
levelAuswahl();
}
#Override
public void onFetchCompleted() {
}
#Override
public void onFetchFailed() {
TextView jatextview = (TextView) findViewById(R.id.ja_textview002a);
if (jatextview != null) {
jatextview.setText(R.string.videoladen_fail);
jatextview.setClickable(false);
}
}
#Override
public void onResume()
{
super.onResume();
UnityAds.changeActivity(this);
onNewIntent(getIntent());
}
public void levelAuswahl() {
int guide;
guide = getIntent().getIntExtra("guide",0);
if (guide == 11001001) {
Intent intent = new Intent(getApplicationContext(), Story001a.class);
startActivity(intent);
}else if (guide == 11002001) {
Intent intent = new Intent(getApplicationContext(), Story002b.class);
startActivity(intent);
}else if (guide == 11007001) {
Intent intent = new Intent(getApplicationContext(), Story004a.class);
startActivity(intent);
} else {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
}
to choose the right activity.. EVERY PART OF THE STORY HAS HIS OWN ACTIVITY
following scenario:
I start the app and fail at the Story002a activity .. then I pass an integer value (guide) with an intent .. After watching an ad succesful the method levelAuswahl() is called (level chooser). it receives the intent and takes the right if clause and I start again at Story001.. THIS PART WORKS CORRECT
BUT.. if I fail at Story003a the value guide is passed with an intent exact as in Story002a..but this time in the the same activitie opens although I use onNewIntent()..
what do I need to change? Any ideas?
Thanks in advance!
here is the manisfest:
<?xml version="1.0" encoding="utf-8"?>
<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/Theme.AppCompat.NoActionBar">
<activity android:name=".Startbildschirm"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Tutorial"
android:screenOrientation="landscape"/>
<activity android:name=".Support"
android:screenOrientation="landscape"/>
<activity android:name=".GameOver"
android:screenOrientation="landscape"/>
<activity android:name=".Story001a"
android:screenOrientation="landscape"/>
<activity android:name=".Story002a"
android:screenOrientation="landscape"/>
<activity android:name=".Story002b"
android:screenOrientation="landscape"/>
<activity android:name=".Story003a"
android:screenOrientation="landscape"/>
<activity android:name=".Story003b"
android:screenOrientation="landscape"/>
</application>
getIntent() returns the Intent that the Activity was started with (ie: the one that caused onCreate() to be called. If you are returning to an existing instance of GameOver, and onCreate() is not being called, then you will get the new Intent delivered in onNewIntent(). The Intent passed to onNewIntent() should contain the correct extra value.
If this is not your case, please give more details about your situation.
Instead of using
android:launchMode="singleTask" //or singleTop
is used
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
and everything works fine
use onNewIntent() like this to get your new intent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
I am currently using the AlarmManager, Broadcast receiver and Intent Service to implement upload service to server rub by background instead of Ui Main Thread but the problem is when it comes to the execution , there is no response for the upload message . At least, in the logcat, I can see any message reporting the progress for the upload weven I have typed and tested correctly.
But afer the upload service is finished , it shows
java.lang.RuntimeException: Handler (android.os.Handler) sending message to a Handler on a dead thread
Would you please tell me what else is missing ?
The below is my code
Intnt Service
public class TaskService extends IntentService {
public TaskService() {
super("TaskService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent arg0) {
// Do some task
Log.i("TaskService","Service running");
boolean ss = uploadRecording("TEST_RECORD" , "test.mp4" , "http://210.177.246.83/uploadFile");
Log.d("Is file uploaded" , String.valueOf(ss));
}
public boolean uploadRecording(String directoryname , String filename , String destination) {
// TODO Auto-generated method stub
boolean result = false;
String destinationPath = destination;
File tes = new File(Environment.getExternalStorageDirectory() + File.separator + directoryname);
File frecord = new File(tes.getAbsolutePath() + File.separator + filename);
if(tes.exists()){
if(frecord.exists()){
List< NameValuePair> httpContents = new ArrayList< NameValuePair>();
httpContents.add(new BasicNameValuePair("file",frecord.getAbsolutePath()));
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(destinationPath);
try{
//setup multipart entity
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0;i< httpContents.size();i++){
//identify param type by Key
if(httpContents.get(i).getName().equals("file")){
File f=new File(httpContents.get(i).getValue());
FileBody fileBody=new FileBody(f);
entity.addPart("file"+i,fileBody);
}
}
post.setEntity(entity);
//create response handler
//execute and get response
HttpResponse uploadReponse = client.execute(post);
Log.d("debug" , "Response : " + uploadReponse);
if(uploadReponse.getStatusLine().getStatusCode() == 200){
result = true;
Toast.makeText(getApplicationContext(), "Upload Success", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
return result;
}
}
BroadCast Receiver
public static String ACTION_ALARM = "com.alarammanager.alaram";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Alarm Receiver", "Entered");
Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
String action = bundle.getString(ACTION_ALARM);
if (action.equals(ACTION_ALARM)) {
Log.i("Alarm Receiver", "If loop");
Toast.makeText(context, "If loop", Toast.LENGTH_SHORT).show();
Intent inService = new Intent(context, TaskService.class);
inService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(inService);
}
else
{
Log.i("Alarm Receiver", "Else loop");
Toast.makeText(context, "Else loop", Toast.LENGTH_SHORT).show();
}
}
Main Acitvity
public class AlaramScheduleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void btnStartSchedule(View v) {
try {
AlarmManager alarms = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(),
AlaramReceiver.class);
intent.putExtra(AlaramReceiver.ACTION_ALARM,
AlaramReceiver.ACTION_ALARM);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 1000 * 10, pIntent);
toast("Started...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void btnCancelSchedules(View v) {
Intent intent = new Intent(getApplicationContext(),
AlaramReceiver.class);
intent.putExtra(AlaramReceiver.ACTION_ALARM,
AlaramReceiver.ACTION_ALARM);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, 1234567,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
alarms.cancel(pIntent);
toast("Canceled...");
}
public void toast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
.show();
}
Android Manifest
INTERNET Permisson is acquired
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TaskService" >
</service>
<receiver
android:name="AlaramReceiver"
android:process=":remote" >
</receiver>
Your problem is in Toast message shown from IntentService.
Fix is simple: create Handler in onCreate of your service and post Runnable to show toast from it.
public class TaskService extends IntentService {
...
private Handler mHandler;
protected void onCreate() {
mHandler = new Handler();
}
...
public boolean uploadRecording(... {
...
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Upload Success", Toast.LENGTH_SHORT).show();
}
});
...
}
}
Internally toast uses Handler to communicate with INotificationManager. Once toast created it create instance of Handler, which uses looper from the thread it is created. In your case it is HandlerThread of IntentService. It is interrupted once service finished all work. That is why it is dead.