I am trying to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices. I added the permissions to the AndroidManifest.xml. And everything seems to be ok. However when I debug the app on the device(Samsung Galaxy tab 3 Lite) I get NullPointerException and the application crashes. Do you have an idea what might cause the problem? Please find below my code and the exception stack trace.
package dyankov.mylibraryrecommender.MainActivities.GUI;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import dyankov.mylibraryrecommender.R;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AroundMeActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button turnOn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
turnOn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
And here is my Logcat file:
Caused by: java.lang.NullPointerException
at dyankov.mylibraryrecommender.MainActivities.GUI.AroundMeActivity.onCreate(AroundMeActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
The code on line 60 is:
turnOn.setOnClickListener(new OnClickListener() { ... }
put turnOn = (Button)findViewById(R.id.turnOn) and all your Button object initialization before turnOn.setEnabled(false);
You try to use button before you set value for it.
Try this code:
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
turnOn.setOnClickListener(new OnClickListener() {
Related
i have problem with this code everything works but when i press scan button nothing happens why is that, i'm sure this code is right i follow Bluetooth Android Developer tutorial, Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled. What am I missing?
package com.example.bluetoothmaccounter;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
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.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonON , buttonOFF, scanBt;
ListView deviceList;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
int requestCodeForEnable = 1;
Intent btEnablingIntent;
Vibrator vibrator;
MediaPlayer mediaPlayer;
TextView textView2 ;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOFF = findViewById(R.id.bt_off);
buttonON = findViewById(R.id.bt_on);
scanBt = findViewById(R.id.bt_scan);
deviceList = findViewById(R.id.device_list);
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
textView2 = findViewById(R.id.textView2);
// /////////////////// Enable bluetooth ///////////////////////
buttonON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "this device not support bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (!bluetoothAdapter.isEnabled()) {
startActivityForResult(btEnablingIntent, requestCodeForEnable);
}
}
}
});
// /////////////////// disable bluetooth ///////////////////////
buttonOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "bluetooth disable", Toast.LENGTH_SHORT).show();
}
}
});
// /////////////////// start scan ///////////////////////
scanBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayList.clear();
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), " bluetooth not Enabled", Toast.LENGTH_SHORT).show();
} else {
bluetoothAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "discover started", Toast.LENGTH_SHORT).show();
}
}
});
try {
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
textView2.setText("befoore receiver");
registerReceiver(receiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
deviceList.setAdapter(arrayAdapter);
} catch (Exception e) {
textView2.setText("exeption" + e.getMessage());
}
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
textView2.setText("on receive 1");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
textView2.setText("found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayList.add(device.getName() + device.getAddress());
String size = "size is " + arrayList.size();
textView2.setText(size);
arrayAdapter.notifyDataSetChanged();
if (arrayList.size() >= 1) {
Toast.makeText(getApplicationContext(), "There are :" + arrayList.size() + "person here ", Toast.LENGTH_LONG).show();
vibrator.vibrate(3 * 1000);
mediaPlayer.start();
}
//
}
}
};
#Override
protected void onDestroy () {
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
textView2.setText("destrrooooooy");
unregisterReceiver(receiver);
}
}
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
You need to add these two permissions in AndroidManifest.xml
I have removed AdMob from my source code of Android Studio, but still, it's showing an empty space at the bottom in the app.
It's always occupying an empty space at the bottom. I do not know how to make that bottom space disappear completely and show a normal preview of the app without ads.
How can I do this?
Here is the code.
Mainactivity.java
package com.dshgh.webview;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.dshgh.webview.Fragments.WebViewFragment;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
boolean doubleBackToExitPressedOnce = false;
private FirebaseAnalytics mFirebaseAnalytics;
RelativeLayout rel_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
rel_layout = (RelativeLayout)findViewById(R.id.rel_layout);
// Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
WebViewFragment webViewFragment = new WebViewFragment();
bundle.putString("url", Config.homeUrl);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
try {
Intent intent = getIntent();
String message = intent.getStringExtra("message");
String url = intent.getStringExtra("url");
Log.d("notification Data", message + url);
if (url.length() > 0) {
bundle.putString("url", url);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
}
}
catch (Exception e) {
Log.d("error notification data", e.toString());
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
displayFirebaseRegId();
}
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = pref.getString("regId", null);
Log.e("FCM", "Firebase reg id: " + regId);
if (!TextUtils.isEmpty(regId)) {
//txtRegId.setText("Firebase Reg Id: " + regId);
}
else
Log.d("Firebase", "Firebase Reg Id is not received yet!");
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
if(((WebViewFragment) fragment).onBackPressed()) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show();
Snackbar snackbar = Snackbar
.make(rel_layout, "Press back once more to exit", Snackbar.LENGTH_LONG);
snackbar.setActionTextColor(Color.RED);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.DKGRAY);
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
}
public void loadFragment(Fragment fragment, Boolean bool) {
loadFragment(fragment, bool, null);
}
public void loadFragment(Fragment fragment, Boolean bool, String TAG) {
showAds();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if(TAG == null) {
transaction.replace(R.id.frameLayout, fragment);
}else {
transaction.replace(R.id.frameLayout, fragment, TAG);
}
if (bool)
transaction.addToBackStack(null);
transaction.commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
((WebViewFragment)fragment).onActivityResult(requestCode, resultCode, intent);
}
super.onActivityResult(requestCode, resultCode, intent);
}
public void hideAds() {
}
public void showAds() {
}
}
I think you forgot to remove <com.google.android.gms.ads.AdView......./> from your XML page.
Please remove it.
Alright so currently my app turns on bluetooth on my device and then lists all paired devices in a List View. I am trying to make it so when the item in the list view is clicked it will connect to the device (primarily for bluetooth speakers). Below i have listed my main java file with all the code that runs my app. If anyone could get me going in the right direction id appreciate it. Also this is my first project working with bluetooth.
package com.applie.itchaboynathan.appv2;
import android.support.v7.app.AppCompatActivity;
import java.io.IOException;
import java.net.Socket;
import java.util.UUID;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.view.MenuItem;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.widget.SeekBar;
import android.widget.TextView;
import android.content.Intent;
import android.widget.ListView;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static SeekBar seek_bar;
private static TextView text_view;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
Handler handler = new Handler();
ListView lv;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
volumeBar();
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.deviceList);
iv = (ImageView)findViewById(R.id.imgConnection);
//define menu button
ImageButton menubutton = (ImageButton)findViewById(R.id.ibtnMenu);
//enables the button to show a menu
menubutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
final PopupMenu popupMenu = new PopupMenu(getApplicationContext(),v);
popupMenu.inflate(R.menu.main_menu);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()) {
case R.id.connect:
//code for connect item
//Delay so the list creates
handler.postDelayed(new Runnable() {
#Override
public void run(){
list();
visible();
iv.setImageResource(R.mipmap.ic_checked);
}
}, 4200);
turnOn();
return true;
case R.id.disconnect:
//code for music item
turnOff();
iv.setImageResource(R.mipmap.ic_disconnected);
listClear();
return true;
case R.id.music:
//code for music item
return true;
case R.id.play:
//code for play item
return true;
case R.id.pause:
//code for pause item
return true;
}
return false;
}
});
}
});//end of button
}
//bluettoth enabler
public void turnOn(){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
//bluetooth disable
public void turnOff(){
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
public void visible(){
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void listClear(){
lv.setAdapter(null);
}
public void list(){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
//volume bar code
public void volumeBar(){
seek_bar = (SeekBar)findViewById(R.id.seekBar);
text_view =(TextView)findViewById(R.id.txtVolumeLvl);
text_view.setText("Volume : " + seek_bar.getProgress() + " % ");
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Volume : " + progress + " % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Volume : " + progress_value + " % ");
}
}
);
}
//end volume bar
}
Try this:
ArrayList list = new ArrayList();
public void list(){
pairedDevices = BA.getBondedDevices();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener () {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selected = list.get(position);
for (Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext(); ) {
BluetoothDevice bt = it.next();
if (bt.getName().equals(selected){
//connect to device
}
}
});
}
You have use BluetoothSocketfor connecting bluetooth.
use the below code to connect.
private BluetoothAdapter mBluetoothAdarpter;
private BluetoothSocket mBtSocket;
private BluetoothDevice mBTDevice;
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
..
..
private boolean connectToDevice(String iAdress) {
try {
if(mBluetoothAdarpter == null) mBluetoothAdarpter = BluetoothAdapter.getDefaultAdapter();
mBTDevice = mBluetoothAdarpter.getRemoteDevice(iAdress);
mBtSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
mBtSocket.connect();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I am writing one app to display user's current address based on latitude and longitude but i am getting one error in this code on line Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show(); It's saying makeText in the type toast is not applicable for arguments. I am unbable to resolve this error.
Any help??
I am trying to display user address in a TextView, but i am not sure whether i am doing good or some runtime error may occur in future.
Here is my Main activity java code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemSelectedListener, ConnectionCallbacks, OnConnectionFailedListener{
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final String DIALOG_ERROR = "dialog_error";
private static final String STATE_RESOLVING_ERROR = "resolving_error";
GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
private boolean mResolvingError=false;
private AddressResultReceiver mResultReceiver;
// Request code to use when launching the resolution activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.shop_category);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.shop_category, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView mytext = (TextView) view;
Toast.makeText(this,"You selected "+mytext.getText(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
startService(intent);
}
#Override
public void onConnected(Bundle arg0) {
boolean mAddressRequested=false;
// TODO Auto-generated method stub
TextView myLatitude = (TextView)findViewById(R.id.lat_value);
TextView myLongitude = (TextView)findViewById(R.id.lang_value);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
myLatitude.setText(String.valueOf(mLastLocation.getLatitude()));
myLongitude.setText(String.valueOf(mLastLocation.getLongitude()));
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
else{
mAddressRequested=true;
if (mAddressRequested) {
startIntentService();
}
}
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (mResolvingError) {
Toast.makeText(this, "Resolving errors", Toast.LENGTH_SHORT).show();
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((MainActivity) getActivity()).onDialogDismissed();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Display the address string
// or an error message sent from the intent service.
String mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
// Show a toast message if an address was found.
if (resultCode == Constants.SUCCESS_RESULT) {
TextView myaddress=(TextView) findViewById(R.id.myaddress);
myaddress.setText(mAddressOutput);
}
else{
Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show();
}
}
}
}
Thank you in advance.
Replace this with MainActivity.this as the first parameter to your makeText() call. this is an instance of your AddressResultReceiver inner class. It is not your activity, and makeText() needs a Context, like an Activity.
Use getApplicationContext() instead of this. Use:
Toast.makeText(getApplicationContext(), "message", Toast.LENGTH_SHORT).show();
this refers to AddressResultReceiver which is not subclass of Context.
Toast.makeText() needs Context.
Here is my problem/question, probably a nooby one....
I have an activity where the app checks if the bluetooth is switched on, if not it displays a pop-up window with a button to activate it.
when activated there is a button which will search for bluetooth devices.
now my question is how can i pair to the selected device which will be protected with an password, if it is already paired just connect to it (witouth entering the password again)
after connecting to the device it should go to the next page.
Here is my Code
package com.example.silcamanager96x32;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
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.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.Toast;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
public class Bluetooth_check extends Activity {
//global variables
private final static int REQUEST_ENABLE_BT = 1;
private ArrayAdapter<String> btArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_check);
btn_go();
btn_scan();
}
//tijdelijke button volgende pagina
public void btn_go(){
Button btn_go=(Button)findViewById(R.id.Button01);
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
Bluetooth_check.this,
home.class);
startActivity(i);
}
});
}
//button scannen naar bluetooth apparaten en in ene lijst plaatsen
public void btn_scan(){
final Button scanb = (Button)findViewById(R.id.button);
final ListView Deviceslist = (ListView)findViewById(R.id.listView1);
btArrayAdapter = new ArrayAdapter<String>(Bluetooth_check.this, android.R.layout.simple_list_item_1);
Deviceslist.setAdapter(btArrayAdapter);
//vraagt of app bluetooth mag inschakelen
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(Bluetooth_check.this, "Your device doesnot support Bluetooth", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//onclick scan button
scanb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
Toast.makeText(Bluetooth_check.this, "Scanning Devices", Toast.LENGTH_LONG).show();
}
});
Deviceslist.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// onclick item gevonden apparaten
AlertDialog.Builder adb = new AlertDialog.Builder(
Bluetooth_check.this);
adb.setTitle("ListView OnClick");
adb.setMessage("Selected Item is = "
+ Deviceslist.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
registerReceiver(FoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(FoundReceiver);
}
private final BroadcastReceiver FoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}};
}
try this link here is whole code ...Android + Pair devices via bluetooth programmatically and add permission to manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />