问题描述
我是安卓开发的新手.我正在为我的应用程序使用 android studio
.我创建了一个 DB
,然后在 Yii 中创建了一个 web 服务
,在 ARC
上测试它并使用 GET
方法,它完美地显示了结果.之后,我创建了一个 app
,我想在其中使用 web service
并使用它的 get 方法来显示结果.
下面是我的数据库表结构
这种情况是,当用户在应用中输入 id
并点击提交按钮时,它应该显示相应的 username
.为此,请参阅以下代码
清单
<申请机器人:allowBackup =真"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><意图过滤器><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></意图过滤器></活动></应用程序>
MainActivity.java
公共类 MainActivity 扩展 AppCompatActivity {String URLGET = "http://my_ip:8000/app/web/users/";字符串结果 = "";TextView 电视;public static final String LOG_TAG = MainActivity.class.getSimpleName();@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);最终按钮按钮 = (按钮) findViewById(R.id.btn_Submit);button.setOnClickListener(new Button.OnClickListener() {@覆盖public void onClick(View v) {字符串 reqURL = URLGET;新的 RestOperation().execute(reqURL);//调用WebService(查询);}});}公共类 RestOperation 扩展了 AsyncTask{final HttpClient httpClient = new DefaultHttpClient();字符串内容;字符串错误;ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);字符串数据 = "";TextView getData = (TextView) findViewById(R.id.getData);EditText userInput = (EditText) findViewById(R.id.EnterId);@覆盖protected void onPreExecute() {super.onPreExecute();progressDialog.setTitle("请稍候...");progressDialog.show();尝试 {数据 += "&"+ URLEncoder.encode("data", "UTF-8") + "-" + userInput.getText();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}@覆盖受保护的 Void doInBackground(String... params) {BufferedReader br = null;URL url = null;尝试 {url = 新 URL(params[0]);URLConnection 连接 = url.openConnection();connection.setDoOutput(true);OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());outputStreamWriter.write(data);outputStreamWriter.flush();br = new BufferedReader(new InputStreamReader(connection.getInputStream()));StringBuilder sb = new StringBuilder();字符串行 = null;while ((line = br.readLine()) != null) {sb.append(line);sb.append(System.getProperty("line.separator"));}内容 = sb.toString();} catch (MalformedURLException e) {错误 = e.getMessage();e.printStackTrace();} catch (IOException e) {错误 = e.getMessage();e.printStackTrace();} 最后 {尝试 {br.close();} catch (IOException e) {e.printStackTrace();}}返回空;}@覆盖protected void onPostExecute(Void aVoid) {super.onPostExecute(aVoid);progressDialog.dismiss();如果(错误!= null){getData.setText("错误" + 错误);} 别的 {getData.setText(content);}}}
}
但是当我运行应用程序时,输入任何给定的 ID 并执行提交.进度条显示了很长时间,然后应用程序崩溃并出现以下错误.
致命异常:AsyncTask #1进程:com.example.accurat.webservice,PID:642java.lang.RuntimeException: 执行 doInBackground() 时发生错误在 android.os.AsyncTask$3.done(AsyncTask.java:304)在 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)在 java.util.concurrent.FutureTask.setException(FutureTask.java:222)在 java.util.concurrent.FutureTask.run(FutureTask.java:242)在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)在 java.lang.Thread.run(Thread.java:818)引起:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference在 com.example.accurat.webservice.MainActivity$RestOperation.doInBackground(MainActivity.java:141)在 com.example.accurat.webservice.MainActivity$RestOperation.doInBackground(MainActivity.java:72)在 android.os.AsyncTask$2.call(AsyncTask.java:292)在 java.util.concurrent.FutureTask.run(FutureTask.java:237)在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)在 java.lang.Thread.run(Thread.java:818)02-07 15:57:42.929 642-642/com.example.accurat.webservice E/WindowManager: android.view.WindowLeaked: Activity com.example.accurat.webservice.MainActivity 已经泄露了窗口 com.android.internal.policy.impl.PhoneWindow$DecorView{3f2c8572 VE.... R......D 0,0-729,322} 最初是在这里添加的在 android.view.ViewRootImpl.(ViewRootImpl.java:363)在 android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)在 android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)在 android.app.Dialog.show(Dialog.java:298)在 com.example.accurat.webservice.MainActivity$RestOperation.onPreExecute(MainActivity.java:90)在 android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)在 android.os.AsyncTask.execute(AsyncTask.java:539)在 com.example.accurat.webservice.MainActivity$1.onClick(MainActivity.java:65)在 android.view.View.performClick(View.java:4780)在 android.view.View$PerformClick.run(View.java:19866)在 android.os.Handler.handleCallback(Handler.java:739)在 android.os.Handler.dispatchMessage(Handler.java:95)在 android.os.Looper.loop(Looper.java:135)在 android.app.ActivityThread.main(ActivityThread.java:5254)在 java.lang.reflect.Method.invoke(Native Method)在 java.lang.reflect.Method.invoke(Method.java:372)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
我在谷歌上搜索了很多文章,但没有找到正确的答案,虽然我尝试实现它们但仍然没有结果.
以下是我的搜索结果.
然后我再次将我的
ip
替换为localhost
但仍然看到相同的错误.我正在模拟器上测试我的应用,所以我把我的
ip
地址放在了 url 中.我几乎一整天都在坚持.任何帮助,将不胜感激.
解决方案您收到空指针异常.
如果在初始化读取器之前发生异常,则会导致此错误,因为 br.close() 被放置在 finally 块中.在最终关闭资源之前始终检查 null 是一种很好的做法.
在 finally 块中试试这个
if(br!= null)br.close();
祝你好运
I am newbie to android development. I am using
android studio
for my application. I have created aDB
and then created aweb service
in Yii, tested it onARC
and use theGET
method and it shows the result perfectly. After that i created anapp
in which i want to use theweb service
and use it's get method to display a result.Below is my DB table structure
The scenario is when ever a user enters the
id
in the app and hit the submit button it should show the correspondingusername
. For this see the below codesManifest
<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
MainActivity.java
public class MainActivity extends AppCompatActivity { String URLGET = "http://my_ip:8000/app/web/users/"; String result = ""; TextView tv; public static final String LOG_TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button = (Button) findViewById(R.id.btn_Submit); button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { String reqURL = URLGET; new RestOperation().execute(reqURL); //callWebService(query); } }); } public class RestOperation extends AsyncTask<String, Void, Void> { final HttpClient httpClient = new DefaultHttpClient(); String content; String error; ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); String data = ""; TextView getData = (TextView) findViewById(R.id.getData); EditText userInput = (EditText) findViewById(R.id.EnterId); @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.setTitle("Please Wait..."); progressDialog.show(); try { data += "&" + URLEncoder.encode("data", "UTF-8") + "-" + userInput.getText(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override protected Void doInBackground(String... params) { BufferedReader br = null; URL url = null; try { url = new URL(params[0]); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream()); outputStreamWriter.write(data); outputStreamWriter.flush(); br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); sb.append(System.getProperty("line.separator")); } content = sb.toString(); } catch (MalformedURLException e) { error = e.getMessage(); e.printStackTrace(); } catch (IOException e) { error = e.getMessage(); e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); progressDialog.dismiss(); if (error != null) { getData.setText("Error" + error); } else { getData.setText(content); } } }
}
But when i run the app, enter any given id's and perform submit. The progress bat shows up for a long while and then the app crashes giving the following errors.
FATAL EXCEPTION: AsyncTask #1 Process: com.example.accurat.webservice, PID: 642 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference at com.example.accurat.webservice.MainActivity$RestOperation.doInBackground(MainActivity.java:141) at com.example.accurat.webservice.MainActivity$RestOperation.doInBackground(MainActivity.java:72) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) 02-07 15:57:42.929 642-642/com.example.accurat.webservice E/WindowManager: android.view.WindowLeaked: Activity com.example.accurat.webservice.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3f2c8572 V.E..... R......D 0,0-729,322} that was originally added here at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85) at android.app.Dialog.show(Dialog.java:298) at com.example.accurat.webservice.MainActivity$RestOperation.onPreExecute(MainActivity.java:90) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591) at android.os.AsyncTask.execute(AsyncTask.java:539) at com.example.accurat.webservice.MainActivity$1.onClick(MainActivity.java:65) at android.view.View.performClick(View.java:4780) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I searched many articles on google and couldn't find the correct answers, though i tried to implement them but still no result.
Below are the findings from my search.
Update 1
By using
Ben
andX3Btel
suggestions my app stops crashing but it's showing me below error on emulatorI then again replaced my
ip
tolocalhost
but still saw the same error.I am testing my app on the emulator so i put my
ip
address in the url.I am stuck to from almost all the day. Any help would be appreciated.
解决方案You are getting a nullpointer exception.
if exception happened before initializing the reader it will lead to this error because br.close() is placed in finally block. It's good practice to always check for null before closing resources in finally.
try this in finally block
if(br!= null) br.close();
Good luck
这篇关于进度对话框不断显示在android studio中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!