11 Replies - 618 Views - Last Post: 25 March 2019 - 10:36 AM

#1 Bobby_Bubbles   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 297
  • Joined: 13-March 18

display time format 00:00:00

Posted 20 March 2019 - 09:49 AM

Im currently working on an uber like program and im trying to get my fare math right.

in order for me to do that i need to have it properly display the duration of the trip by the above format.

This is my code so far.

public void calcFare(){
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText(String.format("%.2f", distKm)+"km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText(convert2Date(curTime-startTime));
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        totalFare = baseFare + ((curTime-startTime)*costTime) + (distKm*kmRate);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(totalFare);
        tVTotal.setText(result);
    }
public static String convert2Date(int time){
        //hours
        int hours = 0;
        for(int i = 0; i >= time;){
            hours++;
            i = i + 3600;
            time = time - 3600;
        }
        //minutes
        int minutes = 0;
        for(int i = 0; i >= time;){
            minutes++;
            i = i + 3600;
            time = time - 60;
        }
        //seconds
        int seconds = time;
        return hours+":"+minutes+":"+seconds;
    }



what happens is that it doesnt add the minutes. the seconds just goes up to something like "00:00:748"

Is This A Good Question/Topic? 0
  • +

Replies To: display time format 00:00:00

#2 ndc85430   User is online

  • I think you'll find it's "Dr"
  • member icon

Reputation: 981
  • View blog
  • Posts: 3,868
  • Joined: 13-June 14

Re: display time format 00:00:00

Posted 20 March 2019 - 11:16 AM

What parts of the Java API do you have access to on Android? The stuff in java.time and java.time.format is useful. If you don't have access to those classes, perhaps Android provides its own date and time API. I find it hard to believe you'd have to write this sort of thing yourself!
Was This Post Helpful? 0
  • +
  • -

#3 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 20 March 2019 - 11:35 AM

EDIT: SEE THREE POSTS BELOW THIS IS NOT THE ANSWER!!!

check out the Timer class (Available via Android API)

https://developer.an...java/util/Timer

here's an example I found

https://v4all123.blo...3/01/timer.html

This post has been edited by hexagod: 20 March 2019 - 03:12 PM

Was This Post Helpful? 0
  • +
  • -

#4 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 20 March 2019 - 11:54 AM

Here is an example of the Time format in android.. you will need to mix the two examples

https://github.com/C...erActivity.java

This post has been edited by hexagod: 20 March 2019 - 11:56 AM

Was This Post Helpful? 0
  • +
  • -

#5 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 20 March 2019 - 02:50 PM

Actually nevermind on the Timer ... not the way you want to do this. Let me take a look at that code and figure out what's going wrong.

I apologize; I thought it worked the same way that the WPF timer does... not the same thing at all.

This post has been edited by hexagod: 20 March 2019 - 02:51 PM

Was This Post Helpful? 0
  • +
  • -

#6 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 20 March 2019 - 03:10 PM

I apologize again man... I had read those docs before and mixed up the API. Here is what you actually want

public static String convert2Date(int time)
{
    long timeLong = Long.valueOf(time);
    String formattedTimeString = DateUtils.formatElapsedTime(timeLong);
    return formattedTimeString;
}



Some of the details you might have to work out but I don't have android studio so I can't test it. I belive this is the easiest way. Convert your seconds int to a long and then use DateUtils.formatElapsedTime(long) and that method automatically outputs a formatted String for you

https://developer.an...apsedTime(long)

This post has been edited by hexagod: 20 March 2019 - 03:11 PM

Was This Post Helpful? 0
  • +
  • -

#7 Bobby_Bubbles   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 297
  • Joined: 13-March 18

Re: display time format 00:00:00

Posted 21 March 2019 - 11:52 AM

not working and the error im getting is not telling me anything...

package com.example.driveragent;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.RoundCap;

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class Index extends AppCompatActivity implements OnMapReadyCallback {
    public static String[] account;

    private int time = 20;
    private Timer timer;

    private static final LatLng ORIGIN = new LatLng(42.3149, -83.0364);
    private static final LatLng WAYPOINT = new LatLng(42.3183, -83.0373);
    private static final LatLng DESTINATION = new LatLng(42.3201, -83.0335);
    private Polyline mMutablePolyline;
    Location lastKnownLocation;
    static Double distKm = 0.0;
    static Double baseFare = 3.50;
    static Double costTime = 0.1;
    static Double kmRate = 0.1;
    static Double totalFare = 0.0;
    boolean initStart = false;
    static int startTime;
    static int curTime;
    public static boolean onFare = false;
    Location prevLoc;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private boolean mPermissionDenied = false;
    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;
    
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
    public double getKm(double lat1, double lon1, double lat2, double lon2)
    {
        final int R = 6371;
        double dLat = deg2rad(lat2 - lat1);
        double dLon = deg2rad(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = R * c;
        return d;
    }
    private double deg2rad(double deg)
    {
        return deg * (Math.PI / 180);
    }
    public void showRoute(Location location){
        BackWork bwork = new BackWork(Index.this);
        bwork.execute("directions",null,null);
        mMap.clear();
        mMutablePolyline = mMap.addPolyline(new PolylineOptions()
                .color(Color.BLUE)
                .width(10)
                .add(ORIGIN, WAYPOINT, DESTINATION));
        mMutablePolyline.setStartCap(new RoundCap());
        mMutablePolyline.setEndCap(new RoundCap());
        mMutablePolyline.setPattern(null);
    }
    public void startFare(View v){
        onFare = true;
        distKm = 0.0;
        startTime = (int)System.currentTimeMillis()/1000;
        totalFare = baseFare + ((curTime-startTime)*costTime) + (distKm*kmRate);
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText("0.00 km");
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(baseFare);
        tVTotal.setText(result);
        Button btnFare = (Button)findViewById(R.id.btnFare);
        btnFare.setText("Stop Fare");
        btnFare.setEnabled(false);
        Button btnStop = (Button)findViewById(R.id.btnStop);
        btnStop.setEnabled(true);
        startTimer();
    }
    public void stopFare(){
        Button btnFare = (Button)findViewById(R.id.btnFare);
        btnFare.setEnabled(false);
        Button btnStop = (Button)findViewById(R.id.btnStop);
        btnStop.setEnabled(true);
        timer.cancel();
        timer.purge();
    }
    public void calcFare(){
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText(String.format("%.2f", distKm)+"km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText(convert2Date(curTime-startTime));
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        totalFare = baseFare + ((curTime-startTime)*costTime) + (distKm*kmRate);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(totalFare);
        tVTotal.setText(result);
    }
    public static String convert2Date(int time){
        //hours
        int hours = 0;
        for(int i = 0; i >= time;){
            hours++;
            i = i + 3600;
            time = time - 3600;
        }
        //minutes
        int minutes = 0;
        for(int i = 0; i >= time;){
            minutes++;
            i = i + 60;
            time = time - 60;
        }
        //seconds
        int seconds = time;
        return hours+":"+minutes+":"+seconds;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tVBase = (TextView)findViewById(R.id.tVBase);
        TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
        tVDriver.setText(account[0]);
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText("0.00km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText("0:00:00");
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(baseFare);
        tVTotal.setText(result);
        tVBase.setText(result);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    public void startTimer() {
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
                        tVDuration.setText(String.format(Locale.getDefault(), "%d", time));
                        if (time > 0)
                            time -= 1;
                        else {
                            tVDuration.setText("test 2");
                        }
                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask, 0, 1000);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationchanged(Location location) {
                if(!initStart){
                    prevLoc = location;
                    initStart = true;
                }
                LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
                if(onFare){
                    distKm = distKm + getKm(prevLoc.getLatitude(),prevLoc.getLongitude(),location.getLatitude(),location.getLongitude());
                    curTime = (int)System.currentTimeMillis()/1000;
                    prevLoc = location;
                    TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
                    tVDistance.setText(String.format("%.2f", distKm)+"km");
                    TextView tVCoords = (TextView)findViewById(R.id.tVCoords);
                    tVCoords.setText("X: "+location.getLatitude()+" Y: "+location.getLongitude()+" Distance: "+distKm.toString()+"\nTime: "+(curTime-startTime));
                    calcFare();
                }

                //mMap.addMarker(new MarkerOptions().position(userLocation).title("Here"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
    }
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            enableMyLocation();
        } else {
            mPermissionDenied = true;
        }
    }
    @Override
    protected void onresumeFragments() {
        super.onresumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionerror();
            mPermissionDenied = false;
        }
    }
    private void showMissingPermissionerror() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }
}



and the error code is this.

03-21 14:42:45.340  1488  1488 E AndroidRuntime: java.lang.RuntimeException: Una
ble to start activity ComponentInfo{com.example.driveragent/com.example.driverag
ent.Index}: java.lang.NullPointerException: Attempt to read from null array
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.ActivityT
hread.performLaunchActivity(ActivityThread.java:2951)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.ActivityT
hread.handleLaunchActivity(ActivityThread.java:3086)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.servertra
nsaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.servertra
nsaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.servertra
nsaction.TransactionExecutor.execute(TransactionExecutor.java:68)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.ActivityT
hread$H.handleMessage(ActivityThread.java:1816)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.os.Handler.di
spatchMessage(Handler.java:106)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.os.Looper.loo
p(Looper.java:193)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.ActivityT
hread.main(ActivityThread.java:6718)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at java.lang.reflect.Met
hod.invoke(Native Method)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at com.android.internal.
os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at com.android.internal.
os.ZygoteInit.main(ZygoteInit.java:858)
03-21 14:42:45.340  1488  1488 E AndroidRuntime: Caused by: java.lang.NullPointe
rException: Attempt to read from null array
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at com.example.driverage
nt.Index.onCreate(Index.java:169)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.Activity.
performCreate(Activity.java:7144)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.Activity.
performCreate(Activity.java:7135)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.Instrumen
tation.callActivityOnCreate(Instrumentation.java:1271)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        at android.app.ActivityT
hread.performLaunchActivity(ActivityThread.java:2931)
03-21 14:42:45.340  1488  1488 E AndroidRuntime:        ... 11 more



the line is this...

tVDriver.setText(account[0]);



problem is when i get to index activity it pulls the information fine. it displays the driver name. The error comes when i hit the button to start fare.

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#0d579b">

    <include
        layout="@layout/map"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginBottom="0dp" />

    <TextView
        android:id="@+id/tVNull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="100dp"
        android:background="#80FFFFFF"
        android:text="Driver"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:textSize="24sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:layout_marginStart="100dp"
        android:layout_marginTop="30dp"
        app:srcCompat="@drawable/logo" />

    <TextView
        android:id="@+id/tVDriver"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="20dp"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:background="#80FFFFFF"
        android:text="No Driver"
        android:textSize="24sp"/>

    <TextView
        android:id="@+id/tVCoords"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="310dp"
        android:background="#80FFFFFF"
        android:paddingLeft="5dp"
        android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:text="TextView" />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="#80FFFFFF"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:paddingLeft="5dp"
        android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:stretchColumns="1"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="150dp">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tVNull1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Base Fare"
                android:textSize="24sp" />

            <TextView
                android:id="@+id/tVBase"
                android:gravity="right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Base"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/tVNull2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="24sp"
                android:text="Distance" />

            <TextView
                android:id="@+id/tVDistance"
                android:gravity="right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="24sp"
                android:text="Distance" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/tVNull3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="24sp"
                android:text="Duration" />

            <TextView
                android:id="@+id/tVDuration"
                android:gravity="right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="24sp"
                android:text="Duration" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/tVNull4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="30sp"
                android:text="Total" />

            <TextView
                android:id="@+id/tVTotal"
                android:gravity="right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="30sp"
                android:text="Total" />
        </TableRow>

    </TableLayout>

    <Button
        android:id="@+id/btnFare"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="155dp"
        android:layout_marginTop="93dp"
        android:onclick="startFare"
        android:text="Start Fare" />

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="155dp"
        android:layout_marginTop="93dp"
        android:onclick="stopFare"
        android:text="Stop Fare" />

</RelativeLayout>


Was This Post Helpful? 0
  • +
  • -

#8 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 21 March 2019 - 02:58 PM

"java.lang.NullPointerException: Attempt to read from null array"

Line 35 public static String[] account; you've instantiated the array but I don't see where you've assigned any value to index 0. Of course, that doesn't explain why setText works in onCreate but not your startFare method

Can you maybe try re-assigning the null array a value @ the applicable index @ the beginning of your startFare method? Very bizarre because I don't see any array required in that method. You shouldn't have to do that but maybe try it temporarily just for troubleshooting purposes? Maybe grab the driver name String and plug it into your null array (@ x index) right before onFare
Was This Post Helpful? 0
  • +
  • -

#9 Bobby_Bubbles   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 297
  • Joined: 13-March 18

Re: display time format 00:00:00

Posted 21 March 2019 - 05:05 PM

package com.example.driveragent;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackWork extends AsyncTask<String,String,String> {
    Context context;
    String type;
    BackWork (Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        type = params[0];
        String login_url = "http://24.57.17.24/SureBudz/";
        if(type.equals("login")){
            try {
                login_url = login_url + "api.php?type=login";
                String user = params[1];
                String pass = params[2];
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                urlconn.setRequestMethod("POST");
                urlconn.setDoOutput(true);
                urlconn.setDoInput(true);
                OutputStream out = urlconn.getOutputStream();
                BufferedWriter bWrite = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                String post_data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(user,"UTF-8")+"&"+URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
                bWrite.write(post_data);
                bWrite.flush();
                bWrite.close();
                out.close();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(type.equals("directions")){
            try {
                login_url = "https://maps.googleapis.com/maps/api/directions/json?origin="+params[1]+"&destination="+params[2]+"&key=AIzaSyCDNJYVNRlDzg7QiZsyFVuKsaKKjpFCEB8";
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected void onPostExecute(String result){
        String array[] = new String[12];
        if(type.equals("login")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such account", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("user");
                    Index.account = array;
                    Toast.makeText(context, "Welcome, "+array[0], Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown login Error: "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }else if(type.equals("directions")){
            if (result.equals("-1")) {
                Toast.makeText(context, "Address not found", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray routes = json.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
                    Toast.makeText(context, routes.length(), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown gmaps error "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onprogressUpdate(String... values){

    }
}




and this is the activity used to login. it goes to loading then index

package com.example.driveragent;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends AppCompatActivity {
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 1);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
    }
    public void OnLogin(View v){
        EditText eTUser = (EditText)findViewById(R.id.eTUser);
        String user = eTUser.getText().toString();
        EditText eTPass = (EditText)findViewById(R.id.eTPass);
        String pass = eTPass.getText().toString();
        if(TextUtils.isEmpty(user) || TextUtils.isEmpty(pass)){
            if(TextUtils.isEmpty(user)){
                eTUser.setError("Required Field");
            }
            if(TextUtils.isEmpty(pass)){
                eTPass.setError("Required Field");
            }
        }else{
            BackWork bwork = new BackWork(this);
            bwork.execute("login",user,pass);
            Intent intent = new Intent(this,Loading.class);
            startActivity(intent);
        }
    }
    public void gMaps(View v){
        Intent intent = new Intent(this,Maps.class);
        startActivity(intent);
    }
}


Was This Post Helpful? 0
  • +
  • -

#10 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: display time format 00:00:00

Posted 22 March 2019 - 10:51 AM

Ok well in all of that code I still don't see where you're assigning the account array any value. I see this but that's it. Just searched account and only two instances. That is one heck of a program so far, me likey.. good work homeboy

Instead of Index.account = array;

can you try this line 106 account[0] = array[0];

96-113
    @Override
    protected void onPostExecute(String result){
        String array[] = new String[12];
        if(type.equals("login")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such account", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("user");
                    account[0] = array[0];
                    Toast.makeText(context, "Welcome, "+array[0], Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown login Error: "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }



if that doesn't work try throwing that line of code at the beginning of the method that's is invoked right before you get the exception thrown. or do a breakpoint on the null array and check value before the exception.

Attached Image

This post has been edited by hexagod: 22 March 2019 - 10:55 AM

Was This Post Helpful? 0
  • +
  • -

#11 Bobby_Bubbles   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 297
  • Joined: 13-March 18

Re: display time format 00:00:00

Posted 22 March 2019 - 05:46 PM

i didnt add the index because in the future i was going to pull more information and i figured i might as well just copy the entire array for future use.

I was able to figure out what was crashing it. its wierd...but it was because i wasnt parsing the duration correctly.

i fixed it.

this is the latest revision

TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText(String.valueOf(duration));



once i was able to resolve that issue, it was starting to calculate precisely.

public class Index extends AppCompatActivity implements OnMapReadyCallback {
    public static String[] account;

    private static final LatLng ORIGIN = new LatLng(42.3149, -83.0364);
    private static final LatLng WAYPOINT = new LatLng(42.3183, -83.0373);
    private static final LatLng DESTINATION = new LatLng(42.3201, -83.0335);
    private Polyline mMutablePolyline;
    Location lastKnownLocation;
    static Double distKm = 8.0;
    static Double baseFare = 3.80;
    static Double costTime = 27.00/3600;
    static Double kmRate = 1.55;
    static Double totalFare = 0.0;
    boolean initStart = false;
    static int duration = 600;
    public static boolean onFare = false;
    Location prevLoc;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private boolean mPermissionDenied = false;
    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
    public double getKm(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371;
        double dLat = deg2rad(lat2 - lat1);
        double dLon = deg2rad(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = R * c;
        return d;
    }
    private double deg2rad(double deg){
        return deg * (Math.PI / 180);
    }
    public void showRoute(Location location){
        BackWork bwork = new BackWork(Index.this);
        bwork.execute("directions",null,null);
        mMap.clear();
        mMutablePolyline = mMap.addPolyline(new PolylineOptions()
                .color(Color.BLUE)
                .width(10)
                .add(ORIGIN, WAYPOINT, DESTINATION));
        mMutablePolyline.setStartCap(new RoundCap());
        mMutablePolyline.setEndCap(new RoundCap());
        mMutablePolyline.setPattern(null);
    }
    public void startFare(View v){
        onFare = true;
        //distKm = 0.0;
        //duration = 0;
        totalFare = baseFare;
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText("0.00km");
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(baseFare);
        tVTotal.setText(result);
        Button btnFare = (Button)findViewById(R.id.btnFare);
        btnFare.setText("Stop Fare");
        btnFare.setBackgroundColor(Color.RED);
    }
    public void calcFare(){
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText(String.format("%.2f", distKm)+"km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText(String.valueOf(duration));
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        totalFare = baseFare + (duration*costTime) + (distKm*kmRate);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(totalFare);
        tVTotal.setText(result);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tVBase = (TextView)findViewById(R.id.tVBase);
        TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
        tVDriver.setText(account[0]);
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText("0.00km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText("0:00:00");
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(baseFare);
        tVTotal.setText(result);
        tVBase.setText(result);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationchanged(Location location) {
                if(!initStart){
                    prevLoc = location;
                    initStart = true;
                }
                LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
                if(onFare){
                    //distKm = distKm + getKm(prevLoc.getLatitude(),prevLoc.getLongitude(),location.getLatitude(),location.getLongitude());
                    //duration++;
                    prevLoc = location;
                    TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
                    tVDistance.setText(String.format("%.2f", distKm)+"km");
                    TextView tVCoords = (TextView)findViewById(R.id.tVCoords);
                    tVCoords.setText("X: "+location.getLatitude()+" Y: "+location.getLongitude()+" Distance: "+distKm.toString()+"\nTime: "+String.format("%.2f",(duration*costTime)));
                    calcFare();
                }
                //mMap.addMarker(new MarkerOptions().position(userLocation).title("Here"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
    }
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            enableMyLocation();
        } else {
            mPermissionDenied = true;
        }
    }
    @Override
    protected void onresumeFragments() {
        super.onresumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionerror();
            mPermissionDenied = false;
        }
    }
    private void showMissingPermissionerror() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }
}



now onto my next issue. im trying to have the login issue resolved. 2 things, 1 to display an error saying i have no internet and 2 display that the login is incorrect.

this is my login method

public void OnLogin(View v){
        EditText eTUser = (EditText)findViewById(R.id.eTUser);
        String user = eTUser.getText().toString();
        EditText eTPass = (EditText)findViewById(R.id.eTPass);
        String pass = eTPass.getText().toString();
        if(TextUtils.isEmpty(user) || TextUtils.isEmpty(pass)){
            if(TextUtils.isEmpty(user)){
                eTUser.setError("Required Field");
            }
            if(TextUtils.isEmpty(pass)){
                eTPass.setError("Required Field");
            }
        }else{
            BackWork bwork = new BackWork(this);
            bwork.execute("login",user,pass);
            Intent intent = new Intent(this,Loading.class);
            startActivity(intent);
        }
    }



and my loading...

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        Intent intent;
        if(Index.account[0].equals("-1")){
            intent = new Intent(this,Login.class);
        }else{
            intent = new Intent(this,Index.class);
        }
        startActivity(intent);
    }



public class BackWork extends AsyncTask<String,String,String> {
    Context context;
    String type;
    BackWork (Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        type = params[0];
        String login_url = "http://ip/site/";
        if(type.equals("login")){
            try {
                login_url = login_url + "api.php?type=login";
                String user = params[1];
                String pass = params[2];
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                urlconn.setRequestMethod("POST");
                urlconn.setDoOutput(true);
                urlconn.setDoInput(true);
                OutputStream out = urlconn.getOutputStream();
                BufferedWriter bWrite = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                String post_data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(user,"UTF-8")+"&"+URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
                bWrite.write(post_data);
                bWrite.flush();
                bWrite.close();
                out.close();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                Toast.makeText(context,"malformed url exception",Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(context,"io exception",Toast.LENGTH_SHORT).show();
            }
        }else if(type.equals("directions")){
            try {
                login_url = "https://maps.googleapis.com/maps/api/directions/json?origin="+params[1]+"&destination="+params[2]+"&key=AIzaSyCDNJYVNRlDzg7QiZsyFVuKsaKKjpFCEB8";
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected void onPostExecute(String result){
        String array[] = new String[12];
        if(type.equals("login")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such account", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("user");
                    Index.account = array;
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown login Error: "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }else if(type.equals("directions")){
            if (result.equals("-1")) {
                Toast.makeText(context, "Address not found", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray routes = json.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
                    Toast.makeText(context, routes.length(), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown gmaps error "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onprogressUpdate(String... values){

    }
}



whenever the login is incorrect or cant connect to the internet it crashes...

This post has been edited by Bobby_Bubbles: 23 March 2019 - 10:58 AM

Was This Post Helpful? 0
  • +
  • -

#12 Bobby_Bubbles   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 297
  • Joined: 13-March 18

Re: display time format 00:00:00

Posted 25 March 2019 - 10:36 AM

So i found a work around...

public void OnLogin(View v){
        EditText eTUser = (EditText)findViewById(R.id.eTUser);
        String user = eTUser.getText().toString();
        EditText eTPass = (EditText)findViewById(R.id.eTPass);
        String pass = eTPass.getText().toString();
        if(TextUtils.isEmpty(user) || TextUtils.isEmpty(pass)){
            if(TextUtils.isEmpty(user)){
                eTUser.setError("Required Field");
            }
            if(TextUtils.isEmpty(pass)){
                eTPass.setError("Required Field");
            }
        }else{
            BackWork bwork = new BackWork(this);
            bwork.execute("login",user,pass);
        }
    }
    public void confirmLogin(View v){
        if (account == null) {
            Toast.makeText(this,"Please login first.",Toast.LENGTH_SHORT).show();
        }else if (account.length == 0){
            Toast.makeText(this,"Please login first."+account.length,Toast.LENGTH_SHORT).show();
        }else if(account[0].equals("-1")){
            Toast.makeText(this,"This account does not exist.",Toast.LENGTH_SHORT).show();
        }else if(account[0].equals("-2")){
            Toast.makeText(this,"Something is wrong with the server. Its not you its us.",Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(this,Index.class);
            startActivity(intent);
        }
    }



With this it checks if the array is null/empty. i only found a way to deal with it by pressing abutton to load the async to pull the login info. THEN after that resolves then i can use that array. but i can never do it in 1 run.

Moving on, what imn trying to do is get a dialog to pop up when a job is available. Here is my updated backwork class.

public class BackWork extends AsyncTask<String,String,String> {
    Context context;
    String type;
    BackWork (Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        type = params[0];
        String login_url = "http://24.57.17.24/SureBudz/";
        if(type.equals("login")){
            try {
                login_url = login_url + "api.php?type=login";
                String user = params[1];
                String pass = params[2];
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                urlconn.setRequestMethod("POST");
                urlconn.setDoOutput(true);
                urlconn.setDoInput(true);
                OutputStream out = urlconn.getOutputStream();
                BufferedWriter bWrite = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                String post_data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(user,"UTF-8")+"&"+URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
                bWrite.write(post_data);
                bWrite.flush();
                bWrite.close();
                out.close();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                Toast.makeText(context,"malformed url exception",Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(context,"io exception",Toast.LENGTH_SHORT).show();
            }
        }else if(type.equals("job")){
            try {
                login_url = login_url + "api.php?type=job";
                String jobid = params[1];
                String did = params[2];
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                urlconn.setRequestMethod("POST");
                urlconn.setDoOutput(true);
                urlconn.setDoInput(true);
                OutputStream out = urlconn.getOutputStream();
                BufferedWriter bWrite = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                String post_data = URLEncoder.encode("jid","UTF-8")+"="+URLEncoder.encode(jobid,"UTF-8")+"&"+URLEncoder.encode("did","UTF-8")+"="+URLEncoder.encode(did,"UTF-8");
                bWrite.write(post_data);
                bWrite.flush();
                bWrite.close();
                out.close();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                Toast.makeText(context,"malformed url exception",Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(context,"io exception",Toast.LENGTH_SHORT).show();
            }
        }else if(type.equals("joblist")){
            try {
                login_url = login_url + "api.php?type=joblist";
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(type.equals("directions")){
            try {
                login_url = "https://maps.googleapis.com/maps/api/directions/json?origin="+params[1]+"&destination="+params[2]+"&key=AIzaSyCDNJYVNRlDzg7QiZsyFVuKsaKKjpFCEB8";
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected void onPostExecute(String result){
        String array[] = new String[12];
        if(type.equals("login")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such account", Toast.LENGTH_SHORT).show();
                Login.account[0] = "-1";
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("id");
                    array[1] = jresponse.getString("user");
                    Toast.makeText(context, "Login successful", Toast.LENGTH_SHORT).show();
                    Login.account = array;
                    Login.logAccount = true;
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown login Error: "+e, Toast.LENGTH_SHORT).show();
                    Login.account[0] = "-2";
                    e.printStackTrace();
                }
            }
        }else if(type.equals("job")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such job available", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("id");
                    array[1] = jresponse.getString("origin");
                    array[2] = jresponse.getString("destination");
                    Toast.makeText(context, "Job Accepted", Toast.LENGTH_SHORT).show();
                    Index.jobFare = array;
                    Index.jobAvail = false;
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown job Error: "+e, Toast.LENGTH_SHORT).show();
                }
            }
        }else if(type.equals("joblist")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No jobs available", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("id");
                    array[1] = jresponse.getString("origin");
                    array[2] = jresponse.getString("destination");
                    Toast.makeText(context, "Available Job", Toast.LENGTH_SHORT).show();
                    Index.jobFare = array;
                    Index.jobAvail = true;
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown job list Error: "+e, Toast.LENGTH_SHORT).show();
                }
            }
        }else if(type.equals("directions")){
            if (result.equals("-1")) {
                Toast.makeText(context, "Address not found", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray routes = json.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
                    Toast.makeText(context, routes.length(), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown gmaps error "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onprogressUpdate(String... values){

    }
}



Here above i added a new type for job and joblist

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tVBase = (TextView)findViewById(R.id.tVBase);
        TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
        tVDriver.setText(Login.account[1]);
        TextView tVDistance = (TextView)findViewById(R.id.tVDistance);
        tVDistance.setText("0.00km");
        TextView tVDuration = (TextView)findViewById(R.id.tVDuration);
        tVDuration.setText("0:00:00");
        TextView tVTotal = (TextView)findViewById(R.id.tVTotal);
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
        format.setCurrency(Currency.getInstance("CAD"));
        String result = format.format(baseFare);
        tVTotal.setText(result);
        tVBase.setText(result);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        Toast.makeText(context,"jobAvail is "+jobAvail,Toast.LENGTH_LONG).show();
        BackWork bwork = new BackWork(this);
        bwork.execute("joblist",null,null);
        new Thread(new Runnable() {
            public void run() {
                while (jobAvail) {
                    if(jobFare == null) {
                        try {
                            TextView tVCoords = (TextView)findViewById(R.id.tVCoords);
                            tVCoords.setText("null");
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else if(jobFare.length == 0){
                        try {
                            TextView tVCoords = (TextView)findViewById(R.id.tVCoords);
                            tVCoords.setText("empty");
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                            builder1.setMessage("A new Fare has appeared!\nFrom: "+Index.jobFare[1]+"\nTo: "+Index.jobFare[2]);
                            builder1.setCancelable(false);
                            builder1.setPositiveButton(
                                    "Accept",
                                    new DialogInterface.onclickListener() {
                                        public void onclick(DialogInterface dialog, int id) {
                                            Toast.makeText(context, "Accepted", Toast.LENGTH_SHORT).show();
                                            BackWork bwork = new BackWork(context);
                                            bwork.execute("job",jobFare[0],Login.account[0]);
                                        }
                                    });
                            builder1.setNegativeButton(
                                    "Decline",
                                    new DialogInterface.onclickListener() {
                                        public void onclick(DialogInterface dialog, int id) {
                                            Toast.makeText(context, "Declined", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                            AlertDialog alert11 = builder1.create();
                            alert11.show();
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }



what happens is when it laods up the index class DISPLAYS THE TOAST "Available Job" then crashes and i get this.

03-25 13:26:44.761  3147  3224 E AndroidRuntime: FATAL EXCEPTION: Thread-10
03-25 13:26:44.761  3147  3224 E AndroidRuntime: Process: com.example.driveragen
t, PID: 3147
03-25 13:26:44.761  3147  3224 E AndroidRuntime: java.lang.RuntimeException: Can
't create handler inside thread Thread[Thread-10,5,main] that has not called Loo
per.prepare()
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.os.Handler.<i
nit>(Handler.java:205)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.os.Handler.<i
nit>(Handler.java:118)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.app.Dialog.<i
nit>(Dialog.java:123)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.app.Dialog.<i
nit>(Dialog.java:168)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.support.v7.ap
p.AppCompatDialog.<init>(AppCompatDialog.java:46)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.support.v7.ap
p.AlertDialog.<init>(AlertDialog.java:97)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at android.support.v7.ap
p.AlertDialog$Builder.create(AlertDialog.java:932)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at com.example.driverage
nt.Index$1.run(Index.java:192)
03-25 13:26:44.761  3147  3224 E AndroidRuntime:        at java.lang.Thread.run(
Thread.java:764)



Im having trouble on why the error is happening. I know i have to put in looper, but i still dont understand why its doing it.

You can view the JSON here ==> http://24.57.17.24/s...hp?type=joblist

{"id":"1","origin":"100 erie street west windsor ontario","destination":"100 goyeau windsor ontario"}


This post has been edited by Bobby_Bubbles: 25 March 2019 - 10:39 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1