package com.example.sander.app;
import android.app.Fragment;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class BlankFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public BlankFragment() {
// Required empty public constructor
}
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
TextView mLatitudeText;
TextView mLongitudeText;
#Override
public void onCreate(Bundle bundle){
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
super.onCreate(bundle);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onStart(){
mGoogleApiClient.connect();
super.onStart();
}
#Override
public void onStop(){
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int arg0) {
}
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
//mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
final TextView txt= (TextView)view.findViewById(R.id.onzin);
//txt.setText(String.valueOf(mLastLocation.getLatitude()));
// Inflate the layout for this fragment
return view;
}
}
ANDROIDMANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sander.app">
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="orientation|screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"></activity>
</application>
</manifest>
LOGCAT
Process: com.example.sander.app, PID: 22804
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.sander.app.BlankFragment.onCreateView(BlankFragment.java:85)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This is the code I have so far, when I launch my "Graph" tab the app crashes. I don't know what I'm doing wrong could anyone help me to fix this issue. What I want is to get the Long & Lat from my last know location.
Related
I'm unable to make WorkManager survive reboot. I want my tasks to be executed automatically even after reboot.
My Device is Realme X2 with Android 10.
WorkManager is working fine. But the moment i reboot my phone and wait for 15 mins for my tasks to be executed but it simply never executes.
WorkManagerReceiver.java
package com.example.surviverebootwm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import java.util.concurrent.TimeUnit;
public class WorkManagerReceiver extends BroadcastReceiver {
WorkManager mWorkManager;
#Override
public void onReceive(Context context, Intent intent) {
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
mWorkManager = WorkManager.getInstance(context);
mWorkManager.enqueue(myWork);
}
}
TestWorker.java
package com.example.surviverebootwm;
import android.content.Context;
import android.media.MediaPlayer;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
public class TestWorker extends Worker {
public TestWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_ALARM_ALERT_URI);
mediaPlayer.setLooping(true);
mediaPlayer.start();
return Result.success();
}
}
MainActivity.java
package com.example.surviverebootwm;
import androidx.appcompat.app.AppCompatActivity;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance(MainActivity.this)
.enqueueUniquePeriodicWork("testworker", ExistingPeriodicWorkPolicy.KEEP, myWork);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.surviverebootwm">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".WorkManagerReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
</manifest>
I would like to get the location of corporate devices using a corporate application.
I've had success with locating the device when the application is in foreground but doesn't seem to work when the app is in the background or killed.
I tried to use push notification to start a service or broadcastReceiver when the app is closed or in background but nothing works.
Is there a way to fetch the location of a device no matter what state the app is in?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.c7lab.fotodinamico">
<!--
io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here.
-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:icon="#mipmap/ic_launcher"
android:label="Corporate Application">
<receiver android:name=".MyLocationService"></receiver>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name="com.example.crm_agenti.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
MyLocationService.class
package com.c7lab.fotodinamico;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static android.content.Context.MODE_PRIVATE;
public class MyLocationService extends BroadcastReceiver {
public static final String ACTION_PROCESS_UPDATE = "com.c7lab.fotodinamico.UPDATE_LOCATION";
private static final String TAG = "MyLocationService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "MYSERVICE WORK?");
SharedPreferences prefs = context.getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
String shared = prefs.getString("flutter.jsonData", null);
JsonObject ed = new JsonObject();
Gson g = new Gson();
if(shared != null) {
ed = new JsonParser().parse(shared).getAsJsonObject();
}
String usr = "no-usr";
if(ed.get("usr") != null) {
usr = ed.get("usr").getAsString();
}
if(intent != null) {
final String action = intent.getAction();
if(ACTION_PROCESS_UPDATE.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if(result != null) {
Location location = result.getLastLocation();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String location_string = new StringBuilder(""+latitude).append(" - ").append(longitude).toString();
Log.v(TAG,location_string);
}
}
}
}
}
MainActivity.class
package com.c7lab.fotodinamico;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String TAG = "MainActivity";
private Handler mainHandler = new Handler();
static MainActivity instance;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationProviderClient;
public static MainActivity getInstance() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
//scheduleJob();
getWindow().addFlags(LayoutParams.FLAG_SECURE);
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Accetta permessi posizione.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
#Override
protected void onStop() {
// call the superclass method first
super.onStop();
}
private void updateLocation() {
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, getPendingIntent());
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(this, com.c7lab.fotodinamico.MyLocationService.class);
intent.setAction(com.c7lab.fotodinamico.MyLocationService.ACTION_PROCESS_UPDATE);
return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(10f);
}
}
I have tried multiple solutions written on this site!
A lot of issues.
1)Don't use getLastLocation. This only works if the device already knows the location. Instead, use requestSingleUpdate to actually turn on the location hardware. This required you to use a real service, as a BroadcastReceiver would be killed too quickly. The BR can start the service though.
2)You need a foreground service, not a background service.
3)IN modern android, the user can choose to grant location only when the app is open and block all background access. Possibly a device policy owner can override this, not sure. But if it can't, you're screwed.
Has anyone try using appcompat-v7:22.1.1 with facebook login sdk version 4.0.0 I tried that but Failed,and I dont know how to fix it, when I try using different layout it works, but when using layout that contain LoginBUtton From facebook it does not work, here is my code :
my Activity looks like this :
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import santana.gujarat.chatmeet.R;
/**
* Created by root on 14/05/15.
*/
public class LoginActivity extends AppCompatActivity implements GraphRequest.GraphJSONObjectCallback {
private static final List<String> permissionNeeds= Arrays.asList("user_photos", "friends_photos", "email", "user_birthday", "user_friends");
private LoginButton loginButton;
private CallbackManager callbackManager;
private GraphRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_activity);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.loginhowto",
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 (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(permissionNeeds);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken();
request = GraphRequest.newMeRequest(loginResult.getAccessToken(), LoginActivity.this);
request.executeAsync();
Log.d("FB Granted", loginResult.getRecentlyGrantedPermissions().toString());
Log.d("FB Denied", loginResult.getRecentlyDeniedPermissions().toString());
AccessToken.getCurrentAccessToken();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.d("Error Login",e.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
Log.d("resultFB", user.toString());
try {
Log.d("resultFB",user.getString("username"));
} catch (JSONException e) {
}
}
}
My Manifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<activity
android:name=".activity.RegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.LoginActivity" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
</application>
</manifest>
My layout :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And the Logcat Error :
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:249)
..
Caused by: null
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
at santana.gujarat.chatmeet.activity.ListPeopleActivity.onCreate(ListPeopleActivity.java:18)
...
I started to learn Android a few days ago, and I'm stuck developing this app, what it does is basically connect to an API using volley, but when I try to run the app in my smartphone I get the following error:
-25 10:17:46.851 24476-24476/com.representemais E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rep, PID: 24476
java.lang.NullPointerException
at com.rep.app.principal.InicioActivity$AutenticacaoLocalTask$1.onResponse(InicioActivity.java:89)
at com.representemais.app.principal.InicioActivity$AutenticacaoLocalTask$1.onResponse(InicioActivity.java:84)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
This is the InicioActivity:
package com.rep.app.principal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rep.R;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InicioActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}
private TextView txtDisplay;
RequestQueue queue = Volley.newRequestQueue(this);
public class AutenticacaoLocalTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://192.168.1.15/rep-api/api/clients";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
return headers;
}
};
queue.add(jsonObjReq);
return true;
} catch (Exception e) {
Log.e("RM", e.getMessage());
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
And the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rep"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".app.principal.InicioActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".app.login.LoginActivity"
android:configChanges="keyboardHidden"
android:label="#string/app_name">
</activity>
<activity
android:name=".app.principal.MainActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.cliente.ClienteDetalheActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.login.LoginTelaBloqueada"
android:label="#string/app_name"></activity>
</application>
</manifest>
I think your forget to
setContentView(R.layout.your_layout);
You should set layout in your onCreate(...) method and then reference TextView.
Correct:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
.........
........
}
At a quick glance, it looks like you aren't setting the content view, which would cause findViewById to return null. Attempting to set the text in the non-existing TextView is what seems to be the direct cause of the crash.
This is my main page code:
package com.example.splasher;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public static String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide statusbar of Android
// could also be done later
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
EditText field= (EditText) findViewById (R.id.editText1);
field.setOnFocusChangeListener(new OnFocusChangeListener(){
public void onFocusChange(View v, boolean hasFocus){
if (hasFocus) ((EditText)v).selectAll();
}
});
text=field.getText().toString();
try{
startActivity(new Intent("com.example.splasher.View"));
}
catch(ActivityNotFoundException e){
}
}
});
}
}
This is the code of my called activity:
package com.example.splasher;
import android.os.Bundle;
import android.app.Activity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class View extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide statusbar of Android
// could also be done later
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.view);
// TextView textview=(TextView) findViewById (R.id.textView1);
// textview.setText(MainActivity.text);
}}
And this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.splasher"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".View"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.splasher.View" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I can't work out why I get this error. Any ideas? Names are all the same and with same upper, lower case letters. They are all described in manifest as well.
In your manifest, type the activity action in caps.
< action android:name="COM.EXAMPLE.SPLASHER.VIEW" / >
this is done for all activities except for the main activity
There is MainActivity.this.startActivity(new Intent(MainActivity.this, Views.class)); Views class with 's' !
there is no need of the intent filter which you have applied in the View activity..Just keep one intent filter in your MainActivity
Replace the start activity line code with following:
startActivity(new Intent(MainActivity.this,View.class));
Try to replace your startActivity call by MainActivity.this.startActivity in your MainActivity.
I think there is a scope trouble.