eclipse android从url加载文本

时间:2014-08-24 09:07:34

标签: java android eclipse url web

我尝试在字符串中加载文本文件。所以我在google搜索了一个示例代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidInternetTxt extends Activity {

    TextView textMsg, textPrompt;
    final String textSource = "http://sites.google.com/site/androidersite/text.txt";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textPrompt = (TextView)findViewById(R.id.textprompt);
        textMsg = (TextView)findViewById(R.id.textmsg);

        textPrompt.setText("Wait...");

        URL textUrl;
        try {
            textUrl = new URL(textSource);
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
            String StringBuffer;
            String stringText = "";
            while ((StringBuffer = bufferReader.readLine()) != null) {
                stringText += StringBuffer;
            }
            bufferReader.close();
            textMsg.setText(stringText);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            textMsg.setText(e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            textMsg.setText(e.toString());
        }

        textPrompt.setText("Finished!");

    }
}

我把它放在我的项目中现在它看起来如此:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Button;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.widget.TextView;
import android.graphics.ImageFormat;

public class ScannerFragment extends Fragment{

//public MainActivity(){}

     private Camera mCamera;
     private CameraPreview mPreview;
     private Handler autoFocusHandler;
     private static final String TAG_PID = "pid";

     TextView scanText;
     ImageScanner scanner;
     private boolean barcodeScanned = false;
     private boolean previewing = true;
     FrameLayout preview;
     final String textSource = "http://www.example.com/mytxt.txt";

     static {
         System.loadLibrary("iconv");
     }

        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

        }

        @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {

            View android = inflater.inflate(R.layout.fragment_scanner, container, false);
            autoFocusHandler = new Handler();
            mCamera = getCameraInstance();
            mPreview = new CameraPreview(this.getActivity(), mCamera, previewCb, autoFocusCB);
            preview = (FrameLayout) android.findViewById(R.id.cameraPreview);
            preview.addView(mPreview);
            scanner = new ImageScanner();
            scanText = (TextView) android.findViewById(R.id.scanText);       

            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            String key2 = sharedPref.getString("key_data", "");
            scanText.setText("barcode result old "+ key2);
            return android;

        }


        public void onPause() {
            super.onPause();
            releaseCamera();
        }

        /** A safe way to get an instance of the Camera object. */
        public static Camera getCameraInstance(){
            Camera c = null;
            try {
                c = Camera.open();
            } catch (Exception e){
            }
            return c;
        }

        private void releaseCamera() {
            if (mCamera != null) {
                previewing = false;
                mCamera.setPreviewCallback(null);
                mCamera.release();
                mCamera = null;
            }
        }

        private Runnable doAutoFocus = new Runnable() {
                public void run() {
                    if (previewing)
                        mCamera.autoFocus(autoFocusCB);
                }
            };

        PreviewCallback previewCb = new PreviewCallback() {
                public void onPreviewFrame(byte[] data, Camera camera) {
                    Camera.Parameters parameters = camera.getParameters();
                    Size size = parameters.getPreviewSize();

                    Image barcode = new Image(size.width, size.height, "Y800");
                    barcode.setData(data);

                    int result = scanner.scanImage(barcode);

                    if (result != 0) {
                        previewing = false;
                        mCamera.setPreviewCallback(null);
                        mCamera.stopPreview();

                        SymbolSet syms = scanner.getResults();
                        for (Symbol sym : syms) {

                            URL textUrl;
                            try {
                                textUrl = new URL(textSource);
                                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                                String StringBuffer;
                                String stringText = "";
                                while ((StringBuffer = bufferReader.readLine()) != null) {
                                    stringText += StringBuffer;
                                }
                                bufferReader.close();
                                scanText.setText(stringText);
                            } catch (MalformedURLException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                scanText.setText(e.toString());
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                scanText.setText(e.toString());
                            }

                            //StringBuilder tv = new StringBuilder();
                             Log.d("test", "voher");
                             Log.d("test", "nachher");

                            //scanText.setText("barcode result " + sym.getData());
                            String key = sym.getData();
                            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("key_data", sym.getData());
                            editor.commit();

                            String str = sharedPref.getString("key_server", "");
                            Log.d("test", "voher");
                            //if (key.equals(str)){
                                //scanText.setText("ist richtig");

                        //    }else{
                        //      scanText.setText("ist falsch");
                        //      
                        //    }

                            barcodeScanned = true;
                        }
                    }
                }
            };

        // Mimic continuous auto-focusing
        AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
                public void onAutoFocus(boolean success, Camera camera) {
                    autoFocusHandler.postDelayed(doAutoFocus, 1000);
                }
            };

    }

