一开始位置是空的 [英] Location is empty at the start

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

问题描述

我正在重新定义我的最后一个问题,该问题没有得到解答,并且我已经按照 Google 的基本位置.

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

with 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

这表明,在开始时,位置为空,

This shows, at the start, location is null,

I/System.out:位置为空

I/System.out: location null

然后创建sunfragment的recyclerview

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

在创建sunfragmentoncreateview 之前,是否可以先获取位置?

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.

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

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.

你应该使用fragment的arguments(Bundle)将初始数据传递给fragment

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天全站免登陆