-1

Goal: Reading a HTML-file using Buffered reader in an AsyncTask on Android.

Problem: The debug log gives the following error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference. It gives the error at the onPostExecute void. On further investigation I found out the following code: TVCode.setText(result); is throwing the NullPointerException. This means result = null. I can't find out why result = null since similar code on the normal Java, using Eclipse, is working fine.

Further info:

Android Studio: 1.3.2

JDK: 1.7.0_79-b15 amd64

Permissions:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Gradle: minSdkVersion 15, targetSdkVersion 23, compileSdkVersion 23

Here is the code of MainActivity.java:

public class MainActivity extends AppCompatActivity {


public static String ETURL = null;
public static final String TAG = MainActivity.class.getSimpleName();



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

        TextView TVCode = (TextView) findViewById(R.id.TVCode);
        ImageButton BTSend = (ImageButton) findViewById(R.id.BTSend);
        final EditText ETURLInput = (EditText) findViewById(R.id.ETUrlInput);

        BTSend.setOnClickListener(new View.OnClickListener() {

                                      public void onClick(View v) {
                                          ETURL = ETURLInput.getText().toString();

                                          new aSync().execute(ETURLInput.getText().toString());


                                      }


                                  }
        );

}

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

    @Override
    protected void onPreExecute() {

    }

    protected String doInBackground(String... ETURL)   {
        String line=null;
        String result="";


            try {
                URL url;

                url = new URL("" + ETURL);
                URLConnection conn = url.openConnection();


                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                line=br.readLine();
                while (line!= null) {

                    result=result+line;
                    line=br.readLine();
                }

                br.close();

                return result;


            } catch (Exception e) {
               Log.e(TAG, "Error:", e);
            }


        return result;
    }

    protected void onPostExecute(String result)  {
        try {
            TextView TVCode = (TextView) findViewById(R.id.TVCode);
            TVCode.setText(result);
        }
        catch (Exception e){
            Log.e(TAG, "ERROR: ", e);
        }
    }
}

Fix:

The TextView must be declared in the onPreExecute method instead of the on onPostExecute method. Thank you all for your help and time.

mehrdad khosravi
  • 2,228
  • 9
  • 29
  • 34
JI38D
  • 11
  • 2
  • 2
    Please post the nullPointerException. Which line ? – Henry Oct 19 '15 at 19:44
  • And while you are at it ... please edit your question for proper indenting. You expect us to spend our time to help you; so you should spend some of your time to provide your input in a form that is immediately readable. Formatting matters; because without it people have to spend much more time to grasp the content of your question! – GhostCat Oct 19 '15 at 19:49
  • What is the value for `result`? Don't initialize textView again in `onPostExecute()` method. You have already initialized in `onCreate()` method. – Piyush Oct 20 '15 at 05:47
  • Comment the udation of textview in post execute and only print result check what is result. – Singhak Oct 20 '15 at 05:53
  • @PiyushGupta The reason I'm declaring it again in _onPostExecute_ is because Android Studio gives the error: _Cannot resolve symbol TVCode_. – JI38D Oct 20 '15 at 11:17
  • Here's the error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference. The error is onPostExecute: TVCode.setText(result);. @Henry – JI38D Oct 20 '15 at 11:25
  • @Jägermeister I'm sorry about the invonveinence and I updated the formatting. I appreciate you spend some of your time to help me. Thank you. – JI38D Oct 20 '15 at 11:26
  • Here's the errorlog: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference. The error is onPostExecute: TVCode.setText(result);. @VVB – JI38D Oct 20 '15 at 11:28
  • @Singhak Please be clearer. I don't fully understand what you mean. – JI38D Oct 20 '15 at 11:31
  • I think I know where you might be wrong. Could you post your activity_main.xml file ? I believe either the view TVCode is missing, or there is a typo. – Henry Oct 20 '15 at 11:51
  • Comment the the line where you are updating textview in onpostexecute then only check value of result in log. If result is null then check in doInbackground your while loop is executing or not – Singhak Oct 20 '15 at 17:23

1 Answers1

0

The problem lies in the onPostExecute(). here you are trying to use findViewById(). But there is no view to be found. Hence the issue. You need to call the findViewById() on the activity or the inflated layout. If it's an activity, you need to pass the activity context to the async task and in case of fragment, you could pass in the inflated view.

More info here : Can't access "findViewById" in AsyncTask

Community
  • 1
  • 1
Henry
  • 17,490
  • 7
  • 63
  • 98