在Android中未使用上下文显示进度对话框

时间:2018-07-15 23:27:39

标签: android android-studio progressdialog

我有一个dialog fragment Java类,它显示一个对话框,它工作得很好,但是唯一的问题是在等待响应时进度对话框没有显示,这与对话框不同,该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();
    }
}

1 个答案:

答案 0 :(得分:1)

  

在Android中,只有主线程/ UI线程可以更新UI

其他线程无法更新UI,但您的代码试图在导致问题的辅助线程中运行异步任务(该线程相应地在UI上/在UI上运行!)。

解决方案:在UI线程上执行Asynch任务

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