Android Studio App crashes after adding code for Bluetooth Connection - java

Im currently working at an app for controlling an arduino via bluetooth. I added some Activitys for menus and so on. Yesterday I added a new Activity for connecting my device to the bluetooth module.
Is it even possible to connect to the device in one activity and actually controlling (sending letters) it in another Activity?
With that said the app crashes every time I try to open the activity with the bluetooth code in it. Every other Activity works without any problem.
I hope somebody can help.
Here is my Code:
MainActivity.java (the activity which will control the module):
package com.car.bluetooth.bluetoothcar;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//MENÜPUNKTE
if (id == R.id.action_settings) {
Intent settingsintent = new Intent(MainActivity.this,
settingsactivity.class);
startActivity(settingsintent);
return false;
}
if (id == R.id.action_connect) {
Intent connectintent = new Intent(MainActivity.this,
connectactivity.class);
startActivity(connectintent);
return false;
}
return super.onOptionsItemSelected(item);
}
//SeekBars
private SeekBar seekBarGas;
private TextView textViewGas;
private SeekBar seekBarSteering;
private TextView textViewSteering;
private CheckBox backwards_checkBox;
boolean rückwärts_var = false;
boolean safeMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
seekBarGas = (SeekBar) findViewById(R.id.seekBarGas);
textViewGas = (TextView) findViewById(R.id.textViewGas);
seekBarGas.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textViewGas.setText(progress + " / " + seekBarGas.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekBarGas.setProgress(0);
}
});
seekBarSteering = (SeekBar) findViewById(R.id.seekBarSteering);
textViewSteering = (TextView) findViewById(R.id.textViewSteering);
seekBarSteering.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textViewSteering.setText(progress + " / " + seekBarSteering.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekBarSteering.setProgress(3);
}
});
//GET DATA Settings
Intent safeMode_Intent = getIntent();
safeMode = safeMode_Intent.getBooleanExtra("safeMode", false);
//Rückwärts
CheckBox backwards_checkBox=(CheckBox)findViewById(R.id.backwards_checkBox);
backwards_checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (((CheckBox)v).isChecked()) {
Toast.makeText(getApplicationContext(), "Rückwärts", Toast.LENGTH_SHORT).show();
rückwärts_var = true;
if (safeMode == true) {
seekBarGas.setMax(2);
}
}
else{
Toast.makeText(getApplicationContext(), "Vorwärts", Toast.LENGTH_SHORT).show();
rückwärts_var = false;
if (safeMode == true){
seekBarGas.setMax(5);
}
}
}
});
//Bluetooth
if (btAdapter == null){
Toast.makeText(getApplicationContext(), "Bluetooth wird auf diesem Gerät nicht unterstützt", Toast.LENGTH_LONG).show();
}
}
}
BT_Classic.java (the activity which connects to the module) :
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
ListView list;
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
list = (ListView) findViewById(R.id.list) ;
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
list.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.car.bluetooth.bluetoothcar">
<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="Bluetooth Car"
android:screenOrientation="landscape"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".connectactivity"
android:label="Connect"
android:screenOrientation="landscape" />
<activity
android:name=".settingsactivity"
android:label="Settings"
android:screenOrientation="landscape" />
<activity
android:name=".BT_LE"
android:label="Connect Bluetooth Low Energy"
android:screenOrientation="landscape"/>
<activity
android:name=".BT_Classic"
android:label="Connect Bluetooth Classic"
android:screenOrientation="landscape"
></activity>
</application>
build.gradle (Module:app) :
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.car.bluetooth.bluetoothcar"
minSdkVersion '16'
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha05'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha05'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
implementation 'com.google.android.material:material:1.0.0-beta01'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
Crashlog:
2018-09-12 17:25:36.957 10178-10178/com.car.bluetooth.bluetoothcar
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.car.bluetooth.bluetoothcar, PID: 10178
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.car.bluetooth.bluetoothcar/com.car.bluetooth.bluetoothcar.BT_Classic}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.car.bluetooth.bluetoothcar.BT_Classic.onCreate(BT_Classic.java:78)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6592) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 

btonButton and btoffButton are not initialized and equals null.
You should initialize them with findViewById() like you do with pairedButton
btonButton = (Button) findViewById(R.id.put_here_btn_on_id);
btoffButton = (Button) findViewById(R.id.put_here_btn_off_id);

