安卓:应用在启动时想要检查网络连接,但是它崩溃了。

3
在我的应用程序中,我从XML加载数据并成功加载,但是当我关闭互联网连接时,它会简单地说应用程序崩溃。
我在Stackoverflow上检查了所有建议使用ConnectivityManager,但即使我的应用程序崩溃,我也不知道为什么会发生这种情况,请给出想法和建议以克服它。
我需要的是,当我的应用程序启动时,它要检查Internet连接是否可用,如果可用,则显示我的ListView,否则它会说连接到Internet并重试。
这是我的代码:
public class MainActivity extends AppCompatActivity {
    // All static variables
    static final String URL1 = "http://my_server.com/tamil";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_LINK = "link";
    URL url;
    URLConnection urlConnection;
    //Context context;
    ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        isNetworkAvailable(this);

        listview = (ListView) findViewById(R.id.list);

        new GetData().execute();


    }
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    Log.w("INTERNET:",String.valueOf(i));
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.w("INTERNET:", "connected!");
                        return true;
                    }
                }
            }
        }
        return false;
    }

    class GetData extends AsyncTask<String, String, String> {
        String xml;

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

            try {
                url = new URL(URL1);

                urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader isw = new InputStreamReader(in);

                BufferedReader br = new BufferedReader(isw);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();

                xml = sb.toString();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return xml;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {

                DocumentBuilder db = dbf.newDocumentBuilder();

                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);


                NodeList nl = doc.getElementsByTagName(KEY_ITEM);
                for (int i = 0; i < nl.getLength(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    Log.e("TAg1", getValue(e, KEY_TITLE));
                    //Log.e("TAg2", getValue(e, KEY_LINK));
                    map.put(KEY_TITLE, getValue(e, KEY_TITLE));
                    map.put(KEY_LINK, getValue(e, KEY_LINK));
                    menuItems.add(map);
                }


            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());

            }

            ListAdapter adapter = new SimpleAdapter(getApplicationContext(), menuItems,
                    R.layout.list_item,
                    new String[]{KEY_TITLE, KEY_LINK}, new int[]{
                    R.id.name});
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
            });

        }

        public final String getElementValue(Node elem) {
            Node child;
            if (elem != null) {
                if (elem.hasChildNodes()) {
                    for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
                        if (child.getNodeType() == Node.TEXT_NODE) {
                            return child.getNodeValue();
                        }
                    }
                }
            }
            return "";
        }

        public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }


    }

日志记录:

c/ussrs/a/studio1.3/config/options/ java.lang.NullPointerException
            at java.io.StringReader.<init>(StringReader.java:47)
            at com.example.a.ro.MainActivity$GetData.onPostExecute(MainActivity.java:132)
            at com.example.a.ro.MainActivity$GetData.onPostExecute(MainActivity.java:86)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5641)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
            at dalvik.system.NativeStart.main(Native Method)

1
MainActivity.java:132 是哪一行代码? - ρяσѕρєя K
@ρяσѕρєяK 他会得到空的 xml 变量,因为它没有被初始化。 - Ravi
如果没有网络连接,该应用程序会提示请连接到互联网。@ρяσѕρєяK - vasanth
@vasanth 看看我的答案,它会解决你的问题。 - Ravi
@RaviRupareliya 是的,我的应用程序没有崩溃,但是如果网络不可用,我想显示错误消息,例如“连接到互联网”。 - vasanth
显示剩余4条评论
2个回答

2

是的,因为当您关闭互联网连接时,它会引发异常,因此它将移动到catch块,最后返回xml变量,该变量为null。这就是您收到空指针异常的原因。

使用互联网连接条件:

if(isNetworkAvailable(this))
    new GetData().execute();
else
    //no internet connection, show your message here

谢谢,但我想在启动时设置错误消息,当网络未连接时显示“连接到互联网”@RaviRupareliya - vasanth
是的,请检查我的代码,在else条件中,您可以显示您的消息。 - Ravi

0
请在你的AppManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

使用此方法来检查连接。
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}

并设置

String xml;

String xml = "error";

并且

new GetData().execute();

if(isNetworkAvailable())
new GetData().execute();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接