<s3dReadConfigFile:75>: Can't open file for reading error - java

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.

Related

Android wear OS retrieving stepcounter in background

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.

Android Studio - Speech Recognizer - onResults

Any thoughts why doesnt this code invoke the onResults method ?
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextToSpeech myTTS;
private SpeechRecognizer mySpeechRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3);
mySpeechRecognizer.startListening(intent);
}
});
initializeTextToSpeech();
initializeSpeechRecognizer();
}
private void initializeSpeechRecognizer() {
if(SpeechRecognizer.isRecognitionAvailable(this)){
mySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
speak("im here");
List<String> result = results.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION
);
processResult(result.get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
private void initializeTextToSpeech() {
myTTS=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size()==0) {
Toast.makeText(MainActivity.this, "There's no TTS engine on this device", Toast.LENGTH_LONG).show();
finish();
}
else{
myTTS.setLanguage(Locale.US);
speak("Hello Im ready");
}
}
});
}
private void speak(String message){
if(Build.VERSION.SDK_INT>=21){
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,null,null);
}
else
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void processResult(String command){
command=command.toLowerCase();
speak(command);
}S
#Override
protected void onPause(){
super.onPause();
myTTS.shutdown();
}
}
-in my AndroidManifest.xml I got the uses-permission I really dont know whats wrong any opinion is welcomed, It seems like the app is somehow skipping initializeSpeechRecognizer();. The app is only supposed to repeat what I said so thats why my processResult method contains only speak("command");
The problem was that my virtual device for some reason didn't cooperate with PC mic, on real machine it works.

How to save an image from webview?

Ya guys i have tried a lot of answers on this website and that all doesn't work at all
I have a webview app that i would love to save image in the website.
I have implemented long press to copy text in the app.
but not able to save image on long press.
those answers on context is not working
this is my main activity code can anyone please edit and answer me
and keep in mind that i only have some basic coding in java and I made most of this app from the codes of different sources
My Main Activity:
package com.example.ragulsundaram.typicaltamilan;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
SwipeRefreshLayout swipe;
private long backPressedTime;
private static final String TAG = "MainActivity";
public static int TIME_OUT=4000;
#Override
public void onBackPressed() {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
return;
}else{
Toast.makeText(getBaseContext(),"Press back again to exit,",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()){
mWebView.goBack();
}
else {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}else{
Toast.makeText(getBaseContext(),"Press back again to exit",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"Pogatheeey",Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Vankakkam",Toast.LENGTH_LONG).show();
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
public void onRefresh(){
LoadWeb();
}
});
LoadWeb();
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_DENIED){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
}
});
}
public void LoadWeb()
{
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.loadUrl("https://typicaltamila.blogspot.com/ ");
swipe.setRefreshing(true);
mWebView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
mWebView.loadUrl("file://android_asset/error.html");
}
public void onPageFinished(WebView view, String url)
{
//hide the swipe refreshlayout
swipe.setRefreshing(false);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith("magnet")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in system.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
//torrent
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url=request.getUrl().toString();
if (url.startsWith("magnet")) { Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in Android.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
//downloading files
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request= new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = android.webkit.CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription(("Downloading"));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url,contentDisposition,mimetype));
DownloadManager dm=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(MainActivity.this,"Your file is downloading",Toast.LENGTH_SHORT).show();
}
});
}
}

Cannot resolve symbol "GooglePlayServicesClient"

