我是Android和Java开发的新手,我是网络开发人员,想学习Android工作室和java。
与学习新语言一样,我要做的第一件事就是进行一些数据库调用,这只是JSON调用。
使用httpURLConnection,我在网上找到了例子,当我在android studio中运行它时它在我的主函数中工作,但是当我把它放在按钮上点击功能并在我的手机上运行我的应用程序时,我的应用程序崩溃。
我也补充说 清单标签内的AndroidManifest.xml。
这是我得到的错误
11-22 19:47:46.354 24975-24975/com.example.adis.myapp I/System.out: I am here//////////////////////////////////////////
11-22 19:47:46.494 24975-24975/com.example.adis.myapp D/AndroidRuntime: Shutting down VM
11-22 19:47:46.494 24975-24975/com.example.adis.myapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41659e00)
11-22 19:47:46.514 24975-24975/com.example.adis.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.adis.myapp, PID: 24975
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
ive Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1148)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
at com.example.adis.myapp.MainActivity.loginFunction(MainActivity.java:85)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
11-22 19:47:46.524 923-1275/? W/ActivityManager: Force finishing activity com.example.adis.myapp/.MainActivity
这是我的onClick功能
public void loginFunction(View view) throws IOException, JSONException {
System.out.println("I am here//////////////////////////////////////////");
try {
URL url = new URL("http://echo.jsontest.com/insert-key-here/insert-value-here/key/value");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
如果你看到一些愚蠢的错误,即使java初学者应该看到,也要严厉对待我,因为我不会。
感谢您停止:)
答案 0 :(得分:2)
您不允许在主线程上建立网络连接,因为这会冻结UI线程并使您的应用无响应。这就是抛出异常的原因。
您可以使按钮触发新线程或AsyncTask以完成操作。
答案 1 :(得分:2)
在Application标签之前将其添加到AndroidManifest.xml: -
<uses-permission android:name="android.permission.INTERNET"/>
<application
.....
</application>
即使在琐碎的互联网连接上,HTTP请求也会花费大量时间,从而冻结主UI线程。你可以做的是在按下按钮时启动一个新的AsyncTask。
将代码放在单独的类中,如: -
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params){
System.out.println("I am here//////////////////////////////////////////");
try {
URL url = new URL("http://echo.jsontest.com/insert-key-here/insert-value-here/key/value");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
并修改onClickButton,如: -
OnButtonclick(...){
...
HTTPRequestTask testTask =new HTTPRequestTask();
testTask.execute();
...
}
PS - 我已将新类命名为HTTPRequestTask。您可以选择自己的名字。