Вопрос

I have developed an android application which required Internet access.

The app works fine when the internet connection is on, but the app gets stopped with an alert "Unfortunately App Has Been Stopped", if my internet connection is switched off.

How to show alert to the user to check his internet connection and prevent the app not to close automatically.

i have searched for solutions and modified my code to show alert, even if the alert is popping up, the app gets closed with the "Unfortunately App Has Been Stopped" pops over my alert.

I hope there is a way to solve this issue, Please someone help me out.

Here is my code.

MyActivity.Java

 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.List;

 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
 import org.apache.http.NameValuePair;
 import org.apache.http.StatusLine;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;

 import android.app.Activity;
 import android.app.AlarmManager;
 import android.app.AlertDialog;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.location.LocationManager;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.provider.Settings;
 import android.util.Log;
 import android.view.Gravity;
 import android.view.Menu;
 import android.view.View;
 import android.widget.CompoundButton;
 import android.widget.EditText;
 import android.widget.Switch;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener{
     private SharedPreferences pref;
     Switch s1;
Switch s2;
TextView t4;
TextView t5;
PendingIntent pintent;
String androidId;
EditText eText;
AlertDialog alertDialog;
public int count=1;
AlertDialog alert;
// flag for Internet connection status
Boolean isInternetPresent = false;

// Connection detector class
ConnectionDetector cd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    isInternetPresent = false;

    try
    {
      cd = new ConnectionDetector(getApplicationContext());

      isInternetPresent = cd.isConnectingToInternet();
    }
    catch(Exception e)
    { 
       Log.e("Main Activity", "Error occurred while detecting Internet Connection !, Error = "+e.toString());
       e.printStackTrace();
    }
    // check for Internet status
    if (isInternetPresent) {
        // Internet Connection is Present
        // make HTTP requests
     //   showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",
       //         "You have internet connection", true);
    } else {
        // Internet connection is not present
        // Ask user to connect to Internet
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //AlertDialog alert1 = null;
        builder.setMessage("No Internet Connection")
                .setTitle("Internet Connection")
               .setCancelable(true)
               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                     //Uncimment the below line, if you want your app to be closed when Ok is pressed.
                    //    MainActivity.this.finish(); ->This line is closing your app.
                     if(alert!=null) alert.dismiss();
                   }
               })
               .setNegativeButton("Settings", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                   }
               });

        alert = builder.create();
        alert.show();
    }


    String androidId = Settings.Secure.getString(getContentResolver(), 
            Settings.Secure.ANDROID_ID);
    eText = (EditText) findViewById(R.id.editText1);
    eText.setGravity(Gravity.CENTER_HORIZONTAL);
    eText.setText(androidId);
    pintent = PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0);
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service
      .isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!enabled) {
      Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      startActivity(intent1);
    } 
    s1 = (Switch) findViewById(R.id.switch1);
    if(s1 != null) {
        s1.setOnCheckedChangeListener(this);
    }
    s2 = (Switch) findViewById(R.id.switch2);
    if(s2 != null) {
        s2.setOnCheckedChangeListener(this);
    }
    t4 = (TextView) findViewById(R.id.textView4);
    t5 = (TextView) findViewById(R.id.textView5);
    loadPreferences();
    try {
        new Myuuid().execute(androidId);
    }
    catch(Exception e) {
            e.printStackTrace();
        }

}


protected void onStart(View v) {

    Toast.makeText(this, "on Start", Toast.LENGTH_SHORT).show();


}

private void loadPreferences() {
    // TODO Auto-generated method stub
    pref = getApplicationContext().getSharedPreferences(
            "My_pref", MODE_PRIVATE);
    boolean get1 = pref.getBoolean("switch_value1", false);
    boolean get2 = pref.getBoolean("switch_value2", false);
    s1.setChecked(get1);
    s2.setChecked(get2);
}

public void onResume(View v) {

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void findButton(View v) {
    boolean status = s2.isChecked();
    pref = getApplicationContext().getSharedPreferences(
            "My_pref", MODE_PRIVATE);
    Editor editor = pref.edit();
    editor.putBoolean("switch_value2",status);
    editor.commit();
    boolean get = pref.getBoolean("switch_value1",false );
}
@Override
public void onCheckedChanged(CompoundButton buttonview, boolean isChecked) {
    // TODO Auto-generated method stub

    switch(buttonview.getId()) {
    case R.id.switch1: 
        pref = getApplicationContext().getSharedPreferences(
                "My_pref", MODE_PRIVATE);
        Editor editor = pref.edit();
        editor.putBoolean("switch_value1",isChecked);
        editor.commit();
        boolean get = pref.getBoolean("switch_value1",false );
        if(isChecked) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 10);

            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            //for 30 mint 60*60*1000
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                         30*1000, pintent);
            View view = this.getWindow().getDecorView();
            Intent intent1 = new Intent(this, MyService.class);
            startService(intent1);
            boolean state = isChecked;
            t4.setText("Tracking");
            t4.setTextColor(-65536);
        }if(!isChecked) {               
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pintent);
            t4.setText("Stopped Tracking");
            t4.setTextColor(-16711936);
            stopService(new Intent(MainActivity.this,MyService.class));             
        }
        break;

    case R.id.switch2:
        if(isChecked) {
            t5.setText("Cab is Busy");
            t5.setTextColor(-65536);
        }
        if(!isChecked) {
            t5.setText("Cab is vacant");
            t5.setTextColor(-16711936);
        }

    }
}