In Google play service 10.0.1, for the following code, when building it I get the error:
“GooglePlayServicesClient” cannot resolve the symbol
Any idea how to resolve this?
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationRequest;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.asyncTasks.EmployeeSerchResult;
import com.shuan.Project.asyncTasks.GetEmployeeSerach;
import com.shuan.Project.employer.PostViewActivity;
import java.util.List;
import java.util.Locale;
public class EmplyeeSearchActivity extends AppCompatActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private Toolbar toolbar;
private Common mApp;
private Boolean flag = false;
private LocationClient mLocationClient;
private ProgressDialog pDialog;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private ProgressBar progressBar;
private ListView list;
private AutoCompleteTextView preferSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
mApp = (Common) getApplicationContext();
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
setTheme(R.style.Junior);
} else {
setTheme(R.style.Senior);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emplyee_search);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
toolbar.setBackgroundColor(getResources().getColor(R.color.junPrimary));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.senPrimary));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
mLocationRequest = new LocationRequest();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
list = (ListView) findViewById(R.id.ser_res);
preferSearch = (AutoCompleteTextView) findViewById(R.id.prefered_serach);
new GetEmployeeSerach(EmplyeeSearchActivity.this, progressBar, preferSearch).execute();
preferSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
preferSearch.dismissDropDown();
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, preferSearch.getText().toString(),
"all").execute();
}
return false;
}
});
preferSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
TextView txt = (TextView) view.findViewById(R.id.display);
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
preferSearch.setText(txt.getText().toString());
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, txt.getText().toString(),
txt1.getText().toString()).execute();
}
});
preferSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
list.setAdapter(null);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
Intent in = new Intent(getApplicationContext(), PostViewActivity.class);
in.putExtra("jId", txt.getText().toString());
in.putExtra("apply", "no");
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emp_search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gps) {
flag = gpsStatus();
if (flag) {
new displayCurrentLocation().execute();
} else {
showGpsAlert();
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class displayCurrentLocation extends AsyncTask<String, String, String> {
String location;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmplyeeSearchActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Searching");
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Location currentLocation = mLocationClient.getLastLocation();
Geocoder geocoder = new Geocoder(EmplyeeSearchActivity.this, Locale.getDefault());
Location loc = currentLocation;
List<android.location.Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
final android.location.Address address = addresses.get(0);
location = address.getLocality();
}
} catch (Exception e) {
}
return location;
}
#Override
protected void onPostExecute(final String s) {
super.onPostExecute(s);
pDialog.cancel();
Intent in = new Intent(getApplicationContext(), EmployeeSearchResultActivity.class);
in.putExtra("loc", s);
startActivity(in);
}
}
private void showGpsAlert() {
AlertDialog.Builder build = new AlertDialog.Builder(EmplyeeSearchActivity.this);
build.setTitle("Alert")
.setMessage("Turn On your GPS! Find the Jobs & companies")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
dialog.cancel();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "Can't Find Employer", Toast.LENGTH_SHORT).show();
}
}).show();
}
private Boolean gpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStus) {
return true;
} else {
return false;
}
}
}
as mentioned in this answer i guess GooglePlayServiceClient and has become outdated so remove it and use GoogleApiClientinstead.Also LocationServices.API, and FusedLocationProviderApi were introduced.
Usage of GoogleApiClient :
To use GoogleApiClient the first thing to change is the interface, the activity or service is implementing
//old code of GooglePlayServiceClient :
public class LocationMonitoringService extends Service implements GooglePlayServicesClient.ConnectionCallbacks
//replace the above ^ code with this: new code for GoogleApiClient
public class LocationMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks
in GooglePlayServiceClient, mLocationClient was just a regular class constructor.
inGoogleApiClient a Builder is used like :
//old code of GooglePlayServiceClient :
LocationClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
replace it^ with new builder code of GoogleApiClient :
GoogleApiClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationClient.connect();
}
Examples :
Requesting location :
Old code was just a simple call like
mLocationClient.requestLocationUpdates(mLocationRequest, locationListener);
in GoogleApiClient we use FusedLocatonApi like :
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationListener);
This post shows you a implementation of most of the methods like :onConnected onConnectionFailed onConnectionSuspended etc.

List<GraphUser> users is null

I am trying to get the friends list of the current logged-in user.
Here's how I am trying to get it:
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
The problem is the users list (List<GraphUser> users) is always null.
I previously set the read permission as follows:
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
So, I am not sure what's wrong. Here is the full Code:
Solved: I didn't add the INTERNET permission in my manifest file.
package home.example.logintest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.facebook.Request;
import com.facebook.Request.GraphUserListCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
private MainFragement mainFragement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragement = new MainFragement();
mainFragement.setParentActivity(this);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragement).commit();
} else {
// Or set the fragment from restored state info
mainFragement = (MainFragement) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
// try {
// PackageInfo info = getPackageManager().getPackageInfo(
// "home.example.logintest", PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md = MessageDigest.getInstance("SHA");
// md.update(signature.toByteArray());
// Log.d("KeyHash:",
// Base64.encodeToString(md.digest(), Base64.DEFAULT));
// }
// } catch (NameNotFoundException e) {
//
// } catch (NoSuchAlgorithmException e) {
//
// }
}
#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;
}
public static class MainFragement extends Fragment {
private UiLifecycleHelper uiHelper;
private ArrayList<FriendInfoHolder> friendsList;
private Activity parentActivity;
public Activity getParentActivity() {
return parentActivity;
}
public void setParentActivity(Activity parentActivity) {
this.parentActivity = parentActivity;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container,
false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i("msg", "Logged in...");
fetchFriends(session);
} else if (state.isClosed()) {
Log.i("msg", "Logged out...");
}
}
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
private FriendInfoHolder buildFriendInfoHolder(GraphUser user) {
String profilePictureUrl = "graph.facebook.com/" + user.getId()
+ "/picture?type=square";
return new FriendInfoHolder(user.getFirstName(),
user.getLastName(), profilePictureUrl);
}
}
}
The problem was that I didn't add the INTERNET permission in the manifest file.

Categories