开始时位置为空 [英] Location is empty at the start

查看:152
本文介绍了开始时位置为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重新定义我的最后一个问题,该问题尚未得到解答,并且我在 Google的BasicLocation .

I am reframing my last question, which is unanswered, and I have rewritten the problem following Google's BasicLocation.

我的主要活动定义为:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
//    private LocationCallback locationCallback;
//     private FusedLocationProviderClient mFusedLocationClient;
    private FusedLocationProviderClient mFusedLocationClient;
    protected Location mLastLocation;
    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
    private static final String TAG = MainActivity.class.getSimpleName();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        ImageButton leftNav = findViewById(R.id.left_nav);
        ImageButton rightNav = findViewById(R.id.right_nav);
        leftNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tab = viewPager.getCurrentItem();
                if (tab > 0) {
                    tab--;
                    viewPager.setCurrentItem(tab);
                } else if (tab == 0) {
                    viewPager.setCurrentItem(tab);
                }
            }
        });

        rightNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tab = viewPager.getCurrentItem();
                tab++;
                viewPager.setCurrentItem(tab);
            }
        });

    }
    @Override
    public void onStart() {
        super.onStart();
        if (!checkPermissions()) {
            requestPermissions();
        } else {
            getLastLocation();
        }
    }

和latlang.[Lat,Lang]在一个单独的文件中:

with latlang.[Lat,Lang] is in a seperate file:

public class latlang {
    public static double Lat;
    public static double Lang;
}

和位置文件(在viewpager中的第一个片段)定义为:

and the location file, which is the first fragment in the viewpager is defined as:

public class SunFragment extends Fragment {

    List<SunSession> sunsList;
    Typeface sunfont;


    //to be called by the MainActivity
    public SunFragment() {
        // Required empty public constructor
    }

    // Keys for storing activity state.
//  private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION_NAME = "location_name";
    public String location;//="No location name found";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve location and camera position from saved instance state.
        if (savedInstanceState != null) {
            location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString();
            System.out.println("OnCreate location  "+location);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
        onSaveInstanceState(new Bundle());
        //SecondFragment secondFragment = new SecondFragment();
        //secondFragment.getDeviceLocation();

        RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
        rv.setNestedScrollingEnabled(false);
        rv.setHasFixedSize(true);
        //MyAdapter adapter = new MyAdapter(new String[]{"Today", "Golden Hour", "Blue Hour", "Civil Twilight", "Nautical Twilight", "Astronomical Twilight", "Hello", "World"});
        //rv.setAdapter(adapter);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);
        System.out.println("location  "+location);



   /*
     Reversegeocoding location
     */
        String location="No location name found";
        String errorMessage = "";
        List<Address> addresses = null;

        Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(
                    latlang.Lat,
                    latlang.Lang,
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
            errorMessage = getString(R.string.service_not_available);
            // Log.e(TAG, errorMessage, ioException);
            if (getView() != null){
                Snackbar.make(getView(), errorMessage, Snackbar.LENGTH_LONG).show();
            }
        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            errorMessage = getString(R.string.invalid_lat_long_used);
            if (getView() != null){
                Snackbar.make(getView(),
                        "Illegal Latitude = " + latlang.Lat + ", Longitude = " +
                                latlang.Lang, Snackbar.LENGTH_LONG).show();
            }
        }
        if (addresses == null || addresses.size() == 0) {
            if (errorMessage.isEmpty()) {
                System.out.println("Adress Empty No Address Found");// Snackbar.LENGTH_LONG).show();
                location = "Lat:"+latlang.Lat+" Lang: "+latlang.Lang;
            }
        } else {
            location = addresses.get(0).getAddressLine(0);//+", "+ addresses.get(0).getLocality();
        /* for(int i = 0; i <= addresses.get(0).getMaxAddressLineIndex(); i++) {
          location = addresses.get(0).getAddressLine(i);
        }*/
        }

与此有关的问题从 logcat 显而易见:

The problem with this is evident from the logcat:

I/System.out: location  null
 I/Google Maps Android API: Google Play services package version: 17785022
 I/Choreographer: Skipped 31 frames!  The application may be doing too much work on its main thread.
 I/System.out: Position:0
 I/System.out: Position:1
 I/System.out: Position:2
 I/zygote: Do full code cache collection, code=202KB, data=177KB
 I/zygote: After code cache collection, code=129KB, data=91KB
 I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
 I/zygote: Background concurrent copying GC freed 44415(2MB) AllocSpace objects, 7(136KB) LOS objects, 49% free, 3MB/6MB, paused 294us total 102.458ms
 I/System.out: Position:3
 I/System.out: Position:4
 I/zygote: Do partial code cache collection, code=193KB, data=126KB
 I/zygote: After code cache collection, code=193KB, data=126KB
 I/zygote: Increasing code cache capacity to 1024KB
 I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
 I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
 E/MainActivity: Latit: 37.42342342342342

这首先显示位置为空,

I/System.out:位置为空

I/System.out: location null

然后创建碎片的回收视图

then the recyclerview of the sunfragment is created

 I/System.out: Position:0
 I/System.out: Position:1
 I/System.out: Position:2

然后我得到了位置:

E/MainActivity: Latit: 37.42342342342342

完整代码的链接: https://drive.google.com/file/d/1pMl_3Lf76sy82C0J4b-9ta4jbSHonJ2y/view?usp = sharing

是否可以在创建 sunfragment oncreateview 之前先获取位置?

Is it somehow possible to get the location first before creating the sunfragment's oncreateview?

推荐答案

我发现您的代码有问题(我可能错了):

I found something wrong about your code (I may be wrong):

  1. 为什么 latlang 的字段是 static ?看起来好像不应该.

  1. Why fields of latlang are static? It doesn't looks like they should.

如果 savedInstanceState!= null ,则在 SunFragment.onCreate()上,您正在读取 location .仅当保存该片段的活动已从保存状态中恢复时, savedInstanceState 不为null.它可能根本不会发生.

At SunFragment.onCreate() you are reading location if savedInstanceState != null. savedInstanceState is not null only if activity that holds this fragment was restored from saved state. It may not happen at all.

您应该使用片段的 arguments (捆绑包)将初始数据传递给片段

You should use fragment's arguments (Bundle) to pass initial data to fragment

您应该为 latlang 实现 Parcelable 接口,以便能够通过Bundle传递自定义类

You should implement Parcelable interface for latlang to be able to pass custom class thru Bundle

我认为这还不是全部,但对我而言,似乎足以使此代码无法按预期工作

I think that's not everything but for me it seems like enough for this code to not work as you expected

这篇关于开始时位置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