1

Can anyone please help me resolve this error? What I'm trying to do is to get current location using google play services and display city name in edit text inside a fragment.

MainActivity.java

    package com.example.mylocationwiki;


import java.util.List;
import java.util.Locale;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
        OnConnectionFailedListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    private Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private boolean mRequestingLocationUpdates = false;
    private LocationRequest mLocationRequest;

    String cityname="";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkPlayServices()) {
            buildGoogleApiClient();
        }

        try {
            getLocation();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        if(cityname!=null)Log.d("pathanor thik agey ", cityname);
        new FragmentA(cityname);

    }


    private void getLocation() throws Exception{

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            Geocoder gc=new Geocoder(this,Locale.getDefault());
            List<Address> addresses=gc.getFromLocation(latitude, longitude, 1);
            cityname=addresses.get(0).getLocality();
            if(cityname!=null)Log.d("calculate holo ", cityname );

            new FragmentA(cityname);

        } else{
        }
        return; 
    }


    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }


    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkPlayServices();
    }


    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {
        try {
            getLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }
}

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:background="#00BBFF"
android:gravity="center"
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.mylocationwiki.MainActivity" >

<fragment
    android:id="@+id/fragment1"
    android:name="com.example.mylocationwiki.FragmentA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" /></RelativeLayout>

FragmentA.java

    package com.example.mylocationwiki;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;


public class FragmentA extends Fragment implements View.OnClickListener{

    String cityname="";
    Button button;
    EditText field;

    FragmentA(String cityname){
        cityname=this.cityname;
        if(cityname!=null)Log.d("received ", cityname);

    }


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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button=(Button) getActivity().findViewById(R.id.button1);
        field=(EditText)getActivity().findViewById(R.id.editText1);
        field.setText(cityname);
    }


    @Override
    public void onClick(View v) {
        // 

    }


}

fragment_a.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="#FFBB00" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="20dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="37dp"
        android:text="Button" />

</RelativeLayout>

What I have tried so far:

Read this this link : similar question on SO and made the following changes in my project:

1) Included the following imports:

    import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

2) Made sure that MainActivity extends FragmentActivity

3) Decared getActivity() method inside onActivityCreated() method as nicely suggested here

4) Even the following part is included in my manifest as suggested Here

    <meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

Still I fail to resolve the issue. Any more insights please? Thanks!

Community
  • 1
  • 1
Swagnik Dutta
  • 117
  • 1
  • 13

1 Answers1

0

I guess the reason is that you don't have a default constructor in your Fragment class. You overloaded the constructor, but Fragment needs an empty one.
Empty Constructor for Extended Fragment
If you need to receive arguments in your fragment, do it using a Bundle:

public static YourFragment getInstance(String argument)
    {
        YourFragment fragment = new YourFragment();
        Bundle bundle = new Bundle();
        bundle.putString("argument", argument);
        fragment.setArguments(bundle);
        return fragment;
    }

And from activity:

YourFragment fragment = YourFragment.getInstance(argument);
getFragmentManager().beginTransaction().add(R.id.container, fragment, "fragmentTag").commit();

R.id.container has to be an id of your RelativeLayout (remove <fragment/> from it).

If you still want to use a <fragment/> in xml, then here is a suggestion, how to pass an argument there: If I declare a fragment in an XML layout, how do I pass it a Bundle?

Community
  • 1
  • 1
smb
  • 749
  • 1
  • 7
  • 17