我是机器人中的新手并说“穷人”英语。
我有一个片段,我必须在执行webview之前测试如果网址存在。
在我的第一次测试中,我得到了一个“ android.os.NetworkOnMainThreadException ”
所以,我使用 AsyncTask
如果url存在,如何测试我的片段活动?
我在Android Studio下测试并在调试'doInBackground'中没有执行???
提前,非常感谢您的支持
这是我的班级AsyncTask:
public class ExistUrl extends AsyncTask<String, Void, Boolean> {
private static final String TAG = "CheckURL";
String filename="";
public ExistUrl(String URL) {
this.filename=URL;
Log.d(TAG, "url="+ this.filename);
}
@Override
protected Boolean doInBackground(String... params) {
// validateParams(params);
Log.v("name of file",this.filename);
Boolean OK =MyUtilities.exists(params[0]);
Log.v("*********** retour exists class:", Boolean.toString(OK));
return OK;
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.i(TAG, "Background cancelled.");
}
@Override
protected void onPostExecute(Boolean result){
super.onPostExecute(result);
String message = null;
if (result)
message = "Url succeeded.";
else
message = "Url failed.";
Log.i(TAG, message); }
}}
这是Myutilities.exists
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
我的片段活动
public class HainautFragment extends Fragment {
public HainautFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hainaut, container, false);
String Zone = "http://www.tournoi.org/tournoilive/affiche_categorie_dbf.asp?nuclb=1005&datedeb=2013/9/13&datefin=2013/9/22&IdTournoi=309569";
ConnectionDetector cd = new ConnectionDetector(getActivity());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new ExistUrl(Zone).execute();
*********************//how to test return***************************
}
return rootView;
}
答案 0 :(得分:0)
在这里传递网址
new ExistUrl(Zone).execute(url);
答案 1 :(得分:0)
试试这个..
if (isInternetPresent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new ExistUrl(Zone).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new ExistUrl(Zone).execute(new String[]{null});
}
然后,一旦您将url分配给文件名字符串,如this.filename=URL;
,则无需再次使用this.filename
,只需使用filename
public ExistUrl(String URL) {
this.filename=URL;
Log.d(TAG, "url="+ filename);
}
修改强>
您的发送Boolean OK =MyUtilities.exists(params[0]);
就像这样发送
MyUtilities.exists(filename);
@Override
protected Boolean doInBackground(String... params) {
Log.v("name of file",filename); //Correction here
Boolean OK =MyUtilities.exists(filename); //Correction here
Log.v("*********** retour exists class:", Boolean.toString(OK));
return OK;
}