简体   繁体   English

尝试将inputstream转换为字符串时,android应用程序崩溃

[英]android app crashing when trying to convert inputstream to string

in the following code, i am trying to perform a GET operation on a webservice that i have coded and hosted on localhost. 在以下代码中,我试图在我已编码并托管在本地主机上的Web服务上执行GET操作。 The method OpenHttpConnection is working just fine because i have put toasts in between to check if there was sth wrong in there. OpenHttpConnection方法工作得很好,因为我在两者之间进行了吐司检查,以了解其中是否存在错误。 the app crashes when i try to convert the input stream into a string using the bufferreader. 当我尝试使用bufferreader将输入流转换为字符串时,应用程序崩溃。 Please have a look and see if you can spot the error. 请看一下,看看是否可以发现错误。

Thanks :) 谢谢 :)

public class ServicetestActivity extends Activity {



public static String iStream_to_String(InputStream is1)
{
     BufferedReader rd = new BufferedReader(new InputStreamReader(is1));
     String line;
     StringBuilder sb =  new StringBuilder();
     try {
        while ((line = rd.readLine()) != null) {
                sb.append(line);
         }
         rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     String contentOfMyInputStream = sb.toString();
     return contentOfMyInputStream;
}






/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    InputStream is=null;
    try {
         is=OpenHttpConnection("http://localhost/webservice.php?device=ayaz");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String line= iStream_to_String(is);
    Toast.makeText(this, line, Toast.LENGTH_LONG).show(); 
}


    private InputStream OpenHttpConnection(String link) throws IOException {
        // TODO Auto-generated method stub
        InputStream inputStream = null;
        int response = -1;
        Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
        URL url = new URL(link);
        URLConnection connection = url.openConnection();
        Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
        if (!(connection instanceof HttpURLConnection))
          throw new IOException("Not a HTTP connection");
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
            httpURLConnection.setAllowUserInteraction(false);
            Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            response = httpURLConnection.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
            }

        } catch (Exception e) {
            // TODO: handle exception
            throw new IOException("Error connecting");
        }
        return inputStream;}

// see http://androidsnippets.com/executing-a-http-get-request-with-httpclient

} }

Also the log cat is as follows: 日志猫也如下所示:

10-14 20:54:13.660: E/AndroidRuntime(1348): FATAL EXCEPTION: main
10-14 20:54:13.660: E/AndroidRuntime(1348): java.lang.RuntimeException: Unable to start activity ComponentInfo{web.service/web.service.ServicetestActivity}: java.lang.NullPointerException
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.os.Looper.loop(Looper.java:130)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread.main(ActivityThread.java:3683)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at java.lang.reflect.Method.invokeNative(Native Method)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at java.lang.reflect.Method.invoke(Method.java:507)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at dalvik.system.NativeStart.main(Native Method)
10-14 20:54:13.660: E/AndroidRuntime(1348): Caused by: java.lang.NullPointerException
10-14 20:54:13.660: E/AndroidRuntime(1348):     at java.io.Reader.<init>(Reader.java:65)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at web.service.ServicetestActivity.iStream_to_String(ServicetestActivity.java:31)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at web.service.ServicetestActivity.onCreate(ServicetestActivity.java:65)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-14 20:54:13.660: E/AndroidRuntime(1348):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-14 20:54:13.660: E/AndroidRuntime(1348):     ... 11 more

This may help you. 这可能对您有帮助。

   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();

            return result;
         }catch (Exception e) {}

The log show information as follows: 日志显示信息如下:

FATAL EXCEPTION: main 10-14 20:54:13.660:E/AndroidRuntime(1348):java.lang.RuntimeException: 
Unable to start activity ComponentInfo{web.service/web.service.ServicetestActivity}:
java.lang.NullPointerException 10-14 20:54:13.660: E/AndroidRuntime(1348):

and then: 接着:

 Caused by: java.lang.NullPointerException 10-14 20:54:13.660: 
 E/AndroidRuntime(1348): at java.io.Reader.(Reader.java:65) 10-14 20:54:13.660:
 E/AndroidRuntime(1348): at java.io.InputStreamReader.(InputStreamReader.java:122) 
 10-14 20:54:13.660: E/AndroidRuntime(1348): at java.io.InputStreamReader. 
 (InputStreamReader.java:59) 10-14 20:54:13.660: E/AndroidRuntime(1348): 
 at web.service.ServicetestActivity.iStream_to_String(ServicetestActivity.java:31) 
 10-14 20:54:13.660: E/AndroidRuntime(1348): 
 at web.service.ServicetestActivity.onCreate(ServicetestActivity.java:65) 

means your app is crashing at line no. 表示您的应用在第行崩溃。 31 in iStream_to_String. iStream_to_String中的31。 So, check at this line no. 因此,请检查此行号。 what is going wrong. 出了什么问题。

For checking condition, if something goes wrong, prefer to use Log other than Toast, as Toast is not for checking errors. 对于检查条件,如果出现问题,请使用Toast以外的其他日志,因为Toast并非用于检查错误。

I got my problem solved. 我的问题解决了。 The problem was not in buffer reader but my connection was being refused. 问题不在缓冲区读取器中,但我的连接被拒绝了。 The connection was being refused because the link that I passed referred to localhost(my machine). 该连接被拒绝,因为我传递的链接引用了localhost(我的机器)。 But in actuality Android takes localhost as the emulator itself, and since there was no server hosted it kept on refusing the connection. 但是实际上,Android将localhost作为模拟器本身,并且由于没有托管服务器,因此它一直拒绝连接。 The solution to this is that I used my machine's ip instead of localhost so it would be http://xxxx/ ...... 解决方案是我使用了机器的ip而不是localhost,所以它将是http:// xxxx / ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM