且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的代码(http连接android)不起作用

更新时间:2023-02-03 19:39:27

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

	

}