btonButton and btoffButton have not been initialised yet and then you are calling setonClickListener this causes NPE
Inside onCreate initialise like this:
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);

Related

Why do I get ClassCastException when I extend a class?

I'm developing an app which can read data from a Bluetooth RFID Reader, but everytime i start the BluetoothActivity (it's a tabbed activity), it always shows a ClassCastException, below is my code..
BluetoothActivity class:
package com.siscaproject.sisca.Activity;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.siscaproject.sisca.Fragment.RegisterFragment;
import com.siscaproject.sisca.Fragment.SearchFragment;
import com.siscaproject.sisca.R;
import com.siscaproject.sisca.Utilities.FamsModel;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BluetoothActivity extends TSLBluetoothDeviceActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
#BindView(R.id.viewpager_bluetooth) ViewPager mViewPager;
#BindView(R.id.toolbar_bluetooth) Toolbar mToolbar;
#BindView(R.id.tab_bluetooth) TabLayout mTabLayout;
private FamsModel mModel;
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
}
private void setupViewPager(ViewPager viewPager){
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RegisterFragment(), "REGISTER");
adapter.addFragment(new SearchFragment(), "SEARCH");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_item_reconnect_reader) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bluetooth, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
private ArrayList<String> fragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title ){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
TSLBluetoothDeviceActivity class:
package com.siscaproject.sisca.Utilities;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.siscaproject.sisca.BuildConfig;
import com.uk.tsl.rfid.DeviceListActivity;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import java.util.Timer;
import java.util.TimerTask;
public class TSLBluetoothDeviceActivity extends AppCompatActivity {
// Debugging
private static final String TAG = "TSLBTDeviceActivity";
private static final boolean D = BuildConfig.DEBUG;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mDevice = null;
protected AsciiCommander getCommander() {
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Create the AsciiCommander to talk to the reader (if it doesn't already exist)
if (getCommander() == null) {
try {
TSLBluetoothDeviceApplication app = (TSLBluetoothDeviceApplication) getApplication();
AsciiCommander commander = new AsciiCommander(getApplicationContext());
app.setCommander(commander);
} catch (Exception e) {
fatalError("Unable to create AsciiCommander!");
}
}
}
// Terminate the app with the given message
private void fatalError(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
finish();
}
}, 1800);
}
protected void bluetoothNotAvailableError(String message) {
fatalError(message);
}
#Override
public void onStart() {
super.onStart();
// If no other attempt to connect is ongoing try to connect to last used reader
// Note: When returning from the Device List activity
if (mBluetoothAdapter.isEnabled()) {
if (mDevice == null) {
// Attempt to reconnect to the last reader used
Toast.makeText(this, "Reconnecting to last used reader...", Toast.LENGTH_SHORT).show();
getCommander().connect(null);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onStop() {
super.onStop();
getCommander().disconnect();
mDevice = null;
}
protected void connectToDevice(Intent deviceData, boolean secure) {
Toast.makeText(this.getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
// Get the device MAC address
String address = deviceData.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
mDevice = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
if (mDevice != null) {
getCommander().connect(mDevice);
} else {
if (D) Log.e(TAG, "Unable to obtain BluetoothDevice!");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "selectDevice() onActivityResult: " + resultCode + " for request: " + requestCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode != Activity.RESULT_OK) {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
bluetoothNotAvailableError("Bluetooth was not enabled\nApplication Quitting...");
}
}
}
public void selectDevice() {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
}
public void disconnectDevice() {
mDevice = null;
getCommander().disconnect();
}
public void reconnectDevice() {
getCommander().connect(null);
}
}
The error log:
11-21 14:47:54.836 18956-18956/com.siscaproject.sisca E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siscaproject.sisca, PID: 18956
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.siscaproject.sisca/com.siscaproject.sisca.Activity.BluetoothActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at com.siscaproject.sisca.Activity.BluetoothActivity.getCommander(BluetoothActivity.java:51)
at com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity.onCreate(TSLBluetoothDeviceActivity.java:45)
at com.siscaproject.sisca.Activity.BluetoothActivity.onCreate(BluetoothActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5411)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) 
at android.app.ActivityThread.access$800(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:149) 
at android.app.ActivityThread.main(ActivityThread.java:5257) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
at dalvik.system.NativeStart.main(Native Method) 
I've followed this code from an app that works fine, but when I implemented it in my project it always shows this error, I'm not sure what I'm doing wrong.
---EDIT---
TSLBluetoothDeviceApplication class:
package com.siscaproject.sisca.Utilities;
import android.app.Application;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
public class TSLBluetoothDeviceApplication extends Application {
private static AsciiCommander commander = null;
/// Returns the current AsciiCommander
public AsciiCommander getCommander() {
return commander;
}
/// Sets the current AsciiCommander
public void setCommander(AsciiCommander _commander) {
commander = _commander;
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.siscaproject.sisca">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".Activity.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.BluetoothTestActivity"
android:theme="#style/StandardTheme" />
<activity
android:name=".Activity.HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/AppTheme" />
<meta-data
android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="barcode" />
<activity android:name=".Activity.QRActivity" />
<activity
android:name=".Activity.BluetoothActivity"
android:label="#string/title_activity_bluetooth"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
getApplication() inside an activity returns an object of type Application. In your case you are trying to cast this object into TSLBluetoothDeviceApplication which, as defined by you, is an Activity type class.
As I see, you are trying to call getCommander() which is defined already in your TSL activity class. I assume you want getCommander() method from another class.. Make sure which one is.
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
This method is already inside TSLBluetoothDeviceApplication class.. I don't know what are you trying to achieve by trying to call same method which is already in your current class.
EDIT:
After the edited post, we noticed that the class was properly implemented, just forgot to add
android:name="com.path.to.ApplicationClass" into the Manifestfile under <application/> tag.
I will let the above answer also, because it may help others
Happy coding <3
It's clear that your application class is not used. You need to add it to your xml Application tag like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication"
android:theme="#style/AppTheme"
tools:replace="android:icon">
and the only change is adding android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication" to the Application tag as your customized class.

Auto Launch on Eddystone-UID within 1 meter

I want to auto-launch my activity when a beacon comes within 1 meter. This question has been posed before, but I am unable to get mine to work using/modifying his code.
Just like that post, I followed the same steps with the android beacon library through the altbeacon github but still have been unsuccessful.
I also have "compile 'org.altbeacon:android-beacon-library:2.7+'" in build.gradle file.
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.communionchapelefca.ccsatx" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET"/>
<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.RECEIVE_BOOT_COMPLETED"/>
"android.hardware.bluetooth_le" android:required="false"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="org.communionchapelefca.ccsatx.SplashScreen" android:label="#string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="org.communionchapelefca.ccsatx.MainActivity" android:label="#string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="org.communionchapelefca.ccsatx.MAINACTIVITY"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import org.altbeacon.beacon.startup.RegionBootstrap;
import java.util.Collection;
public class MainActivity extends Activity implements BootstrapNotifier, RangeNotifier {
public static final String TAG = "MainActivityCCSATX";
private WebView mWebView;
ProgressBar progressBar;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://communionchapelefca.org/edy-home");
mWebView.setWebViewClient(new HelloWebViewClient());
// begin code for bluetooth permission for android 6
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check

if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access to find Communion Chapel beacons");
builder.setMessage("Please grant location access so this app can detect Communion Chapel beacons.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
mAllBeaconsRegion = new Region("all beacons", null, null, null);
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBackgroundPowerSaver = new BackgroundPowerSaver(this);
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
//
Log.d(TAG, " region. starting ranging");
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
mBeaconManager.setBackgroundScanPeriod(11000l);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
// end code for bluetooth permission for android 6
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{ //if back key is pressed
if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private RegionBootstrap regionBootstrap;
private BeaconManager mBeaconManager;
private Region region;
private Region mAllBeaconsRegion;
private BackgroundPowerSaver mBackgroundPowerSaver;
private RegionBootstrap mRegionBootstrap;
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
mRegionBootstrap.disable();
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
try {
mBeaconManager.startRangingBeaconsInRegion(new Region("all beacons", null, null, null));
mBeaconManager.setRangeNotifier(this);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "Got a didEnterRegion call");
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
// TODO Auto-generated method stub
if (beacons.size() > 0) {
for (Beacon beacon: beacons) {
Log.d(TAG, "Found a beacon, getting distance");
if(beacon.getDistance()<1)
{
Log.d(TAG, "within 1 minute call");
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
}
}
}
}
LogCat from fatal error:
01-28 17:23:38.819 6549 6724 D MainActivityCCSATX: Got a didEnterRegion call
01-28 17:23:38.824 6549 6549 D BluetoothAdapter: STATE_ON
01-28 17:23:38.824 6549 6549 D BluetoothLeScanner: could not find callback wrapper
01-28 17:23:38.824 6549 6549 D BluetoothAdapter: STATE_ON
01-28 17:23:38.824 6549 6549 D BluetoothLeScanner: could not find callback wrapper
01-28 17:23:39.444 6549 6549 W cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 6549
01-28 17:23:40.023 6549 6549 W cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 6549
A few tips:
Try adding a debug line Log.d("Distance:"+beacon.get Distance()); before you check for Distance < 1. Then run the app while watching LogCat output looking for that log line.
Understand that if you have Android 4.x, it may take up to five minutes to detect in the background.
It is always easier to get apps working in the foreground first, and then add background capability. Make sure you can write code to detect your beacon in the foreground.
With help from davidgyoung's code posted on github, I was able to solve the problem.

Recording app for Android

Basically, I am trying to make an app able to record something using the mic and save what was recorded in a file. I have followed a tutorial I found and so far, I have this code:
package com.nicu.bogdan.vrec;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static MediaRecorder mediaRecorder;
private static MediaPlayer mediaPlayer;
Button record;
Button stop;
Button play;
static String audioFilePath;
boolean isRecording;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
record = (Button) findViewById(R.id.record);
stop = (Button) findViewById(R.id.stop);
play = (Button) findViewById(R.id.play);
if (!hasMicrophone())
{
stop.setEnabled(false);
play.setEnabled(false);
record.setEnabled(false);
} else {
play.setEnabled(false);
stop.setEnabled(false);
}
}
public boolean hasMicrophone() {
PackageManager pmanager = this.getPackageManager();
return pmanager.hasSystemFeature(
PackageManager.FEATURE_MICROPHONE);
}
public void record (View view) throws IOException
{
audioFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ DateFormat.getDateTimeInstance().format(new Date()) + ".3gp";
isRecording = true;
stop.setEnabled(true);
play.setEnabled(false);
record.setEnabled(false);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //the error comes from this line
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(audioFilePath);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
mediaRecorder.start();
}
public void stop (View view)
{
stop.setEnabled(false);
play.setEnabled(true);
if (isRecording)
{
record.setEnabled(false);
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
isRecording = false;
} else {
mediaPlayer.release();
mediaPlayer = null;
record.setEnabled(true);
}
}
public void play (View view) throws IOException
{
play.setEnabled(false);
record.setEnabled(false);
stop.setEnabled(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioFilePath);
mediaPlayer.prepare();
mediaPlayer.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nicu.bogdan.vrec" >
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The layout is pretty simple, 3 buttons: record, stop and play. I'm not going to post that code since it's not important.
After I click the "record" button, I get this error: Caused by: java.lang.RuntimeException: setAudioSource failed. from the line I have commented above. Now the thing is that I get this only when I run the app from my Nexus 5, when I run the app from Genymotion emulator, I don't get this error.
You need to add
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
to your manifest because accessing the audio source is modifying the audio settings.

Switch activities in Android Activities

Whenever I try to click on a button and switch activities, it always gives me the error and stays on the same activity without doing anything:
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6d42940, error=EGL_SUCCESS
I thought that it was something in my manifest file, but I can't find anything. I've tried changing many things around and inserting different filters and such and nothing solves this problem.
My code is:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.robertmonks.mytestapp" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name="Main_Activity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="Login_Activity"
android:label="#string/title_activity_login_"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name="Register_Activity"
android:label="#string/title_activity_register_"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
</application>
</manifest>
Main_Activity
package com.example.robertmonks.mytestapp;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.app.AlertDialog;
public class Main_Activity extends AppCompatActivity {
android.widget.Button logoutButton;
android.widget.EditText password;
android.widget.EditText username;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password = (android.widget.EditText) findViewById( R.id.etPassword );
username = (android.widget.EditText) findViewById( R.id.etEmailAddress );
logoutButton = (android.widget.Button) findViewById( R.id.blogin);
logoutButton.setOnClickListener(new android.widget.Button.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.blogin) {
logoutButtonClicked();//move action to new method to keep code clean
}
}
});
}
private void logoutButtonClicked()
{
android.content.Intent loginintent = new android.content.Intent(Main_Activity.this, Login_Activity.class);
Main_Activity.this.startActivity(loginintent);
android.util.Log.d("Logout", "Attempted");
}
}
Login_Activity
package com.example.robertmonks.mytestapp;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.app.AlertDialog;
public class Login_Activity extends AppCompatActivity {
android.widget.Button loginButton;
android.widget.Button registerButton;
android.widget.EditText password;
android.widget.EditText username;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password = (android.widget.EditText) findViewById( R.id.etPassword );
username = (android.widget.EditText) findViewById( R.id.etEmailAddress );
loginButton = (android.widget.Button) findViewById( R.id.blogin);
registerButton = (android.widget.Button) findViewById( R.id.bregister);
loginButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.blogin) {
loginButtonClicked();//move action to new method to keep code clean
}
if(v.getId() == R.id.bregister) {
registerButtonClicked();
}
}
});
registerButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.bregister) {
registerButtonClicked();
}
}
});
}
private void loginButtonClicked()
{
//startActivity(Main_Activity.class);
android.util.Log.d("Login", "Attempted");
}
private void registerButtonClicked()
{
android.content.Intent registerintent = new android.content.Intent(Login_Activity.this, Register_Activity.class);
Login_Activity.this.startActivity(registerintent);
android.util.Log.d("New User", "Attempted");
}
}
Registration_Activity
package com.example.robertmonks.mytestapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Register_Activity extends AppCompatActivity {
android.widget.Button createAccountButton;
android.widget.Button LoginPageButton;
android.widget.EditText password1;
android.widget.EditText password2;
android.widget.EditText FirstName;
android.widget.EditText LastName;
android.widget.EditText EmailAddress;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password1 = (android.widget.EditText) findViewById( R.id.etFirstPassword );
password2 = (android.widget.EditText) findViewById( R.id.etSecondPassword );
FirstName = (android.widget.EditText) findViewById( R.id.etFirstName );
LastName = (android.widget.EditText) findViewById( R.id.etLastName );
createAccountButton = (android.widget.Button) findViewById( R.id.blogin);
LoginPageButton = (android.widget.Button) findViewById( R.id.bregister);
EmailAddress = (android.widget.EditText) findViewById( R.id.etEmailAddress);
createAccountButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.blogin) {
createAccountButtonClicked();//move action to new method to keep code clean
}
}
});
LoginPageButton.setOnClickListener(new android.widget.Button.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.bregister) {
LoginPageButtonClicked();
}
}
});
}
private void createAccountButtonClicked()
{
android.util.Log.d("Create Account", "Attempted");
}
private void LoginPageButtonClicked()
{
android.util.Log.d("Login Page", "Attempted");
android.content.Intent loginintent = new android.content.Intent(this, Login_Activity.class);
startActivity(loginintent);
}
}
For all the buttons, try changing the onclicklistener.
e.g. For the register button,
registerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I hope this helps. Cheers :)
Your code looks ok... i think problem is your emulator configuration.
only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
Tools > Android > AVD Manager > Edit the virtual device and the Use Host GPU setting is found there.
for more detail.. click