现在我在日志中收到一个错误:

08-24 11:31:19.096: E/AndroidRuntime(6845): FATAL EXCEPTION: main
08-24 11:31:19.096: E/AndroidRuntime(6845): Process: de.webdesign_schoenefeld.europaschule, PID: 6845
08-24 11:31:19.096: E/AndroidRuntime(6845): android.os.NetworkOnMainThreadException
08-24 11:31:19.096: E/AndroidRuntime(6845):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.net.URL.openStream(URL.java:470)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at de.webdesign_schoenefeld.europaschule.ScannerFragment$2.onPreviewFrame(ScannerFragment.java:144)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at android.hardware.Camera$EventHandler.handleMessage(Camera.java:1013)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at android.os.Looper.loop(Looper.java:157)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at android.app.ActivityThread.main(ActivityThread.java:5335)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.lang.reflect.Method.invokeNative(Native Method)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at java.lang.reflect.Method.invoke(Method.java:515)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-24 11:31:19.096: E/AndroidRuntime(6845):     at dalvik.system.NativeStart.main(Native Method)

当我在URL之前删除http://我得到文本“java error not find protocol”

编辑1:

第70行

scanText = (TextView)getView().findViewById(R.id.scanText);

Stacktrace:

08-24 12:30:33.846: E/MoreInfoHPW_ViewGroup(15791): Parent view is not a TextView 
08-24 12:30:36.716: E/AndroidRuntime(15791): FATAL EXCEPTION: main 
08-24 12:30:36.716: E/AndroidRuntime(15791): Process: de.webdesign_schoenefeld.europaschule, PID: 15791 
08-24 12:30:36.716: E/AndroidRuntime(15791): java.lang.NullPointerException 
08-24 12:30:36.716: E/AndroidRuntime(15791): at de.webdesign_schoenefeld.europaschule.ScannerFragment.onCreate(ScannerFragment.java:70) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.Fragment.performCreate(Fragment.java:1678) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:859) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.BackStackRecord.run(BackStackRecord.java:684) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.os.Handler.handleCallback(Handler.java:733) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.os.Handler.dispatchMessage(Handler.java:95) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.os.Looper.loop(Looper.java:157) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at android.app.ActivityThread.main(ActivityThread.java:5335) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at java.lang.reflect.Method.invokeNative(Native Method) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at java.lang.reflect.Method.invoke(Method.java:515) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 
08-24 12:30:36.716: E/AndroidRuntime(15791): at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

如果您正在主线程(即ui线程)上进行网络操作,则在聊天http://chat.stackoverflow.com/rooms/59874/discussion-between-marius-schonefeld-and-raghunandan中发生NetWorkOnMainThreadException的讨论。

你要求的3个参数

  
      
  1. Params,执行时发送给任务的参数类型。
  2.   
  3. 进度,后台计算期间发布的进度单位的类型。
  4.   
  5. 结果,背景计算结果的类型。
  6.   

示例:

public class AndroidInternetTxt extends Activity {

    TextView textMsg, textPrompt;
    final String textSource = "http://sites.google.com/site/androidersite/text.txt";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textPrompt = (TextView)findViewById(R.id.textprompt);
        textMsg = (TextView)findViewById(R.id.textmsg);

        textPrompt.setText("Wait...");
        new TheTask().execute("http://sites.google.com/site/androidersite/text.txt");
        }

        private class TheTask extends AsyncTask<String,Void,String>
        {

        protected String doInBackground(String... args)
        {
        URL textUrl;
        String stringText = "";
        try {
            textUrl = new URL(args[0]);
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
            String StringBuffer;

            while ((StringBuffer = bufferReader.readLine()) != null) {
                stringText += StringBuffer;
            }
            bufferReader.close();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
         return stringText;
        }
        protected void onPostExecute(String result)
        {
          super.onPostExecute(result); 
          textPrompt.setText(result);
        } 
       }
} 

编辑1:

更改此

scanText = (TextView)getView().findViewById(R.id.scanText);

scanText = (TextView)getActivity().findViewById(R.id.scanText);