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" />
Related
I'm a newbie in programming, trying to implement a Google Signin in my test app.
Folowing Google API documentation I've added all required dependencies at gradle files and registered my test app through OAuth...
Further I wrote a code as described in example provided by Google, but my app crashes at the begining, before any user's action in Virtual device, and does not even set up via APK file at the real device....
What am i doing wrong?
Main (single) activity code:
package ru.podgorny.carcall;
import android.accounts.Account;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
public class MainActivity extends AppCompatActivity {
SignInButton signInButton;
public static final int RC_SIGN_IN = 07;
public static final String TAG = "MainActivity";
TextView tw1;
TextView tw2;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
GoogleSignInClient mGSC = GoogleSignIn.getClient(this, gso);
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
}
private void findViews() {
signInButton = findViewById(R.id.idButtonGoogle);
tw1 = findViewById(R.id.textView1);
tw1 = findViewById(R.id.textView2);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.idButtonGoogle:
signIn();
break;
}
}
private void signIn() {
Intent signInIntent = mGSC.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
updateUI(account);
} catch (ApiException e) {
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
private void updateUI(GoogleSignInAccount account) {
tw1.setText("OK");
tw2.setText("Name: " + account.getGivenName() + ", Family name: " + account.getFamilyName() + ", Email: " + account.getEmail() + " image: " +
account.getPhotoUrl());
}
}
Activity.xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ru.podgorny.carcall.MainActivity"
>
<com.google.android.gms.common.SignInButton
android:id="#+id/idButtonGoogle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foregroundGravity="top"
android:onClick="onClick"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/idButtonGoogle" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView1" />
</android.support.constraint.ConstraintLayout>
Manifest.xml by default:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.podgorny.carcall">
<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>
</application>
</manifest>
Console logs :
03-23 08:35:32.774 5682-5682/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-23 08:35:32.774 5682-5682/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-23 08:35:32.775 5682-5682/? I/art: Not late-enabling -Xcheck:jni (already on)
03-23 08:35:33.180 5682-5682/ru.podgorny.carcall I/InstantRun: starting instant run server: is main process
03-23 08:35:33.746 5682-5682/ru.podgorny.carcall D/AndroidRuntime: Shutting down VM
03-23 08:35:33.753 5682-5682/ru.podgorny.carcall E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.podgorny.carcall, PID: 5682
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ru.podgorny.carcall/ru.podgorny.carcall.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:101)
at com.google.android.gms.common.api.GoogleApi.<init>(Unknown Source)
at com.google.android.gms.auth.api.signin.GoogleSignInClient.<init>(Unknown Source)
at com.google.android.gms.auth.api.signin.GoogleSignIn.getClient(Unknown Source)
at ru.podgorny.carcall.MainActivity.<init>(MainActivity.java:35)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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)
03-23 08:35:33.827 5682-5695/ru.podgorny.carcall I/art: Background sticky concurrent mark sweep GC freed 2567(255KB) AllocSpace objects, 0(0B) LOS objects, 30% free, 773KB/1117KB, paused 18.376ms total 73.744ms
Try this
GoogleSignInOptions gso ;
GoogleSignInClient mGSC ;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGSC = GoogleSignIn.getClient(this, gso);
findViews();
}
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 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.
It always crashes when ran on my device i've tried so many thing but alas im a beginner at android
The Place section which will just show you where you are on the map and you co-ordinates doesnt seem to work for me at all.
Here's My Manifest Code
After Editing Code as Suggested still doesnt work heres the log cat
Log Cat
04-02 03:45:19.025: W/dalvikvm(1102): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-02 03:45:19.104: E/AndroidRuntime(1102): FATAL EXCEPTION: main
04-02 03:45:19.104: E/AndroidRuntime(1102): java.lang.RuntimeException: Unable to start activityComponentInfo{com.hangoverhelper/com.hangoverhelper.Place}: java.lang.NullPointerException
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.os.Handler.dispatchMessage(Handler.java:99)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.os.Looper.loop(Looper.java:137)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-02 03:45:19.104: E/AndroidRuntime(1102): at java.lang.reflect.Method.invokeNative(Native Method)
04-02 03:45:19.104: E/AndroidRuntime(1102): at java.lang.reflect.Method.invoke(Method.java:511)
04-02 03:45:19.104: E/AndroidRuntime(1102): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-02 03:45:19.104: E/AndroidRuntime(1102): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-02 03:45:19.104: E/AndroidRuntime(1102): at dalvik.system.NativeStart.main(Native Method)
04-02 03:45:19.104: E/AndroidRuntime(1102): Caused by: java.lang.NullPointerException
04-02 03:45:19.104: E/AndroidRuntime(1102): at com.hangoverhelper.Place.onCreate(Place.java:42)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.Activity.performCreate(Activity.java:5104)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-02 03:45:19.104: E/AndroidRuntime(1102): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-02 03:45:19.104: E/AndroidRuntime(1102): ... 11 more
Place.java
package com.hangoverhelper;
import com.hangoverhelper.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class Place extends Activity
implements LocationSource, LocationListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.place, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_legalnotices) {
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(Place.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hangoverhelper"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<permission
android:name="com.hangoverhelper.permission.MAPS_RECEIVE"
android:protectionLevel="signature"></permission>
<uses-permission
android:name="com.hangoverhelper.permission.MAPS_RECEIVE"/>
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:logo="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity
android:name="com.hangoverhelper.SplashActivity"
android:label="#string/title_activity_splash"
android:theme="#style/Theme.Splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.hangoverhelper.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
</activity>
<activity
android:name="com.hangoverhelper.Place"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/local_title"
android:theme="#style/AppTheme" >
</activity>
<activity
android:name="com.hangoverhelper.Pill"
android:label="#string/pills_title" >
</activity>
<activity
android:name="com.hangoverhelper.Food"
android:label="#string/food_title" >
</activity>
<activity
android:name="com.hangoverhelper.Coffee"
android:label="#string/coffee_title" >
</activity>
<activity
android:name="com.hangoverhelper.Home"
android:label="#string/home_title" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBkFR4cjuUf2rw8MfLBrWS8iaS2-Th5XA4"/>
</application>
</manifest>
*activity_place.xml*
<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:orientation="vertical"
tools:context=".Place" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"
tools:layout="#layout/custom_info_contents" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#A0FFFFFF" >
<TextView
android:id="#+id/locinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/local" />
</LinearLayout>
</RelativeLayout>
You have some problems in your code:
1. Remove this line:
<uses-library android:name="com.google.android.maps" />
from the manifest file it's for Google Map API V1.
2. Place this peace of code at the bottom of your application tag:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="My API CODE"/>
with your generated key for Google Map for Android API V2.
3. The package name in those permissions:
<permission
android:name="com.example.androidmapsv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature"></permission>
<uses-permission
android:name="com.example.androidmapsv2.permission.MAPS_RECEIVE"/>
doens't match the package name specified for your application (it should):
package="com.hangoverhelper"