如何在android中的另一个类中创建警报对话框

时间:2017-09-28 11:13:01

标签: java android android-alertdialog

我正在尝试在android中的另一个类中创建一个警告对话框。这是一个从另一个类传递参数的类。这是获取场所的gps位置的Set_Location类,这些值将传递给BackgroundWorker类。

SET_LOCATION CLASS:

public class Set_Location extends AppCompatActivity {
private ImageButton imgbutton;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_set__location);
    imgbutton = (ImageButton) findViewById(R.id.PanicBtn);
    textView = (TextView) findViewById(R.id.panictxt);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            String lat= String.valueOf(location.getLatitude());
            String lon= String.valueOf(location.getLongitude());
            String type="location";
            textView.append(" \n "+lat+", "+lon);
            BackgroundWorker back = new BackgroundWorker(this);
            back.execute(type,lat,lon);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    };

    configureButton();
}

private void configureButton() {
    imgbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            locationManager.requestLocationUpdates("gps",5000,0,locationListener);


        }
    });
}

}

这里是BACKGROUND_WORKER CLASS:

public class BackgroundWorker extends AsyncTask <String, Void, String>{
AlertDialog alertDialog;
Context ctx;
LocationListener locationListener;
BackgroundWorker(Context ctx){
    this.ctx = ctx;
}

public BackgroundWorker(LocationListener locationListener) {
    this.locationListener = locationListener;
}

@Override
protected String doInBackground(String... params) {
    String type=params[0];
    String Login_Url= "http://192.168.43.254/login.php";
    String Login_after_registration_Url= "http://192.168.43.254/login2.php";
    String Register_Url= "http://192.168.43.254/register.php";
    String Register_Url2= "http://192.168.43.254/register2.php";
 if(type.equals("location")){
        try {
            String latitude=params[1];
            String longitude=params[2];


            URL url= new URL(Register_Url2);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter  = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data= URLEncoder.encode("latitude","UTF-8")+"="+URLEncoder.encode(latitude,"UTF-8")+"&"
                    +URLEncoder.encode("longitude","UTF-8")+"="+URLEncoder.encode(longitude,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line;
            while ((line=bufferedReader.readLine())!=null){
                result += line;
            }
            bufferedReader.close();;
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
@Override
protected void onPreExecute() {
    alertDialog= new AlertDialog.Builder(ctx).create();
    alertDialog.setTitle(" Status");
}

@Override
protected void onPostExecute(String result) {
    if(result == null)
    {
        Toast.makeText(ctx, "connection error please try again", Toast.LENGTH_LONG).show();
    }
     else if(result.contains("Registration")) // msg you get from success like "Login Success"
    {


        alertDialog.setMessage(result);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Login", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent i = new Intent(ctx,Login_after_Registration.class);
                ctx.startActivity(i);
            }
        });
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }
     else if(result.contains("Login")) // msg you get from success like "Login Success"
    {
        Intent i = new Intent(ctx,Welcome.class);
        ctx.startActivity(i);
        alertDialog.setMessage(result);
        alertDialog.show();
    }
    else if(result.contains("Welcome")) // msg you get from success like "Login Success"
    {
        Intent i = new Intent(ctx,Set_Location.class);
        ctx.startActivity(i);
        alertDialog.setMessage(result);
        alertDialog.show();
    }
     else if(result.contains("Invalid")){
        alertDialog.setMessage(result);
        alertDialog.show();

    }
    else{

        alertDialog.setMessage(result);
        alertDialog.show();
    }

}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

这是我得到的错误日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
        at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
        at com.example.bensonkorir.m_ulinzi.BackgroundWorker.onPreExecute(BackgroundWorker.java:209)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
        at android.os.AsyncTask.execute(AsyncTask.java:539)
        at com.example.bensonkorir.m_ulinzi.Set_Location$1.onLocationChanged(Set_Location.java:35)
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:281)
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:210)
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:226)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

指出错误来自此处:

BackgroundWorker back = new BackgroundWorker(this);
        back.execute(type,lat,lon);

在这里:

alertDialog= new AlertDialog.Builder(ctx).create();
    alertDialog.setTitle(" Status");

任何人都可以帮我修复错误吗?

1 个答案:

答案 0 :(得分:1)

只需初始化您的BackgroundWorker变量,如下所示:

BackgroundWorker back = new BackgroundWorker(Set_Location.this);
    back.execute(type,lat,lon);