Java 使用Mapsactivity时遇到错误(新手)

Java 使用Mapsactivity时遇到错误(新手),java,android,geolocation,maps,currentlocation,Java,Android,Geolocation,Maps,Currentlocation,我无法获得我的位置,我不知道为什么我在谷歌上尝试了一切,因为我是android的新手,请帮我解决这个问题 package com.parkaspot.najeeb.project; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { final Stri

我无法获得我的位置,我不知道为什么我在谷歌上尝试了一切,因为我是android的新手,请帮我解决这个问题

package com.parkaspot.najeeb.project;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
final String TAG = "MAIN";
ArrayList<RecentData> list;
RecentAdapter recentAdapter;
LinearLayoutManager linearLayoutManager;
RecyclerView recyclerView;
Drawer result;
Toolbar toolbar;
Double lat, lng;
Location location;
SharedPreferences sharedPreferences, sharedPreferences1;
String name, password;
SpotsDialog dialog;

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

    dialog = new SpotsDialog(this,"Loading...", R.style.Loading);

    sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
    sharedPreferences1 = getSharedPreferences("userDetails", Context.MODE_PRIVATE);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (networkEnabled) {
        Log.d(TAG,"network is enabled"); //shows successfully
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {  
            Log.d(TAG,"permission ******************granted"); //This log Tag Never appears in logcat

            return;
        }
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Log.d(TAG, "Location is initialized"); //shows successfully
    }

    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        Log.d(TAG, "getting latlng values"); //**Never shows
    }else{       //******Always returning NULL HERE****
        Toast.makeText(getBaseContext(),"location returning null",Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    list = new ArrayList<>();
    recentAdapter = new RecentAdapter(this, list);

    recyclerView = (RecyclerView) findViewById(R.id.parkingRecyclerView);
    linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(recentAdapter);

    setUpDrawer();
    init();
}


private void setUpDrawer() {
/*
    final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName("Home");
*/

    final ProfileDrawerItem profile1 = new ProfileDrawerItem().withName("Najeeb Pasha").withEmail("Najeeb@gmail.com");

    final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withName("Search By Location");
    final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Your Profile");
    final PrimaryDrawerItem logOut = new PrimaryDrawerItem().withName("Log Out");
    final PrimaryDrawerItem gps = new PrimaryDrawerItem().withName("GPS");

    AccountHeader headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                @Override
                public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                    startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
                    return false;
                }
            })
            .withCompactStyle(true)
            .withHeaderBackground(R.color.drawer1)
            .withCloseDrawerOnProfileListClick(true)
            .withSelectionListEnabled(false)
            .withTranslucentStatusBar(true)
            .addProfiles(profile1)
            .build();

    result = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withSelectedItem(-1)
            .withRootView(R.id.drawer_container)
            .withDisplayBelowStatusBar(false)
            .withActionBarDrawerToggleAnimated(true)
            .withCloseOnClick(true)
            .withAccountHeader(headerResult)
            .addDrawerItems(
                    item1,
                    profile,
                    logOut,
                    gps,

                    new SectionDrawerItem().withName("Others")
            )
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem == item1) {
                        startActivity(new Intent(getApplicationContext(), MapsActivity.class)
                                .putExtra("url", Constants.getPlaceUrl(lat,lng)));
                    } else if (drawerItem == logOut) {
                        logOut();
                    } else if (drawerItem == profile) {
                        startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
                    }else if (drawerItem == gps) {
                        startActivity(new Intent(getApplicationContext(), GpsActivity.class));
                    }
                    return false;
                }


            })
            .build();

}

private void logOut() {
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.apply();

    SharedPreferences.Editor editor1 = sharedPreferences1.edit();
    editor1.clear();
    editor1.apply();

    recreate();
    Intent intent = new Intent(MainActivity.this, SignInActivity.class);
    MainActivity.this.startActivity(intent);

}


public void init() {
    new Load().execute();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}


@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finishAffinity();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