Android Could execute method of the activity

I'm building a simple paint app and encountering this error given by the logcat:
I'm using the following code:
This SaveDrawing.java serves as the main activity
package com.example.SaveDrawing;
import com.example.SaveDrawing.drawings.DrawingActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SaveDrawing extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view){
switch (view.getId()){
case R.id.drawBtn:
//Intent drawIntent = new Intent(this, DrawingActivity.class);
//startActivity( drawIntent);
//Toast.makeText(getBaseContext(), "This is the Toast message", Toast.LENGTH_SHORT).show();
Intent nextActivity = new Intent(SaveDrawing.this, DrawingActivity.class);
startActivity(nextActivity);
break;
}
}
}
Then the next activity after clicking the button is DrawingActivity.java
package com.example.SaveDrawing.drawings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import com.example.SaveDrawing.R;
import com.example.SaveDrawing.R.id;
import com.example.SaveDrawing.R.layout;
public class DrawingActivity extends Activity implements View.OnTouchListener{
private DrawingSurface drawingSurface;
private DrawingPath currentDrawingPath;
private Paint currentPaint;
private Button redoBtn;
private Button undoBtn;
private static File APP_FILE_PATH = new File("/sdcard/TutorialForAndroidDrawings");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
setCurrentPaint();
drawingSurface = (DrawingSurface) findViewById(R.id.drawingSurface);
drawingSurface.setOnTouchListener(this);
redoBtn = (Button) findViewById(R.id.redoBtn);
undoBtn = (Button) findViewById(R.id.undoBtn);
redoBtn.setEnabled(false);
undoBtn.setEnabled(false);
}
private void setCurrentPaint(){
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFFFF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
}
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
currentDrawingPath = new DrawingPath();
currentDrawingPath.paint = currentPaint;
currentDrawingPath.path = new Path();
currentDrawingPath.path.moveTo(motionEvent.getX(), motionEvent.getY());
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
}else if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
}else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
drawingSurface.addDrawingPath(currentDrawingPath);
undoBtn.setEnabled(true);
redoBtn.setEnabled(false);
}
return true;
}
public void onClick(View view){
switch (view.getId()){
case R.id.colorRedBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFF0000);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorBlueBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF00FF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorGreenBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF0000FF);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.undoBtn:
drawingSurface.undo();
if( drawingSurface.hasMoreUndo() == false ){
undoBtn.setEnabled( false );
}
redoBtn.setEnabled( true );
break;
case R.id.redoBtn:
drawingSurface.redo();
if( drawingSurface.hasMoreRedo() == false ){
redoBtn.setEnabled( false );
}
undoBtn.setEnabled( true );
break;
case R.id.saveBtn:
final Activity currentActivity = this;
Handler saveHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
final AlertDialog alertDialog = new AlertDialog.Builder(currentActivity).create();
alertDialog.setTitle("Saved 1");
alertDialog.setMessage("Your drawing had been saved :)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
} ;
new ExportBitmapToFile(this,saveHandler, drawingSurface.getBitmap()).execute();
break;
}
}
private class ExportBitmapToFile extends AsyncTask<Intent,Void,Boolean> {
private Context mContext;
private Handler mHandler;
private Bitmap nBitmap;
public ExportBitmapToFile(Context context,Handler handler,Bitmap bitmap) {
mContext = context;
nBitmap = bitmap;
mHandler = handler;
}
#Override
protected Boolean doInBackground(Intent... arg0) {
try {
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
final FileOutputStream out = new FileOutputStream(new File(APP_FILE_PATH + "/myAwesomeDrawing.png"));
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return true;
}catch (Exception e) {
e.printStackTrace();
}
//mHandler.post(completeRunnable);
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if ( bool ){
mHandler.sendEmptyMessage(1);
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.SaveDrawing"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SaveDrawing"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DrawingActivity" android:screenOrientation="landscape" ></activity>
<activity android:name=".drawings.DrawingActivity"/>
</application>
</manifest>
I have the following in my explorer. I'm not so sure if I got a wrong file structure.
Anyone can help me? I'm kinda new to java and android programming. Many thanks!!! :)
remove <activity android:name=".DrawingActivity" android:screenOrientation="landscape" ></activity> from your manifest as there is no such activity. there is only DrawingActivity in your project structure. Then clean build Run.
Also another possible problem could having an Activity Class name SaveDrawing in the package. You should try to rename the package, update relevant changes to the manifest and try running the app again..
You probably forgot to declare DrawingActivity in your manifest.xml
This is because you attempt to launch com.example.SaveDrawing.drawings/com.example.SaveDrawing.drawings.DrawingActivity,
but actual activity you launch in code is com.example.SaveDrawing/com.example.SaveDrawing.drawings.DrawingActivity
Please change
Intent nextActivity = new Intent(SaveDrawing.this, DrawingActivity.class);
to
Intent nextActivity = new Intent();
nextActivity.setClassName ("com.example.SaveDrawing.drawings", "com.example.SaveDrawing.drawings.DrawingActivity");
It might work.

Categories