gpt4 book ai didi

java - 不幸的是,如果没有互联网访问,应用程序已停止

转载 作者:行者123 更新时间:2023-12-01 13:32:16 25 4
gpt4 key购买 nike

我开发了一个需要互联网访问的 Android 应用程序。

当互联网连接打开时,该应用程序可以正常工作,但如果我的互联网连接关闭,该应用程序就会停止,并出现“不幸的是,应用程序已停止”的警报。

如何向用户显示警报以检查其互联网连接并防止应用程序不自动关闭。

我已经搜索了解决方案并修改了我的代码以显示警报,即使弹出警报,应用程序也会关闭,并在我的警报上弹出“不幸的是应用程序已停止”。

我希望有办法解决这个问题,请有人帮助我。

这是我的代码。

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

我的错误日志:

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)

提前致谢。

最佳答案

您的代码在这里失败:

Log.d("one", result);

因为结果null。在方法 onPostExecute() 的开头检查此变量,如果它是 null,则return

编辑:

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

// your code
}

关于java - 不幸的是,如果没有互联网访问,应用程序已停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com