I'm using an HTC Explorer to test my app
Everything was fine , till I altered the code to show my current location. The app works , but the following error is logged in on Logcat : Couldn't get connection factory client
Here is my code for MainActivity.java
package com.example.com.draft1;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.widget.Toast;
import com.google.android.maps.MapController;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends MapActivity {
private LocationManager lm;
public LocationListener locationListener;
// locationListener location =new MyLocationListener();
MapView mapView;
MapController mc;
GeoPoint p;
String coordinates[] = {"41.146064", "-80.642861"};
double lat=Double.parseDouble(coordinates[0]);
double lng=Double.parseDouble(coordinates[1]);
#Override
public void onCreate(Bundle savedInstanceState) {
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener =new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
p=new GeoPoint((int)(lat*1E6),(int)(lng*1E6));
mapView=(MapView)findViewById(R.id.mapView);
mc=mapView.getController();
mc.setCenter(p);
//mc.setZoom(13);
//mapView.invalidate();
//myMapController.setCenter(new GeoPoint((int)(lat*1E6),(int)(lng*1E6)));
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
p=new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
if(loc!= null) {
Toast.makeText(getBaseContext(),"Location : lat"+loc.getLatitude()+" Long "+loc.getLongitude(),Toast.LENGTH_SHORT).show();
}
mc.animateTo(p);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,int status,Bundle extras) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed()
{
//adssad
return false;
}
}
Why exactly is this happening ?
Any Possible solutions ?
I'd really appreciate some help with this
Cheers!
Random Error by Google it seems.Started working on its own :|
Related
I am trying to retrieve step counts from a smartwatch and push it to API. I was able to retrieve and push the data when I open the app. But once it is not activated, then it will not send any data. I am trying to use the android service to run the app in the background so that it will send the data continuously. I have given all the permissions and enabled them.
This is MainActivity.java
package com.example.stepcounter;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
}
protected void onDestroy() {
super.onDestroy();
}
public void onPressStartService(View v){
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void onPressStopService(View v){
stopService(new Intent(getApplicationContext(), MyService.class));
}
}
And this is MyService.java
package com.example.stepcounter;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MyService extends Service implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
private String HelloData;
private TextView mTextView;
private boolean isSensorPresent;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
if(mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE) != null) {
mSensor = mSensorManager.getDefaultSensor(69680);
isSensorPresent = true;
} else {
isSensorPresent = false;
}
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
mTextView.setText("Heart Rate: " + String.valueOf(event.values[0]));
HelloData = (String) String.valueOf(event.values[0]);
if(!HelloData.contains("0.0")){
postDataUsingVolley(HelloData);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private void postDataUsingVolley(String ranData) {
String url = "https://test.com";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject postData = new JSONObject();
try {
postData.put("data", ranData);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, postData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonObjectRequest);
}
}
I have also added the following in AndroidManifest.xml
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
It works for 30 seconds, send the data and once the watch goes inactive, it stops sending data. Any idea what is wrong with this?
You need to unregister your Sensor during onPause:
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
Also, if you unregister, you need to use your boolean activityRunning.
When I say add place from the menu in Android Studio, it sometimes opens the map and sometimes the application closes without opening it. When I say add place, when the application is closed without opening the map, I get the FATAL EXCEPTION: main error.
Logcat Error:
22020-10-04 09:50:34.691 12343-12343/com.nuresrasoylu.myfavoriteplaces E/AndroidRuntime: in writeCrashedAppName, pkgName :com.nuresrasoylu.myfavoriteplaces
2020-10-04 09:50:34.693 12343-12343/com.nuresrasoylu.myfavoriteplaces E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nuresrasoylu.myfavoriteplaces, PID: 12343
java.lang.AbstractMethodError: abstract method "void android.location.LocationListener.onStatusChanged(java.lang.String, int, android.os.Bundle)"
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:304)
at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:242)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6138)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
ManActivity.java
package com.nuresrasoylu.myfavoriteplaces;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_place,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.add_place) {
Intent intent = new Intent(MainActivity.this,MapsActivity.class);
intent.putExtra("info","new");
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
MapsActivity.java
package com.nuresrasoylu.myfavoriteplaces;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
LatLng lastUserLocation = new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastUserLocation,15));
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 ) {
if (requestCode == 1) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
}
}
add_place.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add_place" android:title="Add Place"></item>
</menu>
Include the below code:
public void onLocationChanged(#NonNull Location location){} :
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
I am trying to write an app which constantly monitors the speed at which I run and tells me to speed up if I am running slow and vice verse. My code has no errors, but my TextView text doesn't change as it's supposed to as per my code. Please take a look at my mainActivity.java code:
package com.example.kaushik.speed_measurement;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextToSpeech toSpeech;
int status;
String text;
String text1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
toSpeech=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener(){
#Override
public void onInit(int i) {
if ( status ==TextToSpeech.SUCCESS) {
toSpeech.setLanguage(Locale.UK);
}
else{
Toast.makeText(getApplicationContext(), "Feature not supported",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void onLocationChanged(Location location) {
TextView txt = (TextView) this.findViewById(R.id.speed);
if (location==null){
txt.setText("-,- m/s");
}
else{
float nCurrentSpeed=location.getSpeed();
txt.setText(nCurrentSpeed + "m/s");
if (nCurrentSpeed<5) {
TextView txt1 = (TextView) this.findViewById(R.id.message);
txt.setText("Speed up!");
text = ("Speed up");
toSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,null);
}
else{
TextView txt1 = (TextView) this.findViewById(R.id.message);
txt1.setText("Slow down");
text1 = ("Slow down");
toSpeech.speak(text1, TextToSpeech.QUEUE_FLUSH,null);
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I am getting this error The constructor GPS(MainActivity) is undefined after building a class to handle LocationManager interface (GPS).
... I am totally blank, I do not know what to say. I do not have much experience with java, class and interface.
The codes are posted below.
MainActivity.java
package com.bz.example;
import android.app.Activity;
import android.os.Bundle;
import com.bz.example.libs.GPS;
import com.bz.example.libs.GPSpos;
public class MainActivity extends Activity implements GPSpos {
private GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps = new GPS(MainActivity.this);
}
public void locationChanged(double longitude, double latitude) {
}
#Override
public void displayGPSSettingsDialog() {
}
}
GPSpos.java
package com.bz.example.libs;
public interface GPSpos {
public void locationChanged(double longitude, double latitude);
public void displayGPSSettingsDialog();
}
GPS.java
package com.bz.example.libs;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GPS {
private GPSpos main;
// Helper for GPS-Position
private LocationListener locationListener;
private LocationManager locationManager;
private boolean isRunning;
public void GPS(GPSpos main)
{
this.main = main;
locationManager = (LocationManager) ((Activity) this.main).getSystemService(Context.LOCATION_SERVICE);
locationListener = new locationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, locationListener);
}
public void stopGPS() {
if(isRunning) {
locationManager.removeUpdates(locationListener);
this.isRunning = false;
}
}
public void resumeGPS() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, locationListener);
this.isRunning = true;
}
public boolean isRunning() {
return this.isRunning;
}
public class locationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
GPS.this.main.locationChanged(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
GPS.this.main.displayGPSSettingsDialog();
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
remove void:
public void GPS(GPSpos main)
^^^^ - constructors in java dont have return type
I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.