I have an option for backup the DB of notes. I added the code of backing up the notes in onOptionsItemSelected method in MainActivity and it's works fine. But when I copy the same code to SettingsFragment activity and press that option in my phone, it doesn't work and doesn't show any thing!
Another problem, how I can show a Toast or Snackbar in SettingsFragment activity?!
Hint: This is the first time I work with Settings activities. So, I don't know if the onPreferenceTreeClick method is the correct method to work with some preferences.
SettingsFragment activity:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_layout);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
PreferenceKeys preferenceKeys = new PreferenceKeys(getResources());
if (key.equals(preferenceKeys.night_mode_pref_key)) {
SharedPreferences themePrefs = getActivity().getSharedPreferences(MainActivity.THEME_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor themeEditor = themePrefs.edit();
themeEditor.putBoolean(MainActivity.RECREATE_ACTIVITY, true);
CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference(preferenceKeys.night_mode_pref_key);
if (checkBoxPreference.isChecked()) {
themeEditor.putString(MainActivity.SAVED_THEME, MainActivity.DARKTHEME);
} else {
themeEditor.putString(MainActivity.SAVED_THEME, MainActivity.LIGHTTHEME);
}
themeEditor.apply();
getActivity().recreate();
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
PreferenceKeys preferenceKeys = new PreferenceKeys(getResources());
if(preference.equals(preferenceKeys.backup_db_key))
{
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//com.twitter.i_droidi.mynotesdonation//databases//MyNotes"; // Check...!!!
String backupDBPath = "MyNotes"; // From SD directory.
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getContext(), "Import Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), "Import Failed!", Toast.LENGTH_SHORT)
.show();
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
}
Related
I want to update the bitmap image inside the URL without changing its download URL in the real-time database because at uploading for the first time I have uploaded the image in the storage and stored it URL in the real time database now I want to update that image how should I approach this ??
package com.parth.iitktimes;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.card.MaterialCardView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.Serializable;
import de.hdodenhof.circleimageview.CircleImageView;
public class updataDelete extends AppCompatActivity {
//declaring private variables
private MaterialCardView SelectImage;
private EditText edCreatorName, edCreatorDesignation, edCreatorEmail, edCreatorMobile;
private Button btnUpdateCreator,btnDeleteCreator;
private CircleImageView previewImage;
private Bitmap mbitmap;
private ActivityResultLauncher<String> someActivityResultLauncher;
//download url of the uploaded images
private String downloadUrl = "";
//progressDialog for updates
private ProgressDialog progressDialog;
private Creator obj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updata_delete);
//giving context to the progress dialog
progressDialog = new ProgressDialog(this);
// initialisation
SelectImage = findViewById(R.id.select_image);
edCreatorName = findViewById(R.id.edCreatorName);
edCreatorDesignation = findViewById(R.id.edCreatorDesignation);
edCreatorEmail = findViewById(R.id.edCreatorEmail);
edCreatorMobile = findViewById(R.id.edCreatorMobile);
btnUpdateCreator = findViewById(R.id.updateCreator);
btnDeleteCreator = findViewById(R.id.deleteCreator);
previewImage = findViewById(R.id.preview_image);
progressDialog = new ProgressDialog(this);
//accessing the object from the intent as a serializable extra
obj = (Creator) getIntent().getSerializableExtra("model object");
edCreatorName.setText(obj.getName());
edCreatorDesignation.setText(obj.getDesign());
edCreatorEmail.setText(obj.getEmail());
edCreatorMobile.setText(obj.getPhone());
edCreatorName.requestFocus();
//loading the image from the preview data url to the bitmap variable and preview image
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//initializing the variable and preview image source
mbitmap = bitmap;
previewImage.setImageBitmap(mbitmap);
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
Toast.makeText(getApplicationContext(),"couldnt load bitmap",Toast.LENGTH_SHORT).show();
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.get().load(obj.getDownloadUrl()).into(target);
//click listener for upload button
btnUpdateCreator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = edCreatorName.getText().toString();
String Email = edCreatorEmail.getText().toString();
String Phone = edCreatorMobile.getText().toString();
String Post = edCreatorDesignation.getText().toString();
if (Name.isEmpty()) {
edCreatorName.setError("*required");
} else if (Email.isEmpty()) {
edCreatorEmail.setError("*required");
} else if (Phone.isEmpty()) {
edCreatorMobile.setError("*required");
} else if (Post.isEmpty()) {
edCreatorDesignation.setError("*required");
} else if (mbitmap== null) {
Toast.makeText(getApplicationContext(), "Please add an image", Toast.LENGTH_SHORT).show();
} else {
updateMember();
}
}
});
//activity result launcher
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
try {
mbitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result);
} catch (IOException e) {
e.printStackTrace();
}
previewImage.setImageBitmap(mbitmap);
}
});
//select image click listener
SelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
someActivityResultLauncher.launch("image/*");
}
});
//delete btn click event
btnDeleteCreator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(updataDelete.this, "deleted successfully", Toast.LENGTH_SHORT).show();
}
});
}
private void updateMember(){
Toast.makeText(updataDelete.this,"updated successfully",Toast.LENGTH_SHORT).show();
//inside here I want to update the bitmap image inside the URL without changing its download URL in the real-time database because at uploading for the first time I have uploaded the image in the storage and stored it URL in the real-time database now I want to update that image how should //I approach this ??
}
}
above written code was the activity that I used to update the image bitmap
It's not possible. Each version of a file uploaded to storage has a unique URL. If the object in storage is changed by uploading a new version, then it will require a new URL (with a new token) to get the latest version.
See also: Firebase Storage - Download URL different from actual Download URL in the console (token differs)
I am working on an Android Activity where I want to pass a Camera Intent to an Input Stream, in order to process it further through the Activity;
The aim is that the user can make a Camera picture and that the picture is then processed as an Input Stream and passed to an API.
I am not sure if that´s the best way to "convert" a Camera Image into an Input Stream, therefore I am open to any suggestion and hint; this is my code so far:
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.FaceAnnotation;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import static java.nio.channels.Pipe.open;
public class VisionAPIActivity extends AppCompatActivity {
ImageView imgFavorite;
public final static int CAMERA_REQUEST = 1888;
public void TakePicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TakePicture();
setContentView(R.layout.activity_vision_api);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Vision.Builder visionBuilder = new Vision.Builder(
new NetHttpTransport(),
new AndroidJsonFactory(),
null);
visionBuilder.setVisionRequestInitializer(
new VisionRequestInitializer("AIzaSyCnPwvnEQakkUXpkFaj2TcwJs_E3DPqjm0"));
final Vision vision = visionBuilder.build();
Log.i("log-", "passed VisionBuilder Initialisation");
// Create new thread
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// Convert photo to byte array
final InputStream inputStream =
getResources().openRawResource(R.raw.skate);
byte[] photoData = new byte[0];
Log.i("log-", "Content of Photo Data" + photoData);
try {
photoData = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Image inputImage = new Image();
inputImage.encodeContent(photoData);
Feature desiredFeature = new Feature();
desiredFeature.setType("FACE_DETECTION");
AnnotateImageRequest request = new AnnotateImageRequest();
request.setImage(inputImage);
Log.i("log-", "Content of inputImage" + inputImage);
request.setFeatures(Arrays.asList(desiredFeature));
BatchAnnotateImagesRequest batchRequest =
new BatchAnnotateImagesRequest();
batchRequest.setRequests(Arrays.asList(request));
BatchAnnotateImagesResponse batchResponse =
null;
try {
batchResponse = vision.images().annotate(batchRequest).execute();
List<FaceAnnotation> faces = batchResponse.getResponses()
.get(0).getFaceAnnotations();
// Count faces
int numberOfFaces = faces.size();
Log.i("log-", "number Of Faces" + numberOfFaces);
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView mImageView;
mImageView = findViewById(R.id.imageViewId);
InputStream is = getResources().openRawResource(R.raw.skate);
mImageView.setImageBitmap(BitmapFactory.decodeStream(is));
}
});
// Get joy likelihood for each face
String likelihoods = "";
for (int i = 0; i < numberOfFaces; i++) {
likelihoods += "\n It is " +
faces.get(i).getJoyLikelihood() +
" that face " + i + " is happy";
}
// Concatenate everything
final String message =
"This photo has " + numberOfFaces + " faces" + likelihoods;
// Display toast on UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void imageClick(View view){
imgFavorite = findViewById(R.id.imageView1);
open();
}
public void open(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //IMAGE CAPTURE CODE
startActivityForResult(intent, 0);
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imgFavorite.setImageBitmap(bitmap);
}
You can trigger a Camera intent and tell it where to save your picture, after that you can open the file as an InputStream. To do so you need to pass the file Uri like this:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
If you don't pass the File Uri you'll receive a thumbnail not the full size photo. For more details take a look a the docs:
https://developer.android.com/training/camera/photobasics#TaskPath
Offroute not triggered
I am using navigation launcher.I have tried using navigation view too.But the useroffroute function is not getting triggered.
package com.example.lenovo.offroutetest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
// classes needed to initialize map
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
// classes needed to add the location component
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import android.widget.Toast;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.NavigationView;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.instruction.Instruction;
import com.mapbox.services.android.navigation.v5.milestone.BannerInstructionMilestone;
import com.mapbox.services.android.navigation.v5.milestone.Milestone;
import com.mapbox.services.android.navigation.v5.milestone.MilestoneEventListener;
import com.mapbox.services.android.navigation.v5.milestone.RouteMilestone;
import com.mapbox.services.android.navigation.v5.milestone.Trigger;
import com.mapbox.services.android.navigation.v5.milestone.TriggerProperty;
import com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation;
import com.mapbox.services.android.navigation.v5.navigation.MapboxNavigationOptions;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.offroute.OffRouteListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.navigation.NavigationEventListener;
import okhttp3.Route;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import org.intellij.lang.annotations.Identifier;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, OffRouteListener,PermissionsListener,MilestoneEventListener, ProgressChangeListener,NavigationEventListener{
private MapView mapView;
// variables for adding location layer
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private Button button;
private MapboxNavigation navigation;
private NavigationView navigationView;
private CoordinatorLayout coordinatorLayout;
private boolean running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoicHJpeWFuZ2EiLCJhIjoiY2pwYzQ1OGxpMGgybTNscGhsbjA0cXlvcSJ9.MJD97KhqBQifpKRrPGtomg");
//MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
//MapboxNavigationOptions opt=MapboxNavigationOptions.builder().build()
navigation=new MapboxNavigation(MainActivity.this,"pk.eyJ1IjoicHJpeWFuZ2EiLCJhIjoiY2pwYzQ1OGxpMGgybTNscGhsbjA0cXlvcSJ9.MJD97KhqBQifpKRrPGtomg");
//navigation.addOffRouteListener(offRouteListener);
//navigation.addMilestoneEventListener(this);
navigation.addMilestone(new BannerInstructionMilestone.Builder().setIdentifier(1).setTrigger(Trigger.all(Trigger.eq(TriggerProperty.LAST_STEP, TriggerProperty.TRUE))).setInstruction(new Instruction() {
#Override
public String buildInstruction(RouteProgress routeProgress) {
return "I AM HERE";
}
}).build());
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
//navigationView=findViewById(R.id.navigationView);
//navigationView.onCreate(savedInstanceState);
//navigationView.initialize(this);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMilestoneEvent(RouteProgress routeProgress, String instruction, Milestone milestone) {
//exampleInstructionPlayer.play(instruction);
Log.e("milestone","reached");
Toast.makeText(getApplicationContext(),"Milestone triggered",Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
enableLocationComponent();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(this);
button = findViewById(R.id.startButton);
/*navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "User rerouting", Snackbar.LENGTH_LONG);
snackbar.show();
Toast.makeText(getApplicationContext(), "Off route", Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getFilesDir();
//File path=getApplicationContext().getExternalFilesDir(null);
try {
File path=getApplicationContext().getFilesDir();
Toast.makeText(getApplicationContext(),String.valueOf(path),Toast.LENGTH_SHORT).show();
File file = new File(path, "off_route.txt");
FileOutputStream stream = new FileOutputStream(file);
stream.write(("Offroute"+location.toString()).getBytes());
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//NavigationViewOptions navopt=NavigationViewOptions.builder().directionsRoute(currentRoute).shouldSimulateRoute(false).build();
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
//navigation.startNavigation(currentRoute);
//navigation.startNavigation(currentRoute);
//navigationView.startNavigation(navopt);
}
});
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress)
{
}
#Override
public void onMapClick(#NonNull LatLng point){
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
/*try {
//File path=getApplicationContext().getFilesDir();
File path=getApplicationContext().getExternalFilesDir(null);
Toast.makeText(getApplicationContext(),String.valueOf(path.getAbsolutePath()),Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "off_route.txt");
//Log.e("Writing to file","file");
FileOutputStream stream = new FileOutputStream(file);
stream.write("Offroute am there".getBytes());
Toast.makeText(getApplicationContext(),"I ma here",Toast.LENGTH_LONG).show();
stream.close();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}*/
}
#Override
public void userOffRoute(Location location) {
//Snackbar snackbar = Snackbar
// .make(coordinatorLayout, "User rerouting", Snackbar.LENGTH_LONG);
//snackbar.show();
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getFilesDir();
//File path=getApplicationContext().getExternalFilesDir(null);
try {
File path=getApplicationContext().getExternalFilesDir(null);
Toast.makeText(getApplicationContext(),String.valueOf(path),Toast.LENGTH_SHORT).show();
File file = new File(path, "useroff.txt");
FileOutputStream stream = new FileOutputStream(file);
stream.write(("Offroute"+location.toString()).getBytes());
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void onRunning(boolean running)
{
this.running=running;
if(running)
{
//navigation.addOffRouteListener(this);
//navigation.addProgressChangeListener(this);
}
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(navigation, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
originLocation = locationComponent.getLastKnownLocation();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent();
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
I expect the function useroffroute overridden by me gets triggered.But no trigger happens as in am not able to see the toast message and file creation when the user goes offroute.
So the first thing to address here is that this will definitely not work with NavigationLauncher. That object is really meant to be a full-featured solution to get nav up and running quickly with minimal customization. So it is not quite as flexible and doesn't allow you to modify your offRoute listeners. This is only possible with NavigationView.
It's easy to miss, but the documentation for how to override the default reroute behavior is actually outlined in the Map Matching docs: https://docs.mapbox.com/android/navigation/overview/map-matching/#map-matching-with-mapboxnavigation
With that in mind, it looks like you're missing one crucial step in your code. When you add an offRouteListener to you navigation object, you need to carry through and override the userOffRoute function. Which would end up looking like this:
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});
My main activity has a button and I want that button to redirect me to the opencv camera. I have this code below and my app won't open anymore.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import nerds.thesis.clartips.adapter.ListProductAdapter;
import nerds.thesis.clartips.database.DatabaseHelper;
import nerds.thesis.clartips.model.Product;
public class CLARTIPS_Home extends AppCompatActivity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clartips__home);
lvProduct = (ListView) findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
Button tryMe = (Button) findViewById(R.id.tryMe);
tryMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCam();
}
});
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if(false==database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if (copyDatabase(this)) {
Toast.makeText(this, "Success Copying Database", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Error Copying Database", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.about:
Intent aboutIntent = new Intent(CLARTIPS_Home.this, About.class);
startActivity(aboutIntent);
}
return super.onOptionsItemSelected(item);
}
private void showCam(){
Intent intent = new Intent(this, MA_show_camera.class);
startActivity(intent);
}
}
MA_show_camera.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
//OpenCV Classes
public class MA_show_camera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
//Used for logging success or failure messages
private static final String TAG = "OCVSample::Activity";
//Loads camera view of OpenCV for us to use. This lets us to see using OpenCV
private CameraBridgeViewBase mOpenCvCameraView;
//Used in Camera selection from menu (when implemented)
private boolean mIsJavaCamera = true;
private MenuItem mItemSwitchCamera = null;
//These variables are used (at the moment) to fix camera orientation form 270degree to 0degree
Mat mRgba;
Mat mRgbaF;
Mat mRgbaT;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status){
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public MA_show_camera(){
Log.i(TAG, "Instantiated new " + this.getClass());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.show_camera);
mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#Override
public void onPause(){
super.onPause();
if(mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume(){
super.onResume();
if(!OpenCVLoader.initDebug()){
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for Initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0, this, mLoaderCallback);
} else{
Log.d(TAG, "Internal OpenCV found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy(){
super.onDestroy();
if(mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
mRgbaF = new Mat(height, width, CvType.CV_8UC4);
mRgbaT = new Mat(height, width, CvType.CV_8UC4);
}
#Override
public void onCameraViewStopped() {
mRgba.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
//TODO Auto-generated method sub
mRgba = inputFrame.rgba();
//Rotate mRgba 90 degrees
Core.transpose(mRgba, mRgbaT);
Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
Core.flip(mRgbaF, mRgba, 1);
return mRgba; //This function must return
}
}
I found a tutorial on how to open the camera (the code I used above) but it opens right when you open the app and I wanted it to open via button so I used intent. I'm a beginner so I only know a little about opencv and android development.
you need to pass an extra parameter in the
void startActivityForResult (Intent intent, int requestCode) ;
You can look at the docs for more information.
https://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent,int)
hope this helps
In your main activity , in the onTouch() , you can replace
openCam() with
Intent myIntent = new Intent(CLARTIPS_Home.this, MA_show_camera.class);
CLARTIPS_Home.this.startActivity(myIntent);
The in your camera Activity you can get a handle on it like so
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
I have tried to get this working so that it plays in the background?? why won't it work it looks fine to me??
I am new to java/android development so hope someone can fix the issue and explain what I problem was so I can learn something
Yes I got it to stream so far but once you exit the app the music stops playing
For being new think im doing great must be since I have previous experience with PHP etc..
Thanks ;)
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
public void onClick(View v) {
if (v == buttonPlay) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
well, it is stopping because you're asking it to stop.
When the activity goes to background it pauses.
You should run the stream from a service (that stays in the background without issues) and use a bound service to communicate between activity and service http://developer.android.com/guide/components/bound-services.html