M Garp M Garp - 8 days ago 8
Android Question

TextView value not being updated by the Service - Android GPS

I have a button that starts my DelayedMessageService. The service is very simple service because all it does is calculate the distance travelled by the user. I want to display the total distance travelled but the problem is it's not displaying the value in the TextView of my MainAcitivy. Can someone please help me fix this issue. Here is my MainAcvity, Service, and activity_main.xml:

MainActivity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
String distanceStr;

DelayedMessageService mDelayedMessageService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


watchMileage();



Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DelayedMessageService.class);
intent.putExtra(DelayedMessageService.EXTRA_MESSAGE,
getResources().getString(R.string.button_response));
startService(intent);
}
});
}

private void watchMileage() {
final TextView distanceView = (TextView)findViewById(R.id.distance);
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
double distance = 0.0;
if (mDelayedMessageService != null) {
distance = mDelayedMessageService.getMiles();
}
distanceStr = String.format("%1$,.2f miles", distance);
distanceView.setText(distanceStr);
handler.postDelayed(this, 1000);
}
});
}

//Log.v("INOCRECTEA", distanceStr.toString());
}


//activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:id="@+id/button"
android:onClick="onClick"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView android:text=""
android:id="@+id/distance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:singleLine="false"
android:textSize="50sp"/>
</LinearLayout>

Answer

You declared a variable called mDelayedMessageService but I don't see you initialize it in the snippet of code you provided so it is null. And then inside watchMileage() you do

if (mDelayedMessageService != null) {
      distance = mDelayedMessageService.getMiles();
}

Obviously, your distance will always be 0.0.