Search code examples
location-client

Creating Location Client in Android API 19


I have been making an application that saves user location in a string, First of all I need to Define Location Services Callbacks, for Connecting the Location Client, I need to create a Location Client in OnCreate() method of my Application, so I have used the below code as my Main.java File:

As you see, the Location Client function mLocationClient.connect(); is called in OnStart() method of the activity, and that makes the application to Force Stop.

    package ir.superus8r.location3;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
    LocationClient mLocationClient;
    TextView tv01 = (TextView) findViewById(R.id.tvwtf);
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        mLocationClient = new LocationClient(this, this, this);
    }

    @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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // TODO Auto-generated method stub
        if(connectionResult.hasResolution()){
            try{
                //activity that tries to resolve the error


connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e){
                //error log
                e.printStackTrace();
            }
        } else {
            tv01.setText("Unknown Error!");
        }
    }

    @Override
    public void onConnected(Bundle dataBundle) {
        // TODO Auto-generated method stub
        // displaying the connection status
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        // Display the connection status
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
         mLocationClient.connect();
    }

}

Here's the LogCat output:

07-03 07:13:15.557: D/AndroidRuntime(28102): Shutting down VM
07-03 07:13:15.557: W/dalvikvm(28102): threadid=1: thread exiting with uncaught exception (group=0x41b978b0)
07-03 07:13:15.567: E/AndroidRuntime(28102): FATAL EXCEPTION: main
07-03 07:13:15.567: E/AndroidRuntime(28102): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ir.superus8r.location3/ir.superus8r.location3.MainActivity}: java.lang.NullPointerException
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2192)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.os.Looper.loop(Looper.java:213)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread.main(ActivityThread.java:5225)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at java.lang.reflect.Method.invokeNative(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at java.lang.reflect.Method.invoke(Method.java:525)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at dalvik.system.NativeStart.main(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102): Caused by: java.lang.NullPointerException
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.Activity.findViewById(Activity.java:1853)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at ir.superus8r.location3.MainActivity.<init>(MainActivity.java:29)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at java.lang.Class.newInstanceImpl(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at java.lang.Class.newInstance(Class.java:1130)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-03 07:13:15.567: E/AndroidRuntime(28102):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2183)
07-03 07:13:15.567: E/AndroidRuntime(28102):    ... 11 more

Any helps will be appreciated,

Thanks in advance.


Solution

  • You can use the condition while creating locationClient object.

    onStart(){
    
    if(mLocationClient==null){
    
    mLocationClient = new LocationClient(this, this, this);
    
    }
    
    mLocationClient.connect();
    
    }
    

    Else if onStart is not compulsary call mLocationClient.connect() in onCreate() itself;