package info.testing;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
public class SoupActivity extends Activity {
private static final String TAG = "SoupActivity";
private static final String DATA = null;
private String data = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
showResults();
}
else
{
parsePage();
}
}
protected void parsePage(){
Document doc = null;
try {
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
Elements rows = doc.select("tr[class]");
data = "<table>" + rows.toString() + "</table>";
showResults();
}
protected void showResults(){
WebView web = (WebView)findViewById(R.id.web);
web.loadData(data, "text/html", "utf-8");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString(DATA, data);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
}
super.onRestoreInstanceState(savedInstanceState);
}
}
Flash / Flex开发人员在这里开始进入Android开发阶段,我必须承认我到目前为止都很喜欢它,但显然需要花费很长时间来解决为什么会发生事情的方式。
所以我遇到的问题是我的应用程序在没有Internet连接的情况下崩溃了 - 应用程序(process.testing)意外停止了。只有在没有互联网连接时才会发生这种情况,如果有互联网连接则完美无缺。我的代码访问Internet的唯一部分是在try catch块中,任何人都可以看到我做错了什么或者在没有Internet连接时如何处理错误?
答案 0 :(得分:8)
您可以使用此功能查看连接是否可用:
/**
* Check the network state
* @param context context of application
* @return true if the phone is connected
*/
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
答案 1 :(得分:1)
如果您没有互联网连接,doc
可能为空,而您获得NullPointerException
,因为您没有检查此案例:
Document doc = null;
try {
// connect throws an exception, doc still null
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
// dereferencing null (doc) throws NullPointerException
Elements rows = doc.select("tr[class]");