Ive only been programming a few days, so I am struggling to grasp what I am doing wrong here, hoping the community can point me in the right direction..
Here my MainActivity:
package com.whatsonwhere.app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends ActionBarActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocationClient = new LocationClient(this, this, this);
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
}
/*
* Called when the Activity becomes visible.
*/
#Override
protected void onStart() {
super.onStart();
// Connect the client.
if(isGooglePlayServicesAvailable()){
mLocationClient.connect();
}
}
/*
* Called when the Activity is no longer visible.
*/
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
Location location = mLocationClient.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.whatsonwhere.app" >
<permission
android:name="com.whatsonwhere.app.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.whatsonwhere.app.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<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-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:theme="#style/AppTheme" >
<activity
android:name="com.whatsonwhere.app.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>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="mykey_here(removed)" />
</application>
</manifest>
Activity_main:
<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: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="com.whatsonwhere.app.MainActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/TopText"
android:id="#+id/textView2"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/nearme"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/search"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/loc"
android:id="#+id/textView"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
And finally the logcat:
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app D/AndroidRuntime﹕ Shutting down VM
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415e88b0)
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whatsonwhere.app/com.whatsonwhere.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.whatsonwhere.app.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
03-25 11:28:19.537 6650-6682/com.whatsonwhere.app W/ActivityThread﹕ ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
03-25 11:28:21.477 6650-6650/com.whatsonwhere.app I/Process﹕ Sending signal. PID: 6650 SIG: 9
When you specify:
setContentView(R.layout.activity_main);
And
mapFragment =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView));
map = mapFragment.getMap();
The compiler looks for R.id.mapView in R.layout.activity_main .The names are case sensitive.
The line:
map=mapFragment.getMap():
throws a NPE as the mapView isn't found in its respective layout. Check the names if id(s) and whether it is declared in the mentioned layout.
Also, alternatively..you can use:
map = ((SupportMapFragment) this.getSupportFragmentManager()
.findFragmentById(R.id.mapView)).getMap();
saves a variable declaration and l-o-c, if not necessary otherwise.
Add fragment like this:
<fragment
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/button"
class="com.google.android.gms.maps.SupportMapFragment" />
Sometimes, when the activity is created, the map is not initialised. This leads to NullPointerException.
You must move the code mapFragment etc from onCreate to onResume.
This will ensure that the activity is created and in foreground.
mapFragment is null after the findFragmentById() call. Please make sure you have id = mapView (case-sensitive) inside activity_main.xml. If you have it there, you can also try to move the work with MapFragment from onCreate to onStart or onResume
Change here from
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
to
mapFragment = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
Because in your xml file you are using
android:name="com.google.android.gms.maps.MapFragment"
Related
I am trying to develop a motion sensing application.
For this, I have created two Activities.
The first Activity takes the latitude and longitude from the user and there is a Button which saves the data and passes it onto the next Activity.
The second Activity is a GoogleMaps Activity, where I am using the user's data and all the respective managers (SensorManager, accelerometer, etc).
The first page is working fine, but when I enter the data and press the button,the application stops.
In the log, it shows that a ClassCastException is thrown in the MapsActivity class.
Please help.
Error:
12-21 17:14:44.564 5417-5417/com.example.anurag.anurag_latest_morgenall E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anurag.anurag_latest_morgenall, PID: 5417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anurag.anurag_latest_morgenall/com.example.anurag.anurag_latest_morgenall.MapsActivity}: java.lang.ClassCastException: com.example.anurag.anurag_latest_morgenall.MapsActivity cannot be cast to android.hardware.SensorEventListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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.ClassCastException: com.example.anurag.anurag_latest_morgenall.MapsActivity cannot be cast to android.hardware.SensorEventListener
at com.example.anurag.anurag_latest_morgenall.MapsActivity.onCreate(MapsActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
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)
MainActivity.java file:
package com.example.anurag.anurag_latest_morgenall;
import android.app.usage.UsageEvents;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
float x, y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText latitude = (EditText) findViewById(R.id.latitude1);
final EditText longitude = (EditText) findViewById(R.id.longitude1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
x= Float.parseFloat(latitude.getText().toString());
y= Float.parseFloat(longitude.getText().toString());
Intent intent=new Intent(getApplicationContext(),MapsActivity.class);
Bundle extras= new Bundle();
extras.putFloat("LATITUDE",x);
extras.putFloat("LONGITUDE",y);
intent.putExtras(extras);
startActivity(intent);
}
});
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
MapsActivity.java file:
package com.example.anurag.anurag_latest_morgenall;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.icu.text.SimpleDateFormat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private SensorManager sensorManager;
private Sensor accelerometer;
long lastUpdate=0;
private float last_x,last_y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
last_x = extras.getFloat("LATITUDE");
last_y = extras.getFloat("LONGITUDE");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// set up acclerometer
sensorManager= (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
accelerometer= sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
**the below line is where the error is getting pointed to**
sensorManager.registerListener((SensorEventListener) this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onSensorChanged(SensorEvent event){
Sensor mySensor= event.sensor;
if (mySensor.getType()==Sensor.TYPE_ACCELEROMETER)
{
float x= event.values[0];
float y= event.values[1];
long curTime= System.currentTimeMillis();
if(Math.abs(curTime - lastUpdate)>2000){
java.text.SimpleDateFormat date= new java.text.SimpleDateFormat("dd-MM-yyyy");
String currentDateTime= date.format(new Date());
lastUpdate=curTime;
if(Math.abs(last_x - x)>10)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(last_x,last_y))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title("Hey you moved the x-axis on "+currentDateTime));
}
if(Math.abs(last_y - y)>10)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(last_x,last_y))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Hey you moved the y-axis on "+currentDateTime));
}
last_x=x;
last_y=y;
}
}
}
public void onAccuracyChanged(Sensor sensor,int accuracy)
{
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(last_x,last_y);
mMap.addMarker(new MarkerOptions().position(sydney).title("Virginia Tech"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,14.9f));
}
}
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:id="#+id/activity_main"
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.anurag.anurag_latest_morgenall.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/TextView1"
android:text="#string/Text_Name"
android:gravity="center_horizontal"
android:textSize="20sp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="#+id/latitude1"
android:layout_alignEnd="#+id/latitude1"
android:layout_marginTop="33dp"
android:id="#+id/longitude1"
android:hint="Enter the longitude"
android:gravity="center_vertical|center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="34dp"
android:id="#+id/latitude1"
android:hint="Enter the Latitude"
android:layout_below="#+id/TextView1"
android:layout_centerHorizontal="true"
android:gravity="center_vertical|center" />
<Button
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"
android:layout_below="#+id/longitude1"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="sendData"/>
</RelativeLayout>
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anurag.anurag_latest_morgenall.MapsActivity" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anurag.anurag_latest_morgenall">
<uses-permission android:name="android.permission.INTERNET"/>
<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"/>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I have already entered all the necessary API key in the required places.
Hint: These methods do nothing
public void onSensorChanged(SensorEvent event)
public void onAccuracyChanged(Sensor sensor,int accuracy)
Tip: Add #Override onto them to let the compiler warn you that you didn't implement the interface.
class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
i have attached the registeractivity.xml file, registeractivity.java file, mainactivity.java file, manifest file and logcat.
Whenever i run this application after entering username, email and password when i click on sign-up button the stops working.
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: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="com.example.user.loginapp.RegisterActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Username"
android:ems="10"
android:id="#+id/usernameRegistereditText"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:hint="E-mail"
android:id="#+id/emailRegistereditText"
android:layout_below="#+id/usernameRegistereditText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Password"
android:id="#+id/passwordRegistereditText"
android:layout_below="#+id/emailRegistereditText"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"
android:id="#+id/signupbutton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
RegisterActivity.Java File:
package com.example.user.loginapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class RegisterActivity extends AppCompatActivity {
protected EditText mUsername;
protected EditText mEmail;
protected EditText mPassword;
protected Button mSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//initialise
mUsername=(EditText)findViewById(R.id.usernameRegistereditText);
mEmail=(EditText)findViewById(R.id.emailRegistereditText);
mPassword=(EditText)findViewById(R.id.passwordRegistereditText);
mSignup=(Button)findViewById(R.id.signupbutton);
//Listen to button
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get username password and email and convert to string
String username=mUsername.getText().toString().trim();
String email=mEmail.getText().toString().trim();
String password=mPassword.getText().toString().trim();
// store user to parse
ParseUser user=new ParseUser();
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e==null){
Toast.makeText(RegisterActivity.this,"Sign-up successful",Toast.LENGTH_LONG).show();
}else{
//error message
}
}
});
}
});
}
#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_register, 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);
}
}
mainActivity.java file:
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseObject.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
}
#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);
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.loginapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="E9N4CpvflF5WfGVaQ5kBXYHgNA1Z2BE0cXhgc82j" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="IybWtApcNpi8Ky5odgHSAp34oyaxkFw0Jz9voH5U" />
<activity
android:name=".RegisterActivity"
android:label="#string/title_activity_register" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
LOGCAT:
01-26 16:40:41.028 3836-3836/com.example.user.loginapp E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
01-26 16:40:41.048 3836-3836/com.example.user.loginapp E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
01-26 16:41:00.912 3836-3836/com.example.user.loginapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: You must create this type of ParseObject using ParseObject.create() or the proper subclass.
at com.parse.ParseObject.<init>(ParseObject.java:365)
at com.parse.ParseObject.<init>(ParseObject.java:334)
at com.parse.ParseUser.<init>(ParseUser.java:162)
at com.example.user.loginapp.RegisterActivity$1.onClick(RegisterActivity.java:43)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)
Replace below line in your code,
ParseObject testObject = new ParseObject("TestObject");
with,
ParseObject testObject = ParseObject.create("TestObject");
and it will be solved.
Reference
The error is saying that the ParseObject must be created with its create() method. You have just newed one up without using its factory method. You want something like this:
ParseObject testObject = ParseObject.create("TestObject");
Comment out the following lines an try running again:
// Parse.enableLocalDatastore(this);
// Parse.initialize(this);
// ParseObject testObject = new ParseObject("TestObject");
// testObject.put("foo", "bar");
// testObject.saveInBackground();
I am up to the "Start Another Activity" section of the Android tutorial and it simply won't work when I install and test it.
It compiles fine but running it breaks after I click the send button.
I am using the command line tools on Ubuntu 12.04 and installing to a real device, my Galaxy S5.
I am aware of logcat but haven't been able to get it working, it either shows no output at all, or gives a massive spam of output I can't keep up with. I would happily provide logcat information if I could manage to isolate my app's output and cut through everything else.
I have seen a lot of similar questions on this which leads me to believe the tutorial isn't very well written.
Here is "MyActivity.java"
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.EditText;
import android.view.View;
public class MyActivity extends Activity
{
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
/** Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called when the user clicks the send button */
public void sendMessage(View view)
{
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Here is DisplayMessageActivity
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import com.example.myfirstapp.R;
public class DisplayMessageActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Get the message from intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
//Set the text view as the activity layout
setContentView(textView);
}
}
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity
android:name="MyActivity"
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.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MyActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MyActivity"
/>
</activity>
</application>
</manifest>
EDIT: Here is Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
/>
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
There was some code that I changed and took out as it said to add code in, but then would later show a "this is what your code should look like" and it was missing some of the original code. I also changed the manifest package names in the activities because at the beginning it uses com.example.myfirstapp but later uses com.mycompany.myfirstapp
Any help or advice on why this seemingly simple tutorial doesn't work is greatly appreciated.
EDIT:
Logcat output - (after pressing the send button)
I/Timeline( 3812): Timeline: Activity_launch_request id:com.example.myfirstapp time:74636924
D/AndroidRuntime( 3812): Shutting down VM
E/AndroidRuntime( 3812): FATAL EXCEPTION: main
E/AndroidRuntime( 3812): Process: com.example.myfirstapp, PID: 3812
E/AndroidRuntime( 3812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
E/AndroidRuntime( 3812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
E/AndroidRuntime( 3812): at android.app.ActivityThread.access$900(ActivityThread.java:172)
E/AndroidRuntime( 3812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
E/AndroidRuntime( 3812): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 3812): at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime( 3812): at android.app.ActivityThread.main(ActivityThread.java:5834)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
E/AndroidRuntime( 3812): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:151)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:138)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
E/AndroidRuntime( 3812): at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:16)
E/AndroidRuntime( 3812): at android.app.Activity.performCreate(Activity.java:6221)
E/AndroidRuntime( 3812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
E/AndroidRuntime( 3812): ... 10 more
I/Process ( 3812): Sending signal. PID: 3812 SIG: 9
I/ActivityManager( 871): Process com.example.myfirstapp (pid 3812)(adj 13) has died(104,205)
Here's the working code :
MainActivity.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
}
public void Go(View v)
{
Log.d("check", "Pressed");
String value = et.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", value);
startActivity(intent);
}
}
SecondActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
public class SecondActivity extends ActionBarActivity {
TextView textv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
String txt = getIntent().getStringExtra("key");
Log.d("check", "got : " +txt);
textv = (TextView) findViewById(R.id.textView1);
textv.setText(txt);
}
}
res/layout/activity_main.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: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.testproject.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="67dp"
android:layout_marginTop="46dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Go"
android:text="Button" />
</RelativeLayout>
res/layout/new_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity> // Registered the newly created activity
</application>
Output :
Logcat :
BY SEEING YOUR LOGCAT, I got there is a problem in your Theme.
You didn't declared AppTheme in AndroidManifest.xml file
android:theme="#style/AppTheme"
Try by This Sample Code I have made For You.
mainactivity.xml Code
<EditText
android:id="#+id/edtMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="message"
/>
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
MainActivity.class
Button btnSend;
EditText edtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String Message=edtMessage.getText().toString();
Intent intent=new Intent(getApplicationContext(),Second.class);
intent.putExtra("Message", Message);
startActivity(intent);
}
});
}
second.xml
<TextView
android:id="#+id/tviMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
Second.class
TextView tviMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tviMessage=(TextView)findViewById(R.id.tviMessage);
Bundle extras = getIntent().getExtras();
String message = extras.getString("Message");
tviMessage.setText(message);
}
Manifesto.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Second"
android:label="#string/app_name" >
</activity>
By using logcat with this command:
adb logcat | grep `adb shell ps | grep com.example.myfirstapp | cut -c10-15`
I was able to find the error causing the app to crash. It came from missing the line:
android:theme="#style/Theme.AppCompat.Light"
In the Manifest.xml file. This is required by the Activity bar compatibility class. This part was completely overlooked in the tutorial, presumably because IDEs do this part automatically.
Thank you to everybody for their help and suggestions, it helped me keep looking and trying things until I finally found my solution.
It's apparently a question that has been asked multiple times.but i am not able to find any solution anywhere. i am creating a app called awesomequotes and all this app contains images but whenever i click on the images to view in full screen it shows a error "unfortunately, aweseomequotes has stopped". i tracked the logcat errors it shows....
09-21 15:45:45.950: E/AndroidRuntime(6967): FATAL EXCEPTION: main
09-21 15:45:45.950: E/AndroidRuntime(6967): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.awesomequotes/com.example.awesomequotes.FullScreenViewActivity}: java.lang.NullPointerException
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread.access$600(ActivityThread.java:151)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.os.Handler.dispatchMessage(Handler.java:99)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.os.Looper.loop(Looper.java:155)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread.main(ActivityThread.java:5520)
09-21 15:45:45.950: E/AndroidRuntime(6967): at java.lang.reflect.Method.invokeNative(Native Method)
09-21 15:45:45.950: E/AndroidRuntime(6967): at java.lang.reflect.Method.invoke(Method.java:511)
09-21 15:45:45.950: E/AndroidRuntime(6967): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
09-21 15:45:45.950: E/AndroidRuntime(6967): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
09-21 15:45:45.950: E/AndroidRuntime(6967): at dalvik.system.NativeStart.main(Native Method)
09-21 15:45:45.950: E/AndroidRuntime(6967): Caused by: java.lang.NullPointerException
09-21 15:45:45.950: E/AndroidRuntime(6967): at com.example.awesomequotes.FullScreenViewActivity.onCreate(FullScreenViewActivity.java:54)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.Activity.performCreate(Activity.java:5066)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
09-21 15:45:45.950: E/AndroidRuntime(6967): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
09-21 15:45:45.950: E/AndroidRuntime(6967): ... 11 more
i have various classed but here i am only copying code of FullScreenActivity.java and layout file for full screen activity.
FullScreenActivity.java
package com.example.awesomequotes;
import app.AppController;
import picasa.model.Wallpaper;
import util.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
public class FullScreenViewActivity extends Activity implements OnClickListener {
private static final String TAG = FullScreenViewActivity.class
.getSimpleName();
public static final String TAG_SEL_IMAGE = "selectedImage";
private Wallpaper selectedPhoto;
private ImageView fullImageView;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
// Picasa JSON response node keys
private static final String TAG_ENTRY = "entry",
TAG_MEDIA_GROUP = "media$group",
TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url",
TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height";
#Override
protected void onCreate(Bundle savedInstanceState) {
llSetWallpaper.setOnClickListener(this);
super.onCreate(savedInstanceState);
llDownloadWallpaper.setOnClickListener(this);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
getActionBar().hide();
utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
Intent i = getIntent();
selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE);
// check for selected photo null
if (selectedPhoto != null) {
// fetch photo full resolution image by making another json request
fetchFullResolutionImage();
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT)
.show();
}
}
/**
* Fetching image fullresolution json
* */
private void fetchFullResolutionImage() {
String url = selectedPhoto.getPhotoJson();
// show loader before making request
pbLoader.setVisibility(View.VISIBLE);
llSetWallpaper.setVisibility(View.GONE);
llDownloadWallpaper.setVisibility(View.GONE);
// volley's json obj request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,
"Image full resolution json: "
+ response.toString());
try {
// Parsing the json response
JSONObject entry = response
.getJSONObject(TAG_ENTRY);
JSONArray mediacontentArry = entry.getJSONObject(
TAG_MEDIA_GROUP).getJSONArray(
TAG_MEDIA_CONTENT);
JSONObject mediaObj = (JSONObject) mediacontentArry
.get(0);
String fullResolutionUrl = mediaObj
.getString(TAG_IMG_URL);
// image full resolution widht and height
final int width = mediaObj.getInt(TAG_IMG_WIDTH);
final int height = mediaObj.getInt(TAG_IMG_HEIGHT);
Log.d(TAG, "Full resolution image. url: "
+ fullResolutionUrl + ", w: " + width
+ ", h: " + height);
ImageLoader imageLoader = AppController
.getInstance().getImageLoader();
// We download image into ImageView instead of
// NetworkImageView to have callback methods
// Currently NetworkImageView doesn't have callback
// methods
imageLoader.get(fullResolutionUrl,
new ImageListener() {
#Override
public void onErrorResponse(
VolleyError arg0) {
Toast.makeText(
getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(
ImageContainer response,
boolean arg1) {
if (response.getBitmap() != null) {
// load bitmap into imageview
fullImageView
.setImageBitmap(response
.getBitmap());
adjustImageAspect(width, height);
// hide loader and show set &
// download buttons
pbLoader.setVisibility(View.GONE);
llSetWallpaper
.setVisibility(View.VISIBLE);
llDownloadWallpaper
.setVisibility(View.VISIBLE);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
// unable to fetch wallpapers
// either google username is wrong or
// devices doesn't have internet connection
Toast.makeText(getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
});
// Remove the url from cache
AppController.getInstance().getRequestQueue().getCache().remove(url);
// Disable the cache for this url, so that it always fetches updated
// json
jsonObjReq.setShouldCache(false);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Adjusting the image aspect ration to scroll horizontally, Image height
* will be screen height, width will be calculated respected to height
* */
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if (bWidth == 0 || bHeight == 0)
return;
int sHeight = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
sHeight = size.y;
} else {
Display display = getWindowManager().getDefaultDisplay();
sHeight = display.getHeight();
}
int new_width = (int) Math.floor((double) bWidth * (double) sHeight
/ (double) bHeight);
params.width = new_width;
params.height = sHeight;
Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width
+ ", h = " + sHeight);
fullImageView.setLayoutParams(params);
}
/**
* View click listener
* */
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (v.getId()) {
// button Download Wallpaper tapped
case R.id.llDownloadWallpaper:
utils.saveImageToSDCard(bitmap);
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
utils.setAsWallpaper(bitmap);
break;
default:
break;
}
}
}
this is the layout file
activity_fullscreen_image.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black" >
<ProgressBar
android:id="#+id/pbLoader"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
</ProgressBar>
<!-- Scroll view for fullscreen preview -->
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imgFullscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY" />
</LinearLayout>
</HorizontalScrollView>
<!-- Set as wallpaper button -->
<LinearLayout
android:id="#+id/llSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ico_apply" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="#string/set_wallpaper"
android:textColor="#color/white"
android:textSize="18dp" />
</LinearLayout>
<!-- Download wallpaper button -->
<LinearLayout
android:id="#+id/llDownloadWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ico_download" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="#string/download_wallpaper"
android:textColor="#color/white"
android:textSize="18dp" />
</LinearLayout>
</RelativeLayout>
this is the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.awesomequotes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application
android:name="app.AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".FullScreenViewActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="info.androidhive.awesomewallpapers.SettingsActivity"
android:label="#string/action_settings"
android:screenOrientation="portrait" >
</activity>
</application>
</manifest>
I would really appreciate the help. its been more than 2 days since i am stucked here.
thank you
In your onCreate()
llSetWallpaper.setOnClickListener(this);
super.onCreate(savedInstanceState);
llDownloadWallpaper.setOnClickListener(this);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
you set listener before you found views. You should findViewById first
Your problem is in your onCreate method:
llSetWallpaper.setOnClickListener(this);
super.onCreate(savedInstanceState);
llDownloadWallpaper.setOnClickListener(this);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
You are setting the listeners before instatiating the items, it should be something like this:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image);
//First you instantiate the items
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
//Then you set the listener
llDownloadWallpaper.setOnClickListener(this);
I just started android programming a couple of days ago. I'm trying to integrate google plus login into my App. I followed the tutorial here. When I tried to deploy my app, I get an error message saying -
Unfortunately OAuthTest has stopped.
The logcat shows the following error:
10-10 10:31:37.239 32048-32048/agility.oauthtest D/dalvikvm﹕ Late-enabling CheckJNI
10-10 10:31:37.622 32048-32048/agility.oauthtest D/AndroidRuntime﹕ Shutting down VM
10-10 10:31:37.622 32048-32048/agility.oauthtest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x416a8d40)
10-10 10:31:37.627 32048-32048/agility.oauthtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: agility.oauthtest, PID: 32048
java.lang.RuntimeException: Unable to start activity ComponentInfo{agility.oauthtest/agility.oauthtest.login}: java.lang.NullPointerException: Null options are not permitted for this Api
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: Null options are not permitted for this Api
at com.google.android.gms.internal.fq.b(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.addApi(Unknown Source)
at agility.oauthtest.login.onCreate(login.java:83)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
My code is as follows
Activity_login.xml
<LinearLayout 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"
android:padding="16dp"
tools:context=".login" >
<LinearLayout
android:id="#+id/llProfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="horizontal"
android:weightSum="3"
android:visibility="gone">
<ImageView
android:id="#+id/imgProfilePic"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:orientation="vertical"
android:layout_weight="2" >
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/btn_sign_in"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/btn_sign_out"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_logout_from_google"
android:visibility="gone"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/btn_revoke_access"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_revoke_access"
android:visibility="gone" />
</LinearLayout>
login.java
package agility.oauthtest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import java.io.InputStream;
public class login extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "Login";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.btn_revoke_access:
// Revoke access button clicked
revokeGplusAccess();
break;
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Revoking access from google
* */
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.connect();
updateUI(false);
}
});
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="agility.oauthtest" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".login"
android:label="#string/app_name" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
What I already did -
Cleaned the Application. Rebuilt it.
What I am still confused about.
I created the Client ID in Google API Console, but I've never used it anywhere in the code. And the tutorial seems to be working for many other people.
If anyone could help me here, it would be awesome. Thanks.
pass a single parameter in addApi as .addApi(Plus.API),i.e.
Change
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
to
mGoogleApiClient = new GoogleApiClient.Builder(this,this,this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
as your Logcat shows java.lang.NullPointerException: Null options are not permitted for this Api
hence try this code:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();