private class Myuuid extends AsyncTask<String, Integer, String>{

    @Override
    protected String doInBackground(String... params) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        HttpPost httppost = new HttpPost("http://nuappz.com/taxi/lib/api/checkuuid.inc.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            String androidId = Settings.Secure.getString(getContentResolver(), 
                    Settings.Secure.ANDROID_ID);
            nameValuePairs.add(new BasicNameValuePair("uuid", androidId));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            response = httpclient.execute(httppost);
            StatusLine statusLine = response.getStatusLine();
            Log.d("Tes", String.valueOf(statusLine));
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
                //Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
                //Log.d("Tooo", responseString);
            } else{
                //Closes the connection.
                //String responseBody = EntityUtils.toString(response.getEntity());
                //response.getEntity().getContent().close();
                //Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }


    protected void onPostExecute(String result){
        //super.onPostExecute(result);
        //pb.setVisibility(View.GONE);

        Toast.makeText(getApplicationContext(), "uuid sent", Toast.LENGTH_SHORT).show();
        Toast.makeText(MainActivity.this, " "+ result, Toast.LENGTH_SHORT).show();
        Log.d("one", result);

        if(result.equals("false")) {
            Log.d("one", result);
            String androidId = Settings.Secure.getString(getContentResolver(), 
                    Settings.Secure.ANDROID_ID);
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Your Device UUID is "+androidId+" Complete your Registration with Admin")
                    .setTitle("Register Your UUID")
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                       }
                   });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }

My Error Log:

01-02 02:04:50.400: E/AndroidRuntime(4677): FATAL EXCEPTION: main
01-02 02:04:50.400: E/AndroidRuntime(4677): java.lang.NullPointerException: println needs a message
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.util.Log.println_native(Native Method)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.util.Log.d(Log.java:155)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at com.nuappz.cabtracking.MainActivity$Myuuid.onPostExecute(MainActivity.java:288)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at com.nuappz.cabtracking.MainActivity$Myuuid.onPostExecute(MainActivity.java:1)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.os.AsyncTask.finish(AsyncTask.java:602)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.os.Looper.loop(Looper.java:137)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at android.app.ActivityThread.main(ActivityThread.java:4517)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at java.lang.reflect.Method.invokeNative(Native Method)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at java.lang.reflect.Method.invoke(Method.java:511)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
01-02 02:04:50.400: E/AndroidRuntime(4677):     at dalvik.system.NativeStart.main(Native Method)

Thanks In advance.

Это было полезно?

Решение

Your code failed here:

Log.d("one", result);

Because result is null. Check this variable at the beginning of method onPostExecute() and return if it's null.

EDITED:

protected void onPostExecute(String result) {
    if (result == null) {
        Log.w("one", "result is null");
        return;
    }

    // your code
}

Другие советы

Your AlertDialog is non-cancelable and you left no choice for the user, if the Network connection is not present, other than pressing ok and getting the Application closed.

Please modify your code like this:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

isInternetPresent = false;

try
{
  cd = new ConnectionDetector(getApplicationContext());

  isInternetPresent = cd.isConnectingToInternet();
}
catch(Exception e)
{ 
   Log.e("Main Activity", "Error occurred while detecting Internet Connection !, Error = "+e.toString());
   e.printStackTrace();
}
// check for Internet status
if (isInternetPresent) {
    // Internet Connection is Present
    // make HTTP requests
 //   showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",
   //         "You have internet connection", true);
} else {
    // Internet connection is not present
    // Ask user to connect to Internet
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    AlertDialog alert = null;
    builder.setMessage("No Internet Connection")
            .setTitle("Internet Connection")
           .setCancelable(true)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                 //Uncimment the below line, if you want your app to be closed when Ok is pressed.
                //    MainActivity.this.finish(); ->This line is closing your app.
                 if(alert!=null) alert.dismiss();
               }
           });
           .setNegativeButton("Settings", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
               }
           });

    alert = builder.create();
    alert.show();
}

I hope this helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top