private class Load extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        dialog.show();

    }

    protected Void doInBackground(Void... params) {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        System.out.println(Constants.getPlaceUrl(lat,lng));

        Request request = new Request.Builder()
                /*.url("http://192.168.0.101/parking/place.php?lat=17.308531&lng=78.5364463")*/
                .url(Constants.getPlaceUrl(lat,lng))
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();

            System.out.println(responseData);

            JSONArray jsonArray = new JSONArray(responseData);


            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);

                RecentData data = new RecentData(
                        jsonObject.getString("name"),
                        jsonObject.getString("address"),
                        jsonObject.getString("lat"),
                        jsonObject.getString("lng"),
                        jsonObject.getString("distance"),
                        jsonObject.getString("filled"),
                        jsonObject.getString("total"),
                        jsonObject.getString("service"));

                list.add(data);
            }

        } catch (JSONException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void aVoid) {
        dialog.hide();
        recentAdapter.notifyDataSetChanged();
    }
}
包com.parkaspot.najeeb.project;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.concurrent.TimeUnit;
公共类MainActivity扩展了AppCompatActivity{
最后一个字符串TAG=“MAIN”;
数组列表;
接收器适配器接收器适配器;
直线布局经理直线布局经理;
回收视图回收视图;
抽屉结果;
工具栏;
双lat,液化天然气;
位置;
SharedReferences SharedReferences,SharedReferences 1;
字符串名称、密码;
SpotsDialog对话框;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog=newspotsDialog(这是“加载…”,R.style.load);
SharedReferences=GetSharedReferences(“登录”,Context.MODE\u PRIVATE);
sharedPreferences1=getSharedPreferences(“userDetails”,Context.MODE\u PRIVATE);
LocationManager LocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
boolean networkEnabled=locationManager.isProviderEnabled(locationManager.GPS\U提供程序);
if(可联网){
Log.d(标记“网络已启用”);//显示成功
如果((ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予)&(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
Log.d(标记“permission******************grated”);//此日志标记从未出现在logcat中
回来
}
location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序);
Log.d(标记“位置已初始化”);//显示成功
}
如果(位置!=null){
lat=位置。getLatitude();
lng=location.getLongitude();
Log.d(标记“获取latlng值”);//**从不显示
}else{/*******始终在此处返回NULL****
Toast.makeText(getBaseContext(),“location returning null”,Toast.LENGTH_LONG.show();
意向意向=新意向(设置、动作、位置、来源、设置);
星触觉(意向);
}
toolbar=(toolbar)findviewbyd(R.id.toolbar);
设置支持操作栏(工具栏);
列表=新的ArrayList();
recentAdapter=新的recentAdapter(此,列表);
recyclerView=(recyclerView)findViewById(R.id.parkingRecyclerView);
linearLayoutManager=新的linearLayoutManager(此);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recentAdapter);
setUpDrawer();
init();
}
私有void setUpDrawer(){
/*
final PrimaryDrainerItem1=新PrimaryDrainerItem()。带标识符(1)。带名称(“主”);
*/
final ProfileDrawerItem profile1=新ProfileDrawerItem()。带有名称(“Najeeb Pasha”)。带有电子邮件(“Najeeb@gmail.com");
final PrimaryDrainerItem1=新PrimaryDrainerItem().withName(“按位置搜索”);
final PrimaryDrainerItem profile=新PrimaryDrainerItem()。带有名称(“您的配置文件”);
最终PrimaryDrainerItem注销=新PrimaryDrainerItem()。名称为(“注销”);
最终PrimaryDrainerItem gps=新PrimaryDrainerItem(),名称为(“gps”);
AccountHeader headerResult=新的AccountHeaderBuilder()
.withActivity(本)
.withOnAccountHeaderListener(新的AccountHeader.OnAccountHeaderListener(){
@凌驾
公共布尔值onProfileChanged(视图、IProfile配置文件、布尔值当前){
startActivity(新意图(getApplicationContext(),ProfileActivity.class));
返回false;
}
})
.withCompactStyle(真)
.带床头背景(右颜色抽屉1)
.withCloseDrawerOnProfileListClick(true)
.withSelectionListEnabled(false)
.带半透明状态栏(true)
.addProfiles(profile1)
.build();
结果=新抽屉生成器()
.withActivity(本)
.withToolbar(工具栏)
.with selecteditem(-1)
.带根视图(R.id.抽屉\ U容器)
.withDisplayBelowStatusBar(假)
.withActionBarDrawerToggleAnimated(真)
.withCloseOnClick(真)
.withAccountHeader(headerResult)
艾德瑞特姆斯先生(
项目1,
轮廓
注销,
全球定位系统,
名称为(“其他”)的新节DrawerItem()
)
.withOnDrawerItemClickListener(新抽屉.OnDrawerItemClickListener(){
@凌驾
公共布尔onItemClick(视图、整型位置、IDRAWRITEM DREAWRITEM){
如果(受票人姓名==项目1){
startActivity(新意图(getApplicationContext(),MapsActivity.class)
.putExtra(“url”,Constants.getPlaceUrl(lat,lng));
}else if(drawerItem==注销){
注销();
}else if(drawerItem==配置文件){
startActivity(新意图(getApplicationContext(),ProfileActivity.class));
}否则,如果(M==gps){
startActivity(新意图(getApplicationContext(),GpsActivity.class));
}
返回false;
}
})
.build();
}
私有无效注销(){
SharedReferences.Editor=SharedReferences.edit();
编辑器.clear();
editor.apply();
SharedReferences.Editor editor1=SharedReferences 1.edit();
editor1.clear();
editor1.apply();
重新创建();
意向意向=新意向(MainActivity.this,SignInActivity.class);
MainActivity.this.startActivity(意图);
}
公共void init(){
氖
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, new LocationListener(){  
    @Override 
    public void onLocationChanged(Location location){
        Log.d("LOCATION", location.toString());
    }
});