I'm pretty new to Android development so I'm sure this is going to turn out to be something stupid that I've missed, but I have two activities: StartScreen and Map. StartScreen is just simple text and a button, which is supposed to then take you to the Map activity.
I've already tried reducing the Map activity down to almost nothing, and I'm sure it's nothing in there that's causing the error, but I just can't figure out what is.
This is the logcat output for the error, it happens when I press the button linking the two activities:
04-28 20:40:24.097: E/AndroidRuntime(13458): FATAL EXCEPTION: main
04-28 20:40:24.097: E/AndroidRuntime(13458): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.rr.freespace/com.rr.freespace.Map}: java.lang.NullPointerException
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.access$600(ActivityThread.java:139)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.os.Looper.loop(Looper.java:154)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.main(ActivityThread.java:4945)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-28 20:40:24.097: E/AndroidRuntime(13458): at dalvik.system.NativeStart.main(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): Caused by: java.lang.NullPointerException
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.ComponentName.<init>(ComponentName.java:75)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.Intent.<init>(Intent.java:3475)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.rr.freespace.Map.<init>(Map.java:12)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.Class.newInstanceImpl(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.Class.newInstance(Class.java:1319)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
Here's my StartScreen.java:
package com.rr.freespace;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class StartScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
}
public void doIt(View view) { // Do something in response to button }
Intent intent = new Intent(this, Map.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_screen, menu);
return true;
}
}
The activity_start_screen.xml layout file:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".StartScreen" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:text="#string/hometext2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="#string/doit"
android:onClick="doIt" />
</RelativeLayout>
And finally, the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rr.freespace"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.rr.freespace.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBaoeVjdRY312vJ5KMLXxmzpKHhPiYqASo"/>
<activity
android:name="com.rr.freespace.StartScreen"
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="com.rr.freespace.Map"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
I hope someone can figure out what's going on here, because I can't! Cheers!
EDIT: here's the map.java code, there may be more errors in here that I haven't got to yet, because I hacked most of this together yesterday before I had access to an android device:
package com.rr.freespace;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class Map extends Activity {
final Context context = this;
Intent goback = new Intent(this, StartScreen.class);
protected LocationManager locationManager;
protected LocationListener listener;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
AlertDialog.Builder gpssettings = new AlertDialog.Builder(context);
gpssettings.setMessage(R.string.gpstext)
.setTitle(R.string.gpstitle);
gpssettings.setPositiveButton(R.string.gpsok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
enableLocationSettings();
}
});
gpssettings.setNegativeButton(R.string.gpscancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
startActivity(goback);
}
});
}
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.compassEnabled(false)
.rotateGesturesEnabled(false)
.tiltGesturesEnabled(false);
//Get GPS data
final LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it. Update the UI with
// the location update.
final LatLng position = new LatLng(location.getLatitude(),location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, // 10-second interval.
5, // 5 meters.
listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
protected void onStop() {
super.onStop();
locationManager.removeUpdates(listener);
}
}
Intent goback = new Intent(this, StartScreen.class);
that causes an issue.
You can't use "this" here, best to create intents just before using them.
But if You would like to have it as soon as possible do it in onCreate.
Related
I'm trying to develop basic facebook activty and The app will get username and display it in screen but I'm facing a kind of FATAL EXCEPTION: main error I have provided my complete set of codes starting with manifest file, class file, xml file and the Logcat error,your help is highly required
The below provided code is my manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.world.trialwithmugaputhagam">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MyApplicatioon"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<activity android:name=".MainFragment" />
</application>
The below code is the class file I have used.In below code I have also assigned mTextDetails but when I hover the cursor it say the value is not assigned
import android.os.Bundle;
import android.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends Fragment {
private TextView mTextDetails;
private CallbackManager mcallbackManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mcallbackManager=CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main,container,false);
}
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome "+ profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton. setReadPermissions("user_friends");
loginButton. setFragment(this);
loginButton.registerCallback(mcallbackManager, mcallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mcallbackManager.onActivityResult(requestCode, resultCode, data);
}}
The below code is my XML file
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.world.trialwithmugaputhagam.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Welcome"
android:id="#+id/text_details"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_above="#+id/login_button"/>
<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_marginTop="30dp"
android:layout_marginBottom="30dp"
android:layout_centerInParent="true"/></RelativeLayout>
Logcat error Sorry about the wrong alignment.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.world.trialwithmugaputhagam/com.example.world.trialwithmugaputhagam.MainActivity}: java.lang.ClassCastException: com.example.world.trialwithmugaputhagam.MainActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.world.trialwithmugaputhagam.MainActivity cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Because you are extending MainActivity from Fragment. Thus, your MainActivity is not actually an Activity but a Fragment. Extend it from Activity or subclasses of Activity.
Like this:
MainActivity extends AppCompatActivity
Edit 1: (Based on comments):
You haven't initialized mTextDetails;
try to do like this in Activity's onCreate:
mTextDetails = (TextView)findViewById(R.id.text_view_id);
I'm new to android and trying to add Facebook login and catch the event after clicking the Logout button(using AccessTokenTracker) in android using facebook sdk using Android studio but i'm getting this error
here is the logcat,
// (please horizontal scroll for logcat)
01-12 00:47:15.306 12572-12572/com.example.arpit.facebooklogindemo E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {com.example.arpit.facebooklogindemo/com.example.arpit.facebooklogindemo.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2790)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.arpit.facebooklogindemo.MainActivity.onResume(MainActivity.java:83)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
at android.app.Activity.performResume(Activity.java:5211)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2780)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here is AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.arpit.facebooklogindemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
//from http://developers.facebook.com
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//from http://developers.facebook.com
<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" />
</application>
</manifest>
Here is activity_main.xml,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.arpit.facebooklogindemo.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView2" />
//from http://developers.facebook.com
<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" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_above="#+id/login_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp" />
</RelativeLayout>
Here is MainActivity.java,
package com.example.arpit.facebooklogindemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
LoginButton loginButton;
TextView textView;
AccessTokenTracker accessTokenTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
if(profile != null){
fillTextView(profile);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.d("find", String.valueOf(error));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
textView.setText("Logged out");
}
}
};
accessTokenTracker.startTracking();
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, mFacebookCallback);
}
#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();
Profile profile = Profile.getCurrentProfile();
textView.setText(profile.getName());
}
#Override
protected void onDestroy(){
super.onDestroy();
accessTokenTracker.stopTracking();
}
private void fillTextView(Profile profile){
textView.setText(profile.getName());
}
}
Look at this line in your logs:
Caused by: java.lang.NullPointerException
at com.example.arpit.facebooklogindemo.MainActivity.onResume(MainActivity.java:83)
It is clearly mentioned that your app is crashing due to NullPointerException in onResume() function. One possible reason is you might be getting null profile details while calling profile.getName()
Make a null checking before setting text as below:
Profile profile = Profile.getCurrentProfile();
if(null != profile)
textView.setText(profile.getName());
Sometimes, you might get null or old profile details. In such case, you need to request for updated profile details. Below is samle code:
Profile profile = Profile.getCurrentProfile();
if(null != profile) {
new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if (currentProfile != null) {
// handle it
stopTracking();
}
}
}.startTracking();
} else {
textView.setText(profile.getName());
}
put a null check on your onResume before setting textView.
I'm trying to make an app that simply logs into facebook and then logs out. My app would compile and load however adding the line: loginButton.setFragment(this) causes a compilation which I have fixed by using the package android.support.v4.app.Fragment rather than android.app.Fragment. The issue is that now my app crashes whenever I try to run it.
This is my MainFragment.java
//MainFragment.java
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
/**
* A placeholder fragment containing a simple view.
*/
public class MainFragment extends Fragment {
private CallbackManager mCallBackManager;
private TextView mTextDetails;
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome" + profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallBackManager=CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends", "user_photos");
loginButton.setFragment(this);
loginButton.registerCallback(mCallBackManager, mCallBack);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
}
This is my MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
}
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stan.facebooktestexactexample" >
<uses-permission
android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:name=".MyApplication"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id"/>
<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="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
</manifest>
And here is my MainFragment layout file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<TextView
android:text="#+id/text_details"
android:layout_width="match_parent"
android:gravity="center"
android:layout_above="#+id/login_button"
android:layout_height="wrap_content" />
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
</RelativeLayout>
and here is the logcat
--------- beginning of crash
07-25 05:12:55.211 2473-2473/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stan.facebooktestexactexample, PID: 2473
java.lang.RuntimeException: Unable to instantiate application com.example.stan.facebooktestexactexample.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.example.stan.facebooktestexactexample.MyApplication" on path: DexPathList[[zip file "/data/app/com.example.stan.facebooktestexactexample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4529)
at android.app.ActivityThread.access$1500(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.stan.facebooktestexactexample.MyApplication" on path: DexPathList[[zip file "/data/app/com.example.stan.facebooktestexactexample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newApplication(Instrumentation.java:980)
at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4529)
at android.app.ActivityThread.access$1500(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Suppressed: java.lang.ClassNotFoundException: com.example.stan.facebooktestexactexample.MyApplication
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Please Help!!
if you set android:name=".MyApplication" on manifest you have to create MyApplication class.If you dont want that remove it or create class as
public class MyAppilcation extends Application{
...
}
it is used to declare global variables.
see this link How to declare global variables in Android?
I am working on adding GPS location services to my app. However I get this error I just can't seem to fix. I have included all of my relevant coding. And if anybody has comments on any of my coding not related to the error I would appreciate them too.
Logcat
08-09 11:19:24.602: E/AndroidRuntime(715): FATAL EXCEPTION: main
08-09 11:19:24.602: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.com.proto1/com.example.com.proto1.menu}: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:137)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:511)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-09 11:19:24.602: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.setContentView(Activity.java:1867)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.example.com.proto1.menu.onCreate(menu.java:62)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.performCreate(Activity.java:5008)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 11 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.reflect.InvocationTargetException
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.constructNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 22 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:291)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:264)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:247)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 25 more
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.proto1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/theeye"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".mainj"
android:label="#string/title_activity_mainj" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".menu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Infoactive"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.INFOSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VoicePrompts"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VOICEPROMPTS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPon"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPoff"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPOFF" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- android name must match the name of the java you want to use -->
<activity
android:name=".VoiceRecognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.RECOGNITIONMENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Recognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="ACTION_RECOGNIZE_SPEECH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SpeakingAndroid"
android:label="tts" >
<intent-filter>
<action android:name="android.intent.action.SPEAK" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="GPS_LOCATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<library
name="com.google.android.maps"
file="/system/framework/com.google.android.maps.jar" />
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="5dp" >
</ListView>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:gravity="bottom"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/aboutbutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/a"
android:textSize="25dp" />
<Button
android:id="#+id/talk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="talk"
android:textSize="25dp" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/voicebutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/starttalking"
android:textSize="25dp" />
<Button
android:id="#+id/btn_speak"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/start"
android:textSize="25dp" />
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/myGMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="API_Key_String"
android:clickable="true"
android:enabled="true" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Menu(Main) Java
package com.example.com.proto1;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.example.com.proto1.MyGPSActivity.LocationResult;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
#SuppressWarnings("unused")
public class menu extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// Got the location!
}
};
MyGPSActivity myLocation = new MyGPSActivity();
// defined
TextToSpeech mTts;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
// remember to include a listview on the xml or the voice recognition code
// will not work
public ListView mList;
// TTS object
Button speakButton, infoButton, voiceButton, talkButton;
// TTS object
public TextToSpeech myTTS;
// status check code
public int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle aboutmenu) {
super.onCreate(aboutmenu);
setContentView(R.layout.mainx);
SpeakingAndroid speak = new SpeakingAndroid();
VoiceRecognition voiceinput = new VoiceRecognition();
// get a reference to the button element listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
infoButton = (Button) findViewById(R.id.aboutbutton);
voiceButton = (Button) findViewById(R.id.voicebutton);
talkButton = (Button) findViewById(R.id.talk);
// listen for clicks
infoButton.setOnClickListener(this);
speakButton.setOnClickListener(this);
talkButton.setOnClickListener(this);
// check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// calling method
voiceinputbuttons();
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device//
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
// returns a fail statement if speech doesn't work
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
public void informationmenu() {
speakWords("information screen");
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voicemenu() {
speakWords("voice recognition menu");
startActivity(new Intent("android.intent.action.RECOGNITIONMENU"));
}
public void mainmenu() {
speakWords("main menu");
startActivity(new Intent("android.intent.action.MENU"));
}
// creating method
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
// respond to button clicks
public void onClick(View v) {
switch (v.getId()) {
// use switch case so each button does a different thing
// accurately(similar to an if statement)
case R.id.btn_speak:
String words1 = speakButton.getText().toString();
// speakwords(xxxx); is the piece of code that actually calls the
// text to speech
speakWords(words1);
myLocation.getLocation(this, locationResult);
break;
case R.id.aboutbutton:
String words2 = infoButton.getText().toString();
speakWords(words2);
Intent infoIntent = new Intent("android.intent.action.INFOSCREEN");
startActivity(infoIntent);
break;
case R.id.voicebutton:
speakWords("Speak Now");
startVoiceRecognitionActivity(); // call for voice recognition
// activity
break;
case R.id.talk:
speakWords("This is the main menu.");
break;
}
}
// speak the user text
// setting up the speakWords code
public void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Fire an intent to start the speech recognition activity.
*/
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// == Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationmenu();
}
if (matches.contains("info screen")) {
informationmenu();
}
if (matches.contains("info")) {
informationmenu();
}
if (matches.contains("about")) {
informationmenu();
}
if (matches.contains("home")) {
mainmenu();
}
if (matches.contains("menu")) {
mainmenu();
}
if (matches.contains("home screen")) {
mainmenu();
}
if (matches.contains("speak")) {
startActivity(new Intent("android.intent.action.SPEAK"));
}
if (matches.contains("close")) {
finish();
}
if (matches.contains("stop")) {
finish();
}
if (matches.contains("finish")) {
finish();
}
if (matches.contains("voice")) {
voicemenu();
}
if (matches.contains("recognition")) {
voicemenu();
}
if (matches.contains("voice recognition")) {
voicemenu();
}
}
// still in the onActivityResult: This is for the text to speech part
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myTTS.shutdown();
}
}
GPS Java
package com.example.com.proto1;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyGPSActivity {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Put the following line in the application element of AndroidManifest.xml file.
<uses-library android:name="com.google.android.maps" />
There are 3 buttons on the screen! Start, View Map, Stop
When I click View Map, it should go to a new screen that shows the map! But something goes wrong and the app is getting force closed! I keep getting Could not find class A referenced from method B error. Please please please someone correct it. I've been struck with this for 3 days!!! :'(
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="GPS App"
android:id="#+id/textView1"
android:textSize="40sp"
android:padding="10dp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:text="Start"
android:id="#+id/buttonStart"
android:textSize="30sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<Button
android:text="View Map"
android:id="#+id/buttonMap"
android:textSize="30sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<Button
android:text="Stop"
android:id="#+id/buttonStop"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
map.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mymap"
android:clickable="true"
android:enabled="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="xxxxxxxxxxxxx"
/>
<LinearLayout
android:id="#+id/myzoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Firstdroid.Gps"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<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>
<service android:permission="android.permission.INTERNET"
android:name=".IntentService" android:enabled="true" />
<activity android:name=".MapViewer" android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
</activity>
</application>
<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.READ_PHONE_STATE" />
</manifest>
MainActivity.java
package Firstdroid.Gps;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* START BUTTON */
Button startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Log.d("Firstdroid.Gps", "Starting Exploration..");
// Start Exploration
startService(new Intent(MainActivity.this, GPSexp.class));
}
});
/* MAP BUTTON */
Button mapButton = (Button) findViewById(R.id.buttonMap);
mapButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
Log.d("Firstdroid.Gps", "Loading Map..");
// Loading Google Map View
startService(new Intent(MainActivity.this, MapViewer.class));
}
});
/* STOP BUTTON */
Button stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.d("Firstdroid.Gps", "Stopping Exploration..");
// Stop Exploration
stopService(new Intent(MainActivity.this, GPSexp.class));
}
});
}
}/* End of MainActivity */
The start and stop buttons refer to GPSexp.class defined in GPSexp.java which works correctly. Problem is with MapViewer.java
MapViewer.java
package Firstdroid.Gps;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
public class MapViewer extends MapActivity {
MapView myMap;
MyLocationOverlay myLocOverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
initMap();
initMyLocation();
}
private void initMap() {
myMap = (MapView) findViewById(R.id.mymap);
View zoomView = myMap.getZoomControls();
LinearLayout myzoom = (LinearLayout) findViewById(R.id.myzoom);
myzoom.addView(zoomView);
myMap.displayZoomControls(true);
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map
*/
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, myMap);
myLocOverlay.enableMyLocation();
myMap.getOverlays().add(myLocOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Logcat
06-30 04:25:07.519: WARN/dalvikvm(357): Unable to resolve superclass of LFirstdroid/Gps/MapViewer; (37)
06-30 04:25:07.519: WARN/dalvikvm(357): Link of class 'LFirstdroid/Gps/MapViewer;' failed
06-30 04:25:07.547: ERROR/dalvikvm(357): Could not find class 'Firstdroid.Gps.MapViewer', referenced from method Firstdroid.Gps.MainActivity$2.onClick
06-30 04:25:07.547: WARN/dalvikvm(357): VFY: unable to resolve const-class 8 (LFirstdroid/Gps/MapViewer;) in LFirstdroid/Gps/MainActivity$2;
06-30 04:25:07.559: DEBUG/dalvikvm(357): VFY: replacing opcode 0x1c at 0x000d
06-30 04:25:07.573: DEBUG/dalvikvm(357): VFY: dead code 0x000f-0015 in LFirstdroid/Gps/MainActivity$2;.onClick (Landroid/view/View;)V
06-30 04:25:07.909: INFO/ActivityManager(58): Displayed activity Firstdroid.Gps/.MainActivity: 1828 ms (total 1828 ms)
06-30 04:25:13.180: DEBUG/dalvikvm(129): GC_EXPLICIT freed 670 objects / 38560 bytes in 169ms
06-30 04:25:13.840: DEBUG/Firstdroid.Gps(357): Loading Map..
06-30 04:25:13.850: DEBUG/AndroidRuntime(357): Shutting down VM
06-30 04:25:13.850: WARN/dalvikvm(357): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): FATAL EXCEPTION: main
06-30 04:25:13.880: ERROR/AndroidRuntime(357): java.lang.NoClassDefFoundError: Firstdroid.Gps.MapViewer
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at Firstdroid.Gps.MainActivity$2.onClick(MainActivity.java:40)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.view.View.performClick(View.java:2408)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.view.View$PerformClick.run(View.java:8816)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.os.Handler.handleCallback(Handler.java:587)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.os.Handler.dispatchMessage(Handler.java:92)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.os.Looper.loop(Looper.java:123)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at java.lang.reflect.Method.invokeNative(Native Method)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at java.lang.reflect.Method.invoke(Method.java:521)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-30 04:25:13.880: ERROR/AndroidRuntime(357): at dalvik.system.NativeStart.main(Native Method)
06-30 04:25:13.900: WARN/ActivityManager(58): Force finishing activity Firstdroid.Gps/.MainActivity
06-30 04:25:14.450: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{44fe90c0 Firstdroid.Gps/.MainActivity}
06-30 04:25:15.750: INFO/Process(357): Sending signal. PID: 357 SIG: 9
06-30 04:25:15.841: INFO/ActivityManager(58): Process Firstdroid.Gps (pid 357) has died.
06-30 04:25:15.880: INFO/WindowManager(58): WIN DEATH: Window{4500c988 Firstdroid.Gps/Firstdroid.Gps.MainActivity paused=false}
You added uses-library as child of the activity element... maybe that's the problem.
This is not a standard package in the
Android library. In order to use it,
you must add the following XML
element, as a child of the
application element, in your AndroidManifest.xml file:
<uses-library android:name="com.google.android.maps" />
You're using startService to start your MapViewer activity. Hope that helps