Google Maps API v2 tutorials wanted. - Android Studio

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

Related

Please help with Java homework!!!

Okay here's the thing:
I have an assignment in Java class that's due in 1.5 hours and figured that this would be the best place to ask since you guys are (hopefully) good at this kind of stuff.
Here's the code:
/**
* Exercise 3.
*
* Complete the setBalances method below to set all accounts in an array to the specified value.
*
* The test methods should pass.
*
*/
public class AccountMethods {
public static void main(String[] args) {
Account[] accounts = {new Account(100, "joe"),
new Account(200, "jane"),
new Account(300, "jerry")};
testSetBalances(accounts, 50);
testBalanceNonNegative();
}
public static void setBalances(Account[] accounts, double value) {
double balance = 0;
for (int i = 0; i < accounts.length; i++) {
balance += accounts.getBalance();
}
}
public static boolean testSetBalances(Account[] accounts, double value) {
setBalances(accounts, value);
for (int i = 0; i < accounts.length; i++) {
if (accounts.getBalance() != value) {
System.out.println("testSetBalances fails on element " + i);
return false;
}
}
System.out.println("testSetBalances passes.");
return true;
}
public static boolean testBalanceNonNegative() {
Account a = new Account(100, "jim");
a.setBalance(-100);
if (a.getBalance() < 0) {
System.out.println("testBalanceNonNegtaive fails");
return false;
} else {
System.out.println("testBalanceNonNegative passes.");
return true;
}
}
}
The bold part is what I'm suppose to be working with, but I can't get it to pass in the testSetBalances method. I don't know if I'm explaining this right, but when I'm compiling the code, it's suppose to say:
testSetBalances passes
But instead, it's saying: testSetBalances fails on element 0
Don't worry about the other parts of the code because the assignment for that is done already.

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

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?

Soundpool with onTouch

Hi,everyone!
I have a question- how to make all the buttons work, like the button with its ID "button"?
There are 10 buttons (button, button2,3,5,6,7,8,9,10,11) and 10 sounds (bark, bark 2,3,5,6,7,8,9,10,11)
activity code^
[SRC JAVA]package com.example.drums.candydrums;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.button);
View view2 = findViewById(R.id.button2);
View view3 = findViewById(R.id.button3);
View view5 = findViewById(R.id.button5);
View view6 = findViewById(R.id.button6);
View view7 = findViewById(R.id.button7);
View view8 = findViewById(R.id.button8);
View view9 = findViewById(R.id.button9);
View view10 = findViewById(R.id.button10);
View view11 = findViewById(R.id.button11);
view.setOnTouchListener(this);
view2.setOnTouchListener(this);
view3.setOnTouchListener(this);
view5.setOnTouchListener(this);
view6.setOnTouchListener(this);
view7.setOnTouchListener(this);
view8.setOnTouchListener(this);
view9.setOnTouchListener(this);
view10.setOnTouchListener(this);
view11.setOnTouchListener(this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.bark, 1);
}
@override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return true;
}
}[/SRC]

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

2 editboxes 2 date pickers 2 times pickers

Hello guys
im trying to find out what im doing wrong in this case
Im trying to have 2 edittext and every time they get tapped to display date picker and time picker and get print of the date on this format "dd/MM/yyyy HH:mm"
instead of this i get "dd/MM/yyyy - HH:mm - HH:mm""
what the heck im doing wrong ?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import static com.example.neo.myapplication.R.id.currenttext;
public class MainActivity extends FragmentActivity {
static EditText DateEdit;
static EditText DateEdit2;
static TextView DateFinalText;
Button buttoncalc;
Button FinalCalc;
static String DesFinalDate;
static String DVRFinalDate;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(currenttext);
final String datecur = new SimpleDateFormat("dd-MM-yyyy HH:mm").format(Calendar.getInstance().getTime());
tv.setText(datecur);
FinalCalc = (Button) findViewById(R.id.buttoncalc);
FinalCalc.setOnClickListener(new View.OnClickListener(){
@override
public void onClick(View v) {
try {
//Dates to compare
String CurrentDate= "10/4/2017 10:21";
String FinalDate= "11/03/2016 11:21";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy HH:mm");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
});
DateEdit = (EditText) findViewById(R.id.editText1);
DateEdit.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
showTimePickerDialog(v);
showDatePickerDialog(v);
}
});
DateEdit2 = (EditText) findViewById(R.id.editText2);
DateEdit2.setOnClickListener(
new View.OnClickListener() {
@override
public void onClick(View v) {
showTimePickerDialog1(v);
showDatePickerDialog1(v);
}
});
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showDatePickerDialog1(View v) {
DialogFragment newFragment = new DatePickerFragment1();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
//DATE PICKER FRAGMENT
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + "/" + (month + 1) + "/" + year);
}
}
//DATE PICKER FRAGMENT 1
public static class DatePickerFragment1 extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit2.setText(day + "/" + (month + 1) + "/" + year);
}
}
//TIME PICKER FRAGMENT
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showTimePickerDialog1(View v) {
DialogFragment newFragment = new TimePickerFragment1();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
DateEdit.setText(DateEdit.getText() + " -" + hourOfDay + ":" + minute);
DVRFinalDate = DateEdit.toString();
}
}
//TIME PICKER FRAGMENT1
public static class TimePickerFragment1 extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
DateEdit2.setText(DateEdit2.getText() + " -" + hourOfDay + ":" + minute) ;
DesFinalDate = DateEdit2.toString();
}
}

Categories

Resources