- Forum-Beiträge: 2
12.06.2018, 19:30:25 via Website
12.06.2018 19:30:25 via Website
Wie kann ich einen loading Dialog anzeigen, solange die gps daten abgefragt werden?
— geändert am 13.06.2018, 03:21:01 durch Moderator
12.06.2018, 19:30:25 via Website
12.06.2018 19:30:25 via Website
Wie kann ich einen loading Dialog anzeigen, solange die gps daten abgefragt werden?
— geändert am 13.06.2018, 03:21:01 durch Moderator
12.06.2018, 19:33:11 via Website
12.06.2018 19:33:11 via Website
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
Activity activity;
android.support.v7.widget.Toolbar toolbar;
private TextView temperatureTextView, conditionTextView, lastUpdateTextView, yahooWeatherTextView;
private EditText locationEditText;
private ImageView weatherImageView;
private ImageButton searchImageButton;
Switch gpsSwitch = null;
private ProgressDialog loadingDialog = new ProgressDialog(this);
private LocationManager locationManager;
private LocationListener locationListener;
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//findViewById
locationEditText = findViewById(R.id.locationEditText);
searchImageButton = findViewById(R.id.searchImageButton);
yahooWeatherTextView = findViewById(R.id.yahooWeatherTextView);
weatherImageView = findViewById(R.id.weatherImageView);
temperatureTextView = findViewById(R.id.temperatureTextView);
conditionTextView = findViewById(R.id.conditionTextView);
lastUpdateTextView = findViewById(R.id.lastUpdateTextView);
this.activity = this;
//Toolbar
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Weather App with Yahoo API");
getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_dhbw));
//setVisibility
locationEditText.setVisibility(View.INVISIBLE);
searchImageButton.setVisibility(View.INVISIBLE);
//function Switch
gpsSwitch = findViewById(R.id.gpsSwitch);
gpsSwitch.setOnCheckedChangeListener(this);
//function of ImageButton
searchImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String EditTextCity = locationEditText.getText().toString();
locationEditText.setText("");
getWeatherInfoEditText(EditTextCity);
}
});
//get location
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
//when there is a new location
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
String gpsCity = addresses.get(0).getLocality();
getWeatherInfoGPS(gpsCity);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
//check if GPS is disabled
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
//start message allow GPS
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
}, 10);
}
} else {
getlocation();
}
}
//if Switch true&false
@Override
public void onCheckedChanged(CompoundButton gpsSwitch, boolean isChecked) {
if (isChecked) {
locationEditText.setVisibility(View.INVISIBLE);
searchImageButton.setVisibility(View.INVISIBLE);
//getWeatherInfoGPS(String gpsCity);
} else {
locationEditText.setVisibility(View.VISIBLE);
searchImageButton.setVisibility(View.VISIBLE);
}
}
//get WeatherInfo for GPS
public void getWeatherInfoGPS(String gpsCity) {
try {
loadingDialog = new ProgressDialog(this);
loadingDialog.setMessage(getString(R.string.loading));
loadingDialog.setCancelable(false);
loadingDialog.show();
new Thread() {
public void run() {
try {
sleep(1000);
} catch (Exception ignored) {
}
loadingDialog.dismiss();
}
}.start();
requestQueue = Volley.newRequestQueue(this);
url = url.replaceAll(" ", "%20");
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@SuppressLint("SetTextI18n")
@Override
public void onResponse(JSONObject response) {
try {
//Yahoo! Weather for city, region, country
String header = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getString("description");
//weather image code
int imagecode = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getInt("code");
//temperature
int temperature = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getInt("temp");
//condition
String condition = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getString("text");
//last update
String lastupdate = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getString("lastBuildDate");
//setTitle
yahooWeatherTextView.setText(header);
//setImage
int WeatherImageCode = getResources().getIdentifier("dhbw.weatherappwithyahooapi:drawable/icon_" + imagecode, null, null);
weatherImageView.setImageResource(WeatherImageCode);
//setTemperature
temperatureTextView.setText(temperature + " °C");
//setCondition
conditionTextView.setText(condition);
//setLastUpdate
lastUpdateTextView.setText("last update: " + lastupdate);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity, "Sorry, weather is currently not available! \uD83D\uDE15", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(request);
} catch (Exception ignored) {
}
}
//get WeatherInfo for EditText
public void getWeatherInfoEditText(String EditTextCity) {
try {
loadingDialog = new ProgressDialog(this);
loadingDialog.setMessage(getString(R.string.loading));
loadingDialog.setCancelable(false);
loadingDialog.show();
new Thread() {
public void run() {
try {
sleep(1000);
} catch (Exception ignored) {
}
loadingDialog.dismiss();
}
}.start();
requestQueue = Volley.newRequestQueue(this);
url = url.replaceAll(" ", "%20");
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@SuppressLint("SetTextI18n")
@Override
public void onResponse(JSONObject response) {
try {
//Yahoo! Weather for city, region, country
String header = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getString("description");
//weather image code
int imagecode = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getInt("code");
//temperature
int temperature = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getInt("temp");
//condition
String condition = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONObject("condition").getString("text");
//last update
String lastupdate = response.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getString("lastBuildDate");
//setTitle
yahooWeatherTextView.setText(header);
//setImage
int WeatherImageCode = getResources().getIdentifier("dhbw.weatherappwithyahooapi:drawable/icon_" + imagecode, null, null);
weatherImageView.setImageResource(WeatherImageCode);
//setTemperature
temperatureTextView.setText(temperature + " °C");
//setCondition
conditionTextView.setText(condition);
//setLastUpdate
lastUpdateTextView.setText("last update: " + lastupdate);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity, "Sorry, weather is currently not available! \uD83D\uDE15", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(request);
} catch (Exception ignored) {
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
getlocation();
}
}
//get location
private void getlocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, null);
}
//when app opan again, load new gps data
@Override
protected void onStop() {
super.onStop();
finish();
}
}
13.06.2018, 03:22:35 via App
13.06.2018 03:22:35 via App
Hallo madu31,
ohne deine. Code gelesen zu haben:
ProgressDialog öffnen wenn du den GPS request sendest und schließen wenn Daten verfügbar.
Ansonsten eine. Tipp: Steukturiere deinen Code in verschiedene Klassen. Wird dann deutlich übersichtlicher...
LG Pascal //It's not a bug, it's a feature.
Empfohlener redaktioneller Inhalt
Mit Deiner Zustimmung wird hier ein externer Inhalt geladen.
Mit Klick auf den oben stehenden Button erklärst Du Dich damit einverstanden, dass Dir externe Inhalte angezeigt werden dürfen. Dabei können personenbezogene Daten an Drittanbieter übermittelt werden. Mehr Infos dazu findest Du in unserer Datenschutzerklärung.