0

I want to be able to display the content of a text file on a server into a textview. Please, someone tell me why I keep getting a NullPointerException when I try to run this app. I Even added the Internet permissions in the manifest.xml file.

package com.example.httpclient_examples;

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 MainActivity extends Activity implements Runnable {



     final String textSource = "http://www.website.com/text.txt";

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.fragment_main);



           TextView textPrompt = (TextView)findViewById(R.id.textprompt);          


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

           //thread

           Runnable r = new MainActivity();
           Thread t = new Thread(r);
           t.start();





           textPrompt.setText("Finished!");

       }

    @Override
    public void run() {
          TextView textMsg = (TextView)findViewById(R.id.textmsg);

          try {
               URL   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) {

           e.printStackTrace();
           textMsg.setText(e.toString());
          } catch (IOException e) {

           e.printStackTrace();
           textMsg.setText(e.toString());
          }       

    }
}

 

07-28 12:06:29.477: I/Choreographer(7101): Skipped 121 frames!  The application may be doing too much work on its main thread.
07-28 12:06:31.087: I/Choreographer(7101): Skipped 271 frames!  The application may be doing too much work on its main thread.
07-28 12:06:32.387: D/gralloc_goldfish(7101): Emulator without GPU emulation detected.
07-28 12:06:34.817: I/Process(7101): Sending signal. PID: 7101 SIG: 9
07-28 17:25:58.658: D/AndroidRuntime(14851): Shutting down VM
07-28 17:25:58.658: W/dalvikvm(14851): threadid=1: thread exiting with uncaught exception (group=0xb3ab7ba8)
07-28 17:25:58.858: E/AndroidRuntime(14851): FATAL EXCEPTION: main
07-28 17:25:58.858: E/AndroidRuntime(14851): Process: com.example.httpclient_examples, PID: 14851
07-28 17:25:58.858: E/AndroidRuntime(14851): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.httpclient_examples/com.example.httpclient_examples.MainActivity}: java.lang.NullPointerException
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.os.Looper.loop(Looper.java:136)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread.main(ActivityThread.java:5017)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at java.lang.reflect.Method.invokeNative(Native Method)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at java.lang.reflect.Method.invoke(Method.java:515)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at dalvik.system.NativeStart.main(Native Method)
07-28 17:25:58.858: E/AndroidRuntime(14851): Caused by: java.lang.NullPointerException
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.Activity.findViewById(Activity.java:1884)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at com.example.httpclient_examples.MainActivity.<init>(MainActivity.java:16)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at java.lang.Class.newInstanceImpl(Native Method)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at java.lang.Class.newInstance(Class.java:1208)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-28 17:25:58.858: E/AndroidRuntime(14851):    ... 11 more
07-28 17:26:06.898: I/Process(14851): Sending signal. PID: 14851 SIG: 9
laalto
  • 150,114
  • 66
  • 286
  • 303
  • please post Logcat .. your code have many issues .. first you cant write to UIThread textMsg.setText(stringText) on a Background task. if you want to read and write to UIThread use AsyncTask – Itzik Samara Jul 28 '14 at 22:04
  • And you shouldn't manage threads yourself, check http://developer.android.com/reference/android/os/AsyncTask.html – Leonardo Jul 28 '14 at 22:07
  • possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – panini Jul 28 '14 at 22:09
  • have you considered some library such as Volley? have a look here : http://blog.chrisblunt.com/android-getting-started-with-volley/ – Rocel Jul 28 '14 at 22:35
  • I just added the logcat. Would it be better if I used an AsyncTask instead of a normal thread? – user3665751 Jul 28 '14 at 23:49
  • This is a buggy code. Post Logcat in proper format. – VVB Jul 29 '14 at 04:34

2 Answers2

0
07-28 17:25:58.858: E/AndroidRuntime(14851): Caused by: java.lang.NullPointerException
07-28 17:25:58.858: E/AndroidRuntime(14851):    at android.app.Activity.findViewById(Activity.java:1884)
07-28 17:25:58.858: E/AndroidRuntime(14851):    at com.example.httpclient_examples.MainActivity.<init>(MainActivity.java:16)

The code you posted doesn't match with the stacktrace. However, this stacktrace says you're calling findViewById() too early when MainActivity is being initialized, likely trying to init a member variable on row 16. That's the NPE. To fix it, move the findViewById() to onCreate() after setContentView().

There are other problems as well.

  • This is totally wrong:

    Runnable r = new MainActivity();
    

    Never instantiate activities with new. In this case you could use this to get a reference to your current activity instance.

  • In your background thread run() you cannot touch your UI views such as call setText() on TextViews.

Please read some introductory text on AsyncTask - it's the basic building block for doing work on a background thread while providing updates and results in the UI.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

It's working now. I moved the textview declarations to the oncreate() and changed Runnable r = new MainActivity(); to Runnable r = this; and I also used runOnUiThread() to post the updated text to the screen.

package com.example.httpclient_examples;

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 MainActivity extends Activity implements Runnable {

     TextView textPrompt, textMsg;
     String stringText = "";

     final String textSource = "http://www.website.com/text.txt";

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.fragment_main);



           textPrompt = (TextView)findViewById(R.id.textprompt);           
           textMsg = (TextView)findViewById(R.id.textmsg);

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

           //thread

           Runnable r = this;
           Thread t = new Thread(r);
           t.start();





           textPrompt.setText("Finished!");

       }

    @Override
    public void run() {


          try {
               URL   textUrl = new URL(textSource);
           BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                 String StringBuffer;

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


                 bufferReader.close();

                 runOnUiThread(new Runnable(){

                     @Override
                     public void run(){
                         textMsg.setText(stringText);

                    }
                 });
          } 


          catch (MalformedURLException e) {

           e.printStackTrace();
           textMsg.setText(e.toString());
          } catch (IOException e) {

           e.printStackTrace();
           textMsg.setText(e.toString());
          }       

    }
}