gpt4 book ai didi

android - 如何解决 java.net.UnknownHostException

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:40 26 4
gpt4 key购买 nike

我在 list 文件中获得了互联网许可。我的移动网络连接也正常。主要代码:

/**
* Created by Yogesh on 5/07/2016.
*/
public class All_Item_Fragment extends android.support.v4.app.ListFragment {
// Declare Variables
JSONArray jsonarray = null;
ListView list;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> itemlist;
static String NAME = "name";
static String DESCRIPTION = "Description";
static String PRICE = "price";
static String IMAGE = "image_path";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.all_item_layout, container, false);
itemlist = new ArrayList<HashMap<String, String>>();
new ReadJSON().execute();
list = (ListView) view.findViewById(android.R.id.list);

return view;
}

private class ReadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {
// Create an array
itemlist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
JSONObject jsonobject = JSONfunctions.getJSONfromURL("http://mahatiffin.com/web/selectallmenu.php");

try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("AllMenu");

for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("name", jsonobject.getString("name"));
map.put("Description", jsonobject.getString("Description"));
map.put("price", jsonobject.getString("price"));
map.put("image_path", jsonobject.getString("image_path"));
// Set the JSON Objects into the array
itemlist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), itemlist);
// Set the adapter to the ListView
list.setAdapter((ListAdapter) adapter);
}
}
}


public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;

// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}

// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {

jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

return jArray;
}
}

在可能的 fragment 页面中,不会显示任何内容,只会显示空白页面。

日志输出:

>05-18 17:43:11.730 27019-27019/com.androidbelieve.MahaTiffin D/dalvikvm: VFY: replacing opcode 0x6f at 0x0000
05-18 17:43:11.740 27019-27082/com.androidbelieve.MahaTiffin E/log_tag: Error converting result java.lang.NullPointerException
05-18 17:43:11.740 27019-27082/com.androidbelieve.MahaTiffin E/log_tag: Error parsing data org.json.JSONException: End of input at character 0 of
05-18 17:43:11.770 27019-27082/com.androidbelieve.MahaTiffin W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0x40e11378)
05-18 17:43:11.770 27019-27082/com.androidbelieve.MahaTiffin E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTas...(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.androidbelieve.MahaTiffin.All_Item_Fragment$ReadJSON.doInBackground(All_Item_Fragment.java:58)
at com.androidbelieve.MahaTiffin.All_Item_Fragment$ReadJSON.doInBackground(All_Item_Fragment.java:43)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTas...(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
05-18 17:43:12.420 27019-27019/com.androidbelieve.MahaTiffin W/FragmentManager: moveToState: Fragment state for Veg_Item_Fragment{415d7030 #1 id=0x7f0c00a0 android:switcher:2131493024:1} not updated inline; expected state 3 found 2
05-18 17:43:12.530 27019-27104/com.androidbelieve.MahaTiffin E/log_tag: Error in http connection java.net.UnknownHostException: Unable to resolve host "mahatiffin.com": No address associated with hostname
05-18 17:43:12.540 27019-27104/com.androidbelieve.MahaTiffin E/log_tag: Error converting result java.lang.NullPointerException
05-18 17:43:12.540 27019-27104/com.androidbelieve.MahaTiffin E/log_tag: Error parsing data org.json.JSONException: End of input at character 0 of
05-18 17:43:12.570 27019-27104/com.androidbelieve.MahaTiffin W/dalvikvm: threadid=14: thread exiting with uncaught exception (group=0x40e11378)
05-18 17:43:12.570 27019-27104/com.androidbelieve.MahaTiffin I/Process: Sending signal. PID: 27019 SIG: 9

我该如何解决这个问题?

最佳答案

原因:通常,当您无法解析您提供的 URL 的 DNS 记录时,会触发 UnknownHostException。该操作有一个合理的超时时间,但如果您的 Wi-Fi 连接信号较弱或者您的设备上没有足够的信号,通信可能会在发送请求和接收响应之间中断,因此您的设备没有收到响应,因此它认为这是 DNS 超时。

长话短说,异常主要有两个原因:

  1. 如果您的 Wi-Fi 信号较弱。
  2. 如果您的设备连接到 Wi-Fi 但没有互联网可用。

解决方案:在请求之前检查互联网的可用性

public static boolean isInternetOn(Context context) {

if (isMobileOrWifiConnectivityAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (Exception e) {
DebugLog.console("Couldn't check internet connection Exception is : " + e);
}
} else {
DebugLog.console("Internet not available!");
}
return false;
}


public static boolean isMobileOrWifiConnectivityAvailable(Context ctx) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;


try {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected()) {
haveConnectedWifi = true;
}
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected()) {
haveConnectedMobile = true;
}
}
} catch (Exception e) {
DebugLog.console("[ConnectionVerifier] inside isInternetOn() Exception is : " + e.toString());
}
return haveConnectedWifi || haveConnectedMobile;
}

关于android - 如何解决 java.net.UnknownHostException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37314712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com