I am new to android and i am stuck. the basic premise for me is, when an app is opened, i need to prompt the user to switch on the bluetooth. and when yes is pressed, i need to begin scanning for nearby devices automatically. one more premise is that i should not use any buttons to start scanning. it should start automatically when the bluetooth is switched on.
The code has no syntax errors. Am i doing something wrong logically?
Because when i run the app, nothing happens. It does prompt to establish bluetooth connection, but after switch on, it should automatically scan and populate the listView in the activity_main file. which is not happening.
the activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shashineha.mybluetoothapp.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/listView_Bluetooth"/>
</RelativeLayout>
the mainActivity.java :
package com.example.bluetooth.bluetoothApp
import android.support.v7.app.AppCompatActivity;
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.shashineha.mybluetoothapp.R;
public class MainActivity extends AppCompatActivity {
ListView listView;
BluetoothAdapter bluetoothAdapter;
ArrayAdapter mArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
}
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.startDiscovery();
}
}
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
listView = (ListView)findViewById(R.id.listView_Bluetooth);
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
listView.setAdapter(mArrayAdapter);
}
}
};
#Override
protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(mReceiver);
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.disable();
}
}
the androidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth.mybluetoothapp">
<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:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
please make sure you have added these permissions in your manifest.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
After this, change the condition little bit this way in your onCreate()
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
} else {
bluetoothAdapter.startDiscovery();
}
if bluetooth is already turned on, it will simple start scanning which is not happening at the moment. Now it should scan. also note the line
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
will create null point exception once some device founds. you can first simply check with log message initially. Bind your adapter as it is null in start. Also make sure that you have some Bluetooth devise which can be scanned.
Related
(DISCLAIMER: SUPER NEW TO ANDROID STUDIO) I'm creating an app to scan for ble devices and display them on the list but it seems like no devices are being discovered and being displayed on the listview. Any help is appreciated. I'm planning to update the Textview with the number of devices that are found. I haven't set up the scanfilters yet since I'm still trying to figure out the UUIDs for the tags that I'm using. I also changed the min sdk to 23 since it was giving me an error while setting the scanmode, callback, and matchmode.
MainActivity.java
package com.example.tygatraxseconddraft;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TWESBTSCANNER";
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
private ListView listView;
private Button scanningBtn;
private BluetoothAdapter bluetoothAdapter;
private final ArrayList<String> mDeviceList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.device_list);
scanningBtn = findViewById(R.id.scanning_btn);
hasPermissions();
checkBluetoothState();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
listView = findViewById(R.id.device_list);
scanningBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
final ScanCallback scanCallback = new ScanCallback() { //studio made it not private
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
// ...do whatever you want with this found device
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
// Ignore for now
}
#Override
public void onScanFailed(int errorCode) {
// Ignore for now
}
};
UUID SERVICE_DATA_UUID = UUID.fromString("00005246-0000-1000-8000-00805f9b34fb");//filter for the Nordic tags
UUID[] serviceUUIDs = new UUID[]{SERVICE_DATA_UUID};
List<ScanFilter> filters = null;
if (serviceUUIDs != null) {
filters = new ArrayList<>();
for (UUID serviceUUID : serviceUUIDs) {
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(serviceUUID))
.build();
filters.add(filter);
}
}
ScanSettings scanSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
.setReportDelay(0L)
.build();
if (scanner != null) {
scanner.startScan(null, scanSettings, scanCallback); // must set scan settings first
Log.d(TAG, "scan started");
} else {
Log.e(TAG, "could not get scanner object");
}
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public final BroadcastReceiver mReceiver = new BroadcastReceiver() { //
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
private boolean hasPermissions() { //checks and asks for location permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_ACCESS_COARSE_LOCATION);
return false;
}
}
return true;
}
//ENABLE WHEN TESTING ON PHONE
private void checkBluetoothState() {
//gets the bluetooth adapter
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter.isEnabled()){
Toast.makeText(this,"Bluetooth is enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please turn on Bluetooth", Toast.LENGTH_SHORT).show();
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}//requests permission if bluetooth is not enabled
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tygatraxseconddraft">
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Needed only if your app looks for Bluetooth devices.
You must add an attribute to this permission, or declare the
ACCESS_FINE_LOCATION permission, depending on the results when you
check location usage in your app. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<!-- Needed only if your app makes the device discoverable to Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION_LOCATION"/>
<!--Makes the app show up for only ble enabled devices-->
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true"/>
<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/Theme.TygaTraxsecondDraft">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".MainActivity">
<TextView
android:id="#+id/number_devices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="#string/number_of_devices"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/scanning_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="50dp"
android:text="#string/button_text"
android:textColor="#212121"
app:backgroundTint="#color/gray"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<ListView
android:id="#+id/device_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
app:layout_constraintBottom_toTopOf="#+id/scanning_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/number_devices" />
</androidx.constraintlayout.widget.ConstraintLayout>
In case this is needed
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="gray">#7393B3</color>
</resources>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tyga Trax (second draft)</string>
<string name="button_text">Scan</string>
<string name="number_of_devices">There are </string>
</resources>
New Answer
I just realised you are simply doing nothing with the found devices right now, your ScanCallback is empty. You should add something like this to see the results:
final ScanCallback scanCallback = new ScanCallback() { //studio made it not private
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
Log.d(TAG, "BLE scan found Device " + device.getName() + " with MAC " + device.getAddress());
// TODO: add device to ListView
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
// Ignore for now
}
#Override
public void onScanFailed(int errorCode) {
// Ignore for now
}
};
You should see the found devices in your log now
Previous Answer
You are requesting the ACCESS_COARSE_LOCATION permission but your target SDK is 31. The guide for Bluetooth permissions states
ACCESS_FINE_LOCATION is necessary because a Bluetooth scan can gather information about the location of the user. This information may come from the user's own devices, as well as Bluetooth beacons in use at locations such as shops and transit facilities.
and also
Note: If your app targets Android 9 (API level 28) or lower, you can declare the ACCESS_COARSE_LOCATION permission instead of the ACCESS_FINE_LOCATION permission.
It even states to use ACCESS_BACKGROUND_LOCATION for devices with Android 10 or above. But there are new permissions for a target SDK of 31 (Android 12) as stated in this document.
<manifest>
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Needed only if your app looks for Bluetooth devices.
You must add an attribute to this permission, or declare the
ACCESS_FINE_LOCATION permission, depending on the results when you
check location usage in your app. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- Needed only if your app makes the device discoverable to Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
...
</manifest>
As you can see the legacy Bluetooth permissions like BLUETOOTH are added as well, but have the option android:maxSdkVersion="30" set to only work up to Android 11.
I am trying access the camera on an android device, so I tried some code from this site
I get this error: image at Imgur when I hover my mouse over 'file'. Take a look at the code below.
MainActivity.Java
package com.example.camera;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED){
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_image"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:onClick="takePicture"
android:text="Take a picture!"/>
</RelativeLayout>
android_manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera">
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Sorry if there are some formatting errors, I am quite new to Stack Overflow. The code is some testing for a future project. If anyone could answer my question on this error, +1 to you. I would really appreciate the help :)
You need to declare file variable globally.
Like:
private Uri file;
In Java
A variable is a container that holds values that are used in a
Java program. To be able to use a variable it needs to be declared.
Declaring variables is normally the first thing that happens in any
program.
I have issue with this code.I am trying to display all devices that are connected on the same WIFI in the list.
I did debugging and it shows that connection with WIFI was made but it does not detect any devices, even though there are some connected devices for sure. I did pinging with both sides with computer and android and connection was made.
If you guys have any ideas where could be a problem, please let me know, cause I am out of ideas.
MANIFEST FILE.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:required="true" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.NFC"
android:required="true" />
<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=".Intro_Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_intro_"
android:theme="#style/FullscreenTheme"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.app.MainActivity">
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onToggleClicked"
android:textOff="Wi-Fi Off"
android:textOn="Wi-Fi On" />
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MainActivity.java
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private WifiManager wifiManager;
private BroadcastReceiver wifiReciever;
private ArrayAdapter adapter;
SupplicantState supState;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WiFiScanReceiver();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
}
public void onToggleClicked(View view) {
adapter.clear();
ToggleButton button = findViewById(R.id.toggleButton);
if (wifiManager == null) {
//device does not support wifi
Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
Toast.LENGTH_SHORT).show();
button.setChecked(false);
} else {
if (button.isChecked()) { // to turn on wifi
if (!wifiManager.isWifiEnabled()) {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
wifiManager.setWifiEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
Toast.LENGTH_SHORT).show();
}
}
}
class WiFiScanReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
for (int i = 0; i < wifiScanResultList.size(); i++) {
ScanResult accessPoint = wifiScanResultList.get(i);
String listItem = accessPoint.SSID + ", " + accessPoint.BSSID;
adapter.add(listItem);
}
}
}
}
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReciever, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReciever);
}
}
Like I said in my title I am trying to learn to use databases in android application. So I thought of creating a sample application that takes photos from gallery and uploads the image into the firebase database. However, my application collapses itself after I select a photo from gallery.
Here is my android manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.trump.demo_cameraapp">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
Here is my layout file, activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width = "match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2">
</ImageView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Photo!"
android:textColor="#color/Blue"
android:id="#+id/chooseButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Upload Photo!"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/uploadButton"/>
</LinearLayout>
I have the following lines of code in MainActivity
package com.example.trump.demo_cameraapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PICK_IMAGE_REQUEST = 1;
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
private ImageView mImageView;
private StorageReference storage;
private ProgressDialog mProgressDialog;
public static final int GALLERY_INTENT = 2;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
mImageView = (ImageView) findViewById(R.id.imageView1);
Button choose = (Button) findViewById(R.id.chooseButton);
choose.setOnClickListener(this);
Button upload = (Button) findViewById(R.id.uploadButton);
upload.setOnClickListener(this);
}
private void showFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select an image"),PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data!=null && data.getData()!=null) {
Log.d("ResultOK", String.valueOf(RESULT_OK));
Log.d("CameraDemo", "Pic saved");
mProgressDialog.setMessage("Uploading...");
mProgressDialog.show();
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
StorageReference filepath = storage.child("images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.chooseButton){
showFileChooser();
}else if(view.getId() == R.id.uploadButton){
}
}
}
I have not yet written codes to upload the image on firebase database. All I am trying to do right now is to display the image I picked from gallery in the imageview of my app. However, like I said before it's not displaying anything right now and as soon as I choose some photo from gallery it collapses. Any help regarding the issue would be very appreciated.
I think there is no issue with your image picker code, what i found a problem is that you are using mProgressDialog without initializing it in the onCreate() method. So what is recommend is that you first initialize mProgressDialog object in your onCreate() method right after you the initialization of mImageView. And i hope that your application will not collapse now.
Hi have created splash screen as a separate project by using this link : http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/ . And it did worked on my emulator . However, when I implemented this in my app. It did not worked . I don' know whats wrong with my code. My main.java, splash screen.java and splash.xml are the following. Please note that I did define my activity in manifest file. Any help will be greatly appreciated...
MainActivity.Java
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button_1).setOnClickListener(this);
findViewById(R.id.button_2).setOnClickListener(this);
findViewById(R.id.button_3).setOnClickListener(this);
}
public void onClick(View v) {
int resId=1;
// Release any resources from previous MediaPlayer
if (mp != null) {
mp.release();
}
switch (v.getId()) {
case R.id.button_1: resId = R.raw.button_1; break;
case R.id.button_2: resId = R.raw.button_2; break;
case R.id.button_3:
startActivity(new Intent(MainActivity.this,SecondActivity.class));
return;
}
// Create a new MediaPlayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
}
SplashScreen.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
activity_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background" >
<ImageView
android:id="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/images235" />
</RelativeLayout>
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Smit.yourbollywoodyourplaylist"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="11" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.androidhive.androidsplashscreentimer.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
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=".SecondActivity"
android:label="#string/app_name"/>
</application>
</manifest>
It's not clear which package your SplashScreen.java lives in, but
android:name="info.androidhive.androidsplashscreentimer.SplashScreen"
might need to be changed to
android:name=".SplashScreen"
You may have just pasted in the manifest definition from the sample project without adjusting the activity name to match your own project.