使用 ConnectivityManager 和 NetworkInfo 避免 NullPointerException
在我的应用程序中,我通过使用 PHP 脚本查询数据库。目前,应用程序一出现在屏幕上,它就会立即获取信息。但是,如果您没有互联网连接,它会返回 NullPointerException,因为它没有获取任何数据。此后,我使用 ConnectivityManager 和 NetworkInfo 更新了我的代码,如果用户未连接到其网络或 WiFi,则会显示 toast。问题是它跳过了这一点,只是像平常一样执行其余的代码。
public class Shc_BalloonSat_Activity extends Activity
{
int historyCountFromUser;
httpAPI api;
mapAPI map;
DecimalFormat df = new DecimalFormat("##.#####");
DecimalFormat decimalf = new DecimalFormat("##.######");
SharedPreferences pref;
Editor prefEditor;
String lastpacketsPHP;
// User to determine how many packet the user would like to see.
int userDefinedCount = 5;
/*
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 0);
prefEditor = pref.edit();
prefEditor.putString(lastpacketsPHP, "/* PHP file url goes here */");
prefEditor.commit();
if(!isNetworkConnected(this))
{
Toast.makeText(this, "Please connect to the internet to access the full functionality of this app.", Toast.LENGTH_LONG).show();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
try
{
returned = api.getData();
}
catch (Exception e)
{
e.printStackTrace();
}
TextView infoTV = (TextView)this.findViewById(R.id.info);
infoTV.setText(returned);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
public boolean isNetworkConnected(Context context)
{
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isAvailable() && connectionManager.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
有什么想法我做错了吗?
更新(LogCat错误消息):
02-19 13:55:19.450: E/log_tag(443): Error in HTTP connection: java.net.UnknownHostException: Host is unresolved: space.uah.edu:80
02-19 13:55:19.450: E/log_tag(443): Error converting result: java.lang.NullPointerException
02-19 13:55:19.450: E/log_tag(443): Error in HTTP connection: java.net.UnknownHostException: Host is unresolved: space.uah.edu:80
02-19 13:55:19.450: E/log_tag(443): Error converting result: java.lang.NullPointerException
02-19 13:55:19.450: E/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception
02-19 13:55:19.473: E/AndroidRuntime(443): java.lang.RuntimeException: Unable to start activity ComponentInfo{shc_BalloonSat.namespace/shc_BalloonSat.namespace.Shc_BalloonSat_Activity}: java.lang.NullPointerException: println needs a message
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.os.Looper.loop(Looper.java:123)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.main(ActivityThread.java:4363)
02-19 13:55:19.473: E/AndroidRuntime(443): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): at java.lang.reflect.Method.invoke(Method.java:521)
02-19 13:55:19.473: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
02-19 13:55:19.473: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
02-19 13:55:19.473: E/AndroidRuntime(443): at dalvik.system.NativeStart.main(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): Caused by: java.lang.NullPointerException: println needs a message
02-19 13:55:19.473: E/AndroidRuntime(443): at android.util.Log.println(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.util.Log.e(Log.java:208)
02-19 13:55:19.473: E/AndroidRuntime(443): at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.assignInfoToInfoTextView(Shc_BalloonSat_Activity.java:173)
02-19 13:55:19.473: E/AndroidRuntime(443): at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.onCreate(Shc_BalloonSat_Activity.java:75)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
02-19 13:55 :19.473: E/AndroidRuntime(443): ... 11 more
In my application I'm querying a database via the use of a PHP script. Currently, it gets the information as soon as the app comes up on the screen. However, if you don't have an internet connection it returns a NullPointerException because it's not getting any data. I've since updated my code with a ConnectivityManager and NetworkInfo that displays a toast if the user is not connected to either their network or to a WiFi. The problem is it's skipping this and just executing the rest of the code like normal.
public class Shc_BalloonSat_Activity extends Activity
{
int historyCountFromUser;
httpAPI api;
mapAPI map;
DecimalFormat df = new DecimalFormat("##.#####");
DecimalFormat decimalf = new DecimalFormat("##.######");
SharedPreferences pref;
Editor prefEditor;
String lastpacketsPHP;
// User to determine how many packet the user would like to see.
int userDefinedCount = 5;
/*
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 0);
prefEditor = pref.edit();
prefEditor.putString(lastpacketsPHP, "/* PHP file url goes here */");
prefEditor.commit();
if(!isNetworkConnected(this))
{
Toast.makeText(this, "Please connect to the internet to access the full functionality of this app.", Toast.LENGTH_LONG).show();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
try
{
returned = api.getData();
}
catch (Exception e)
{
e.printStackTrace();
}
TextView infoTV = (TextView)this.findViewById(R.id.info);
infoTV.setText(returned);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
public boolean isNetworkConnected(Context context)
{
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isAvailable() && connectionManager.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
Any ideas what I'm doing wrong?
Update (LogCat error message):
02-19 13:55:19.450: E/log_tag(443): Error in HTTP connection: java.net.UnknownHostException: Host is unresolved: space.uah.edu:80
02-19 13:55:19.450: E/log_tag(443): Error converting result: java.lang.NullPointerException
02-19 13:55:19.450: E/log_tag(443): Error in HTTP connection: java.net.UnknownHostException: Host is unresolved: space.uah.edu:80
02-19 13:55:19.450: E/log_tag(443): Error converting result: java.lang.NullPointerException
02-19 13:55:19.450: E/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception
02-19 13:55:19.473: E/AndroidRuntime(443): java.lang.RuntimeException: Unable to start activity ComponentInfo{shc_BalloonSat.namespace/shc_BalloonSat.namespace.Shc_BalloonSat_Activity}: java.lang.NullPointerException: println needs a message
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.os.Looper.loop(Looper.java:123)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.main(ActivityThread.java:4363)
02-19 13:55:19.473: E/AndroidRuntime(443): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): at java.lang.reflect.Method.invoke(Method.java:521)
02-19 13:55:19.473: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
02-19 13:55:19.473: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
02-19 13:55:19.473: E/AndroidRuntime(443): at dalvik.system.NativeStart.main(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): Caused by: java.lang.NullPointerException: println needs a message
02-19 13:55:19.473: E/AndroidRuntime(443): at android.util.Log.println(Native Method)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.util.Log.e(Log.java:208)
02-19 13:55:19.473: E/AndroidRuntime(443): at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.assignInfoToInfoTextView(Shc_BalloonSat_Activity.java:173)
02-19 13:55:19.473: E/AndroidRuntime(443): at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.onCreate(Shc_BalloonSat_Activity.java:75)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-19 13:55:19.473: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
02-19 13:55 :19.473: E/AndroidRuntime(443): ... 11 more
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的连接检查逻辑工作正常,请将其设置为 if/else。如果未连接则显示 toast,否则继续逻辑。
Assuming your connection check logic working fine, make it as, if/else. If not connected show toast, else continue with logic.