1

Textview value is crashing with null pointer exception Below is the code which i am using. Is there any issue in the code.

 public class MainActivity extends Activity {
 Button btn;
 int i =0;
 SharedPreferences.Editor preferences;
 TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button1);
    preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
    txt = (TextView) findViewById(R.id.textView1);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

             new LongOperation().execute("");
        }
    });

}

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

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            txt.setText("Executed -----------------------    ");
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

}

After it is coming to onPostExecute the textview value is not setting the value. Please help me. Thanks in advance.

Nikhil PV
  • 1,014
  • 2
  • 16
  • 29

1 Answers1

1

Textview value is not setting because the value of id may be null. check it.