在 Android 中使用上下文未显示进度对话框
Progress Dialog not displaying using Context in Android
我有一个 dialog fragment
Java class 它显示了一个对话框,它工作得很好,但唯一的问题是在等待响应时 progressDialog 没有显示,这个与对话框不同,此 progressDialog 在 AsyncTask
中工作,同时从 http.
获取响应
这是我的代码:
package com.example.kapoyei.hatidtubigan.helper;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kapoyei.hatidtubigan.R;
import com.example.kapoyei.hatidtubigan.other.Http;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class AddStation extends AppCompatDialogFragment implements View.OnClickListener {
public static String jsonObject; // THIS WILL BE THE HANDLER OF JSON LATER
Button btnCreate; // GET THE BUTTON
EditText etStationName, etAddress, etContact; // GET THE INPUT TEXT
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// CREATE A DIALOG BOX
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// GET THE LAYOUT
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_addstation, null);
builder.setView(view);
builder.setCancelable(true);
// GET THE VALUES
etStationName = (EditText) view.findViewById(R.id.etStationName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etContact = (EditText) view.findViewById(R.id.etContact);
btnCreate = (Button) view.findViewById(R.id.btnCreate);
// SET CLICK LISTENER OF THE BUTTON
btnCreate.setOnClickListener(this);
return builder.create();
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
Thread stationThread = new Thread() {
@Override
public void run() {
Looper.prepare();
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
}
};
stationThread.start();
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
public class StoreStation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
private Context mContext;
public StoreStation(Context c) {
mContext = c;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mContext);
pd.setMessage("Adding station ...");
pd.setCancelable(false);
pd.show();
}
@Override
protected void onPostExecute(String result) {
pd.cancel();
getResponse(result);
}
@Override
protected String doInBackground(String... url) {
String data = "";
jsonObject = "";
try {
String link = (String) url[0];
URL getURL = new URL(link);
HttpURLConnection huc = (HttpURLConnection) getURL.openConnection();
huc.setReadTimeout(10000);
huc.setConnectTimeout(15000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.connect();
InputStream is = huc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void getResponse(String json) {
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("station");
String result = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
result = obj.getString("result");
}
if(result.equalsIgnoreCase("done")) {
Toast.makeText(mContext, "Successfully save!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("exists")) {
Toast.makeText(mContext, "Station is already exists!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, "Connection problem", Toast.LENGTH_LONG).show();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
}
In Android, only Main thread /UI thread can update UI
其他线程无法更新 UI 但您的代码正在尝试 运行 异步任务(这是一个 运行 off/on UI 相应的线程,太棒了!)在导致问题的工作线程中。
解决方案:在UI线程
上执行异步任务
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
我有一个 dialog fragment
Java class 它显示了一个对话框,它工作得很好,但唯一的问题是在等待响应时 progressDialog 没有显示,这个与对话框不同,此 progressDialog 在 AsyncTask
中工作,同时从 http.
这是我的代码:
package com.example.kapoyei.hatidtubigan.helper;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kapoyei.hatidtubigan.R;
import com.example.kapoyei.hatidtubigan.other.Http;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class AddStation extends AppCompatDialogFragment implements View.OnClickListener {
public static String jsonObject; // THIS WILL BE THE HANDLER OF JSON LATER
Button btnCreate; // GET THE BUTTON
EditText etStationName, etAddress, etContact; // GET THE INPUT TEXT
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// CREATE A DIALOG BOX
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// GET THE LAYOUT
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_addstation, null);
builder.setView(view);
builder.setCancelable(true);
// GET THE VALUES
etStationName = (EditText) view.findViewById(R.id.etStationName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etContact = (EditText) view.findViewById(R.id.etContact);
btnCreate = (Button) view.findViewById(R.id.btnCreate);
// SET CLICK LISTENER OF THE BUTTON
btnCreate.setOnClickListener(this);
return builder.create();
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
Thread stationThread = new Thread() {
@Override
public void run() {
Looper.prepare();
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
}
};
stationThread.start();
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
public class StoreStation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
private Context mContext;
public StoreStation(Context c) {
mContext = c;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mContext);
pd.setMessage("Adding station ...");
pd.setCancelable(false);
pd.show();
}
@Override
protected void onPostExecute(String result) {
pd.cancel();
getResponse(result);
}
@Override
protected String doInBackground(String... url) {
String data = "";
jsonObject = "";
try {
String link = (String) url[0];
URL getURL = new URL(link);
HttpURLConnection huc = (HttpURLConnection) getURL.openConnection();
huc.setReadTimeout(10000);
huc.setConnectTimeout(15000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.connect();
InputStream is = huc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void getResponse(String json) {
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("station");
String result = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
result = obj.getString("result");
}
if(result.equalsIgnoreCase("done")) {
Toast.makeText(mContext, "Successfully save!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("exists")) {
Toast.makeText(mContext, "Station is already exists!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, "Connection problem", Toast.LENGTH_LONG).show();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
}
In Android, only Main thread /UI thread can update UI
其他线程无法更新 UI 但您的代码正在尝试 运行 异步任务(这是一个 运行 off/on UI 相应的线程,太棒了!)在导致问题的工作线程中。
解决方案:在UI线程
上执行异步任务public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}