Black screen and app shutdown when trying to go back to the previous activity/view - Android Studio

When i run my script below everything works fine. When i want to go back to the previous activity i get a black screen on the emulator and then the app shuts down, i also get a black screen when i exit the application and try to resume it.
The script:
Code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onResume(){
super.onResume();
drawView.resume();
}
@Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
@Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what i do get is about 13 messages saying "suspending all threads took: X ms" so it has something to the with my gameloop Thread i think. Unfortunately i dont see what the problem is in my code... Can anyone help me with this?

Related

Insert data to database SQlite

I want to insert data to a database I have created. I have created an insert command at the OnCreate class. When viewing the database in SQLite Browser the data do not show. Can anyone help me
DatabaseHelper
Code:
package app.mobiledevicesecurity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Martin on 2015/07/28.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mobilesec.db";
public static final String TABLE_NAME = "read_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "CATEGORY";
public static final String COL_3 = "HEADING";
public static final String COL_4 = "INFO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, CATEGORY TEXT, HEADING TEXT, INFO TEXT)");
ContentValues cv = new ContentValues();
cv.put(COL_2,"Malware");
cv.put(COL_3,"Virus");
cv.put(COL_4,"Harmfull for device");
db.insert(TABLE_NAME, null, cv);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
MainActivity
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
when I run the app on the emulator and open Android Device Monitor and get the database file and open it with SQlite Browser. Only the Column names are created the values are not shown. Why is this happening
Try to commit after you insert a record, also I think you can check what the insert command is returning to see if the insert command was successful or not...
The reason it isn't working is because you probably added the the insert after you had already created your database, so therefore onCreate is not being called anymore.
onUpgrade will only be called if you change the version of your database, so that will not be called either.
you should just make another method that is used to update your table, or explicitly call Oncreate.
what I did while I was testing is in the constructor of my database class, i would call a method that would drop all the tables, and then explicitly call onCreate after that. Remove this code when you are done testing

Pass data from one activity to another

Can you help me. I have developed a app with a quiz. When the quiz is finished a new activity (result) appears showing the score. I want to pass the score to a new activity namely score. Here is my code. What is wrong. The score must be showed in a textview.
Result.java
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity
{
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
Scores.java
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Intent intent = getIntent();
String value = intent.getStringExtra("somevariable");
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
txtScore1.setText("You scored" + " " + value + " for the quiz.");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scores, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this
In Result.java
i.putExtra("somevariable",score);alter this code like below..
i.putExtra("somevariable", score.toString());
you are passing integer and getting as string..try to pass it as string may help
or simply change this in scores.java
String value = intent.getStringExtra("somevariable")alter this code like below
Int value = intent.getIntExtra("somevariable")
Sent from my SM-N900 using XDA Free mobile app
As noted by taku_coder you are sending and int then you try to extract a String at least be consistent if you want to send an int then extract as an int on your receiving Activity.
Also i noted that the that you are sending the value to Result Activity shouldnt it be the Scores Activity?
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
Shouldnt it be like this?
Intent i = new Intent(getApplicationContext(), Scores.class);
i.putExtra("somevariable",score);
startActivity(i);
In Result.java
intent.putExtra("KeyName",X.toString());
you are passing as string, you can get it by using
intent.getextra("KeyName")
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
It seems to be the code above in OnCreate() method of Result make recursive creation of Result class.

How to long press on my app based webview

Hi guy this is my first application android, i using android studio and i need the help. i long press in not show context menu to download the image, below I leave the code if someone is kind enough to give me help.
Code:
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar progressBar;
private AudioManager audio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setSupportZoom(true);
webView.setVerticalScrollBarEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setHorizontalScrollBarEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl("https://alpha.wallhaven.cc/");
//Barra de progreso
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
MainActivity.this.setProgress(progress * 1000);
progressBar.incrementProgressBy(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
}
}
});
/*Adding shortcut for MainActivity
//on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent.putExtra("duplicate", false);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);*/
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
//if Back key pressed and webview can navigate to previous page
webView.goBack();
// go back to previous page
return true;
} else {
finish();
// finish the activity
}
return super.onKeyDown(keyCode, event);
default:
return false;
}
}
}

Need help in combining gyro & accelerometer sensor coding on Android Studio

