为什么我的代码(http连接android)不起作用 [英] why my code (http connection android) doesn't work

查看:71
本文介绍了为什么我的代码(http连接android)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨大家好!

我试图制作简单的应用程序来连接互联网。但它不起作用!

&我不知道为什么?!我还搜索谷歌找到简单的例子,但我没有找到任何有用的东西。

请帮助我并解决我的错误。

tnx





错误


java.lang.NullPointerException:println需要一条消息

W / IInputConnectionWrapper(2880):showStatusIcon on inactive InputConnection







代码:



hi Guys !
im trying to make simple app to connect internet. but it doesn't work !
& i dont know why ?! i also searched Google to find Simple exampels but i didnt find anything usefull .
please help me and fix my mistakes .
tnx


error
:
java.lang.NullPointerException: println needs a message
W/IInputConnectionWrapper(2880): showStatusIcon on inactive InputConnection



Code :

package net.learn2develop.http3;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		
		
		
		Log.d("location", " 0 as start");
		
		InputStream in=null;
		int response=-1;
		String urlString="http://www.tabnak.ir";
		try
		{
		URL url=new URL(urlString);
		URLConnection conn=url.openConnection();
		if(!(conn instanceof  HttpURLConnection))
		throw new IOException("Not ann HTTP Connection");
		try
		{
			HttpURLConnection httpConn=(HttpURLConnection)conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response=httpConn.getResponseCode();
			if(response==HttpURLConnection.HTTP_OK)
			{in=httpConn.getInputStream();}
			else{ 
				Log.d("location", " 1");
				}
			TextView intxt=(TextView)findViewById(R.id.mytxt); 
			intxt.setText(in.toString());
			
		}
		catch(Exception ex0)
		{
			Log.d("e:",ex0.getLocalizedMessage());
		}
		
		}
		catch(Exception ex)
		{
			Log.d("location 2 Exception : ", ex.toString());
		}
		
		
		

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		
		
	}







AndroidManifest.xml:






AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="net.learn2develop.http3"

    android:versionCode="1"

    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >
        <activity

            android:name="net.learn2develop.http3.MainActivity"

            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>





UI:





UI :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

    <TextView

        android:id="@+id/mytxt"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />

</RelativeLayout>

推荐答案

java.lang.NullPointerException



您需要了解的一个基本错误。您有一个尚未初始化以引用任何内容的引用对象。使用你的调试器找出它的位置。



另外,如果你更好地使用空格和换行符,你的代码会更容易阅读。


One of the basic errors that you need to understand. You have a reference object somewhere that has not been initialized to refer to anything. Use your debugger to find out where it is.

Also, your code would be much easier to read if you made better use of spaces and newlines.


将您的HTTP连接代码移动到工作线程。网络I / O将导致UI线程崩溃(onCreate)。
Move your HTTP connection code to a worker thread. The network I/O will cause crash in UI thread (onCreate).


我解决了mySelf!



I solved it mySelf !

package com.example.html5;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import android.util.Log;
import android.os.AsyncTask;

public class MainActivity extends Activity {
	
	
	
	
	
	protected String ShowHtml()
	{
		//TextView myTxt=(TextView)findViewById(R.id.txtReturn); 
		HttpURLConnection urlConnection = null;
		String line="Start:";
		try
		{
		URL myUrl=new URL("http://google.com");
		urlConnection = (HttpURLConnection)myUrl.openConnection();
		BufferedReader in = new BufferedReader (new InputStreamReader(urlConnection.getInputStream()));
		
		//int Counter=0;
		while(in.readLine()!=null)
		{
			line=line+in.readLine().toString();
			//Counter++;
		}
		
	//	myTxt.setText(line);
		}
		catch(Exception ex0)
		{
		Log.d("Error : ",ex0.toString());
	//	myTxt.setText(ex0.toString());
		}
		finally
		{
			if(urlConnection!=null){urlConnection.disconnect(); 	}
			
			
		}
		return line;
		
	}
	
	
	
	
	
	class RetrieveFeedTask extends AsyncTask<string,> {

	    

	    protected String doInBackground(String... urls) {
	    	try
	    	{
	        return ShowHtml();
	    	}
	    	catch(Exception e)
	    	{
	    	return e.toString();
	    	}
	    }

	    protected void onPostExecute(String Result) {
	    	TextView mytxt2=(TextView)findViewById(R.id.txtReturn);
	    	mytxt2.setText(Result);
	      
	    }
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new RetrieveFeedTask().execute();
	}

	

}


这篇关于为什么我的代码(http连接android)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