Android:应用程序想要启动时检查Internet连接但它崩溃

时间:2015-11-20 09:23:55

标签: android xml-parsing connection

在我的应用程序中,我从Xml加载数据并且它已成功加载但当我关闭我的Internet连接时它只是说Appname崩溃..

我在Stackoverflow中检查所有都是Sugessting使用ConnectivityManager,但即使我的应用程序崩溃我不知道为什么它发生了plz给出想法和Sugesstion来克服它

我需要的是当我的应用程序启动时它想要检查Internet连接是否可用我的列表视图将显示Else它说连接到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));
        }


    }

logcat的:

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)

2 个答案:

答案 0 :(得分:2)

是的,因为当您关闭互联网连接时,它会引发异常,因此它会移动到catch块,最后返回@RunWith(PowerMockRunner.class) @PrepareForTest({Box.class,Red.class}) class Test{ // your testing code } 变量,该变量为null 这就是你得到空指针异常的原因。

使用互联网连接条件:

xml

答案 1 :(得分: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();