I am new in javascript and android studio. Im trying to learn how to combine this 2 coding into one to get the accelerometer and gyro readings running on 1 app. The top code is for the accelerometer. The bottom is for the gyro.
HTML:
package com.example.mzr.accelerometer;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private float lastX, lastY, lastZ;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private float vibrateThreshold = 0;
private TextView currentX, currentY, currentZ, maxX, maxY, maxZ;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
//initialize vibration
}
public void initializeViews() {
currentX = (TextView) findViewById(R.id.currentX);
currentY = (TextView) findViewById(R.id.currentY);
currentZ = (TextView) findViewById(R.id.currentZ);
maxX = (TextView) findViewById(R.id.maxX);
maxY = (TextView) findViewById(R.id.maxY);
maxZ = (TextView) findViewById(R.id.maxZ);
}
//onResume() register the accelerometer for listening the events
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
[user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();
// display the max x,y,z accelerometer values
displayMaxValues();
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
}
}
public void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}
// display the current x,y,z accelerometer values
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}
// display the max x,y,z accelerometer values
public void displayMaxValues() {
if (deltaX > deltaXMax) {
deltaXMax = deltaX;
maxX.setText(Float.toString(deltaXMax));
}
if (deltaY > deltaYMax) {
deltaYMax = deltaY;
maxY.setText(Float.toString(deltaYMax));
}
if (deltaZ > deltaZMax) {
deltaZMax = deltaZ;
maxZ.setText(Float.toString(deltaZMax));
}
}
}
HTML:
package com.example.mzr.gyro;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textX, textY, textZ;
SensorManager sensorManager;
Sensor sensor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
textX = (TextView) findViewById(R.id.maxX);
textY = (TextView) findViewById(R.id.maxY);
textZ = (TextView) findViewById(R.id.maxZ);
}
public void onResume() {
super.onResume();
sensorManager.registerListener(gyroListener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStop() {
super.onStop();
sensorManager.unregisterListener(gyroListener);
}
public SensorEventListener gyroListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) { }
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
textX.setText("X : " + (int)x + " rad/s");
textY.setText("Y : " + (int)y + " rad/s");
textZ.setText("Z : " + (int)z + " rad/s");
}
};
}

Google Maps API v2 tutorials wanted.

Hi everyone,
I'm working on my first app (still a noob) with Google Maps API v2 in Android Studio and followed a couple of tutorials to get the user's current position and draw a path between two points (not working right now). I am using Retrofit to parse JSON. Now I have a current position and when the user taps the screen, a green marker appears and when the user taps again a red marker appears. Clicking on my driving button to get the route between red and green does nothing.
I would like the current position of the user also to be the starting point (so no extra markers). A user has to be able to enter an address and a new marker has to be set at that address. A route should be drawn between the current position of the user and the new address (showing distance and time) Like Runkeeper, I would like that - when the user moves - the marker at the current position moves with him.
I just can't find any good up to date tutorials which I can use to create this? Is someone able to help me or could someone look at my code? Or know any good tutorials?
Code:
package com.lemonkicks.trackmycab.trackmycab;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.lemonkicks.trackmycab.trackmycab.POJO.Example;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.List;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng origin;
LatLng dest;
ArrayList<LatLng> MarkerPoints;
TextView ShowDistanceDuration;
Polyline line;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ShowDistanceDuration = (TextView) findViewById(R.id.show_distance_time);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
//show error dialog if Google Play Services not available
if (!isGooglePlayServicesAvailable()) {
Log.d("onCreate", "Google Play Services not available. Ending Test case.");
finish();
} else {
Log.d("onCreate", "Google Play Services available. Continuing.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// clearing map and generating new marker points if user clicks on map more than two times
if (MarkerPoints.size() > 1) {
mMap.clear();
MarkerPoints.clear();
MarkerPoints = new ArrayList<>();
ShowDistanceDuration.setText("");
}
// Adding new item to the ArrayList
MarkerPoints.add(point);
Log.i("onMapClick", "Map clicked, number of points is now " + MarkerPoints.size());
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 2) {
origin = MarkerPoints.get(0);
dest = MarkerPoints.get(1);
Log.i("onMapClick", "origin and dest now set.");
} else {
Log.i("onMapClick", "origin and dest not set as number of marker points is " + MarkerPoints.size());
}
}
});
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
//Remove previous line from map
if (line != null) {
line.remove();
}
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getRoutes().size(); i++) {
String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
List<LatLng> list = decodePoly(encodedString);
line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(20)
.color(Color.RED)
.geodesic(true)
);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
// Checking if Google Play Services Available or not
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
}

Categories

Resources