0

I try to load a text file in a string. So I searched in google an found an example code:

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!");

    }
}

I put it in my project now it looks so:

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

    }

And now i get an error in log it says:

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)

When I delete the http:// before the URL i get the text "java error can't find protocol"

Edit 1:

Line 70 is

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)
madhan kumar
  • 1,560
  • 2
  • 26
  • 36
Marius Schönefeld
  • 425
  • 2
  • 6
  • 21

1 Answers1

1

Form the discussion in the chat https://chat.stackoverflow.com/rooms/59874/discussion-between-marius-schonefeld-and-raghunandan its NetWorkOnMainThreadException which occurs if you are doing networkoperation on the main thread which is the ui thread.

The 3 params that you asked for

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

Example:

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

For Edit 1:

Change this

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

to

scanText = (TextView)getActivity().findViewById(R.id.scanText); 
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256