我无法获取我的位置,我不知道为什么我作为iam的新手向我尝试了google上的所有内容
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();
}
}
这个总是返回null的内容,请从头开始帮助我,我不知道如何解决它,而且我对android非常非常新,这是我的大学家庭作业项目,即使使用gps或net provider也无法获得。 **请仅在这件事上帮助我,然后我的项目就会完成。
将位置返回为Null
我是新手;
请更改时回复我整个代码,request.request(Noob) 非常感谢你先生
答案 0 :(得分:0)
要获取位置,您需要使用位置管理器上的方法requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
来请求位置更新。
创建一个将打印数据的侦听器,例如:
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, new LocationListener(){
@Override
public void onLocationChanged(Location location){
Log.d("LOCATION", location.toString());
}
});
这将要求位置管理器每1000毫秒(1s)为我提供一次,如果我从上一个位置移走了10m,则提供了一个新位置。