Cannot resolve symbol 'file' - java

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.

Related

Call measure how far you dragged in Android

I made an application running in the background, and I want to add a function to measure the slide on the screen. I'll leave you the code for both, and someone can help me. I'm a beginner and I've been looking all over trying to solve this without results.
I know the post is too long, but I did not know how to shorten it so you can understand it.
The code for running the application in the background
App.java
package com.codinginflow.foregroundserviceexample;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager =
getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codinginflow.foregroundserviceexample">
<application
android:name=".App"
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>
<service android:name=".ExampleService" />
</application>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
</manifest>
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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.codinginflow.foregroundserviceexample.MainActivity">
<EditText
android:id="#+id/edit_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startService"
android:text="Start Service" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stopService"
android:text="Stop Service" />
</LinearLayout>
ExampleService.java
package com.codinginflow.foregroundserviceexample;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.codinginflow.foregroundserviceexample.App.CHANNEL_ID;
public class ExampleService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this,
CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.codinginflow.foregroundserviceexample;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editTextInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextInput = findViewById(R.id.edit_text_input);
}
public void startService(View v) {
String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", input);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this, ExampleService.class);
stopService(serviceIntent);
}
}
Code for sliding measurement
Point p1;
Point p2;
View view = new View(this);
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
p1 = new Point((int) event.getX(), (int) event.getY());
else if(event.getAction() == MotionEvent.ACTION_UP)
p2 = new Point((int) event.getX(), (int) event.getY());
return false;
}
});
Can someone call me this code in my app?

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

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.

Turn phoneSpeakers when start a call

I trying to turn on the Speaker after starting a call with a Button. But the Speaker don't get turn on. My Code:
I tried audioManager.setMode(AudioManager.MODE_IN_CALL); but it dont worked.
What I'm doing wrong?
MainActivity.java
package app.fabi.telefon_freisprech;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonCall);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
check();
Intent myIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "+123456789";
myIntent.setData(Uri.parse(phNum));
startActivity( myIntent ) ;
audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true);
}
});
}
void check(){
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CALL_PHONE,
Manifest.permission.CALL_PHONE, Manifest.permission.CALL_PHONE}
, 10);
}
return;
}
}
}
}
activity_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" >
<Button
android:id="#+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Anrufen +123456789" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.fabi.telefon_freisprech">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<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>
I think its not a big thing but i don't get it to work.

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