Camera "Bitmap imageBitmap = (Bitmap) extras.get("data");" gives Nullpointer error - java

I am following the Android developer tutorials on camera here: https://developer.android.com/training/camera/photobasics#java
I however get an error in the method
onActivityResult:,java.lang.NullPointerException: Attempt to invoke
virtual method 'java.lang.Object
android.os.Bundle.get(java.lang.String)' on a null object reference
This line is giving the error:
Bitmap imageBitmap = (Bitmap) extras.get("data");
Somehow when I comment out this line then the app works:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
My entire code is located here:
https://github.com/europa9/EanScannerForAndroid
MainActivity.java
package one.askit.eanscanner;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission
checkPermissionExternalRead();
checkPermissionExternalWrite();
checkPermissionCamera();
// Listeners
listeners();
FrameLayout frameLayoutCameraPreview = findViewById(R.id.frameLayoutCameraPreview);
frameLayoutCameraPreview.setVisibility(View.GONE);
}
/*- Check permission Read ------------------------------------------------------------------- */
// Pops up message to user for reading
private void checkPermissionExternalRead(){
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
/*- Check permission Write ------------------------------------------------------------------ */
// Pops up message to user for writing
private void checkPermissionExternalWrite(){
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionWrite
/*- Check permission Camera ----------------------------------------------------------------- */
public void checkPermissionCamera(){
int MY_PERMISSIONS_REQUEST_CAMERA = 1;
if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.CAMERA)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionInternalRead
public void listeners(){
Button buttonScan = findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonScanClicked();
}
});
}
public void buttonScanClicked(){
// Scan text
TextView TextViewScan = findViewById(R.id.TextViewScan);
TextViewScan.setText("Now scanning");
// Take picture
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
String file_path = Environment.getExternalStorageDirectory().toString() +
"/" + this.getResources().getString(R.string.app_name);
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
// IMAGE_PATH = new File(dir, mContext.getResources().getString(R.string.app_name) + AppConstants.USER_ID + System.currentTimeMillis() + ".png");
File IMAGE_PATH = new File(dir, this.getResources().getString(R.string.app_name) + System.currentTimeMillis() + ".png");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
picIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", IMAGE_PATH));
}
else {
picIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(IMAGE_PATH));
}
startActivityForResult(picIntent, REQUEST_TAKE_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
//Do your logic
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView imageViewScanPreview = findViewById(R.id.imageViewScanPreview);
imageViewScanPreview.setImageBitmap(imageBitmap);
} else {
//Do something else
Toast.makeText(this, "Its null!", Toast.LENGTH_LONG).show();
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frameLayoutCameraPreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<ImageView
android:id="#+id/imageViewScanPreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="?attr/colorAccent" />
<TextView
android:id="#+id/TextViewScan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Doint nothing"></TextView>
<Button
android:id="#+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Scan" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="one.askit.eanscanner">
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_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">
<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}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="images" path="."/>
<external-path name="external_files" path="."/>
</paths>

Change your file provider like below
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
And your file_path.xml be like below
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="images" path="."/>
<external-path name="external_files" path="."/>
</paths>
For image capture use this Intent
Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
String file_path = Environment.getExternalStorageDirectory().toString() +
"/" + mContext.getResources().getString(R.string.app_name);
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
// IMAGE_PATH = new File(dir, mContext.getResources().getString(R.string.app_name) + AppConstants.USER_ID + System.currentTimeMillis() + ".png");
IMAGE_PATH = new File(dir, mContext.getResources().getString(R.string.app_name) + System.currentTimeMillis() + ".png");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
picIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(mContext, mContext.getPackageName()+".fileprovider", IMAGE_PATH));
}
else {
picIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(IMAGE_PATH));
}
((Activity) mContext).startActivityForResult(picIntent, CAMERA_REQUEST);
And inside the onActivityREsult , you need to change the code as follow
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int cropperType = 1;
if (requestCode == REQUEST_IMAGE_CAPTURE) {
switch (resultCode) {
case Activity.RESULT_OK:
String imagePAth= Uri.fromFile(IMAGE_PATH);
GlideApp.with(this).load(imagePAth).diskCacheStrategy(DiskCacheStrategy.ALL).skipMemoryCache(false).
placeholder(R.drawable.default_picture).error(R.drawable.default_picture).dontAnimate().into(YOUR_IMAGEVIEW);
break;
case Activity.RESULT_CANCELED:
break;
}
}
}
And if you want the Bitmap from the onActivityResult than you need to refer this link Click here

There are different ways to receive a bitmap from the camera.
You are trying to get a Bitmap from the extras that is not there. Since you are casting the null to Bitmap the error happens at the moment of accessing the data and not the moment you try to work with the bitmap.
If your are supplying a output URI via takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); most Android phones will store the photo at this URI and you have to access the bitmap through the file that was stored there. If you remove the URI the photo is supplied in the extra in the Intent, that is why the code works if you remove that line.

Related

Can not send image from android studio to pc using java sockets, filePath returns null

I tried the code from Client-Server: File transfer from Android to PC connected via socket and the app crashes when sending the image. The Path for the image once the image is selected is returned null. The app is running on an emulator.
My current code is MainActivity:
package com.example.floweridentifier;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
Button send = (Button) findViewById(R.id.bSend);
final TextView status = (TextView) findViewById(R.id.tvStatus);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Socket sock;
try {
sock = new Socket("My pc's public ip", 800);
System.out.println("Connecting...");
// sendfile
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.floweridentifier">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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/Theme.FlowerIdentifier">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="#string/app_name"
android:theme="#style/Theme.FlowerIdentifier.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvStatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<TextView
android:id="#+id/tvPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/path" />
<Button
android:id="#+id/bBrowse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/browse" />
<Button
android:id="#+id/bSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send" />
<ImageView
android:id="#+id/ivPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/todo">
</ImageView>
</LinearLayout>
strings.xml
strings.xml
<resources>
<string name="app_name">Flower identifier</string>
<string name="action_settings">Settings</string>
<!-- Strings used for fragments for navigation -->
<string name="first_fragment_label">First Fragment</string>
<string name="second_fragment_label">Second Fragment</string>
<string name="next">Next</string>
<string name="previous">Previous</string>
<string name="hello_first_fragment">Hello first fragment</string>
<string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
<string name="hello">Flower identifier</string>
<string name="path">Path</string>
<string name="browse">browse</string>
<string name="send">send</string>
<string name="todo">todo</string>
</resources>
FileInputStream fis = new FileInputStream(myFile);
replace that by:
InputStream is = getContentResolver().openInputStream(data.getData());
And use is instead of fis.
Throw away selectedImagePath.

Cannot resolve symbol 'file'

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.

Can't display list of wifi connected devices in Android

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);
}
}

An android application that chooses photo from gallery and uploads into the firebase batabase

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.

Querying Bluetooth Devices android

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.

Categories