Following is the code of main activity class. It sets content to main.xml, which includes a button btn . When this button is clicked, content is set to pic.xml, which has two buttons, btn1 and btn2. When btn1 is clicked, it should set the content back to main.xml but this is not happening.
package com.asin.amit;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
public class AsinActivity extends Activity {
/** Called when the activity is first created. */
private TextView tv ;
private VideoView myVideoView;
private Button btn;
private Button btn1;
private Button btn2;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.b);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
String str= "/sdcard/DCIM/a.mp4";
tv = (TextView) findViewById(R.id.tv1);
myVideoView = (VideoView)findViewById(R.id.myvideoview);
myVideoView.setVideoPath(str);
myVideoView.setMediaController(new MediaController(this));
myVideoView.requestFocus();
myVideoView.start();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myVideoView.pause();
setContentView(R.layout.pic);
}
});
btn1.setOnClickListener(new ButtonListener());
}
catch (Exception e) {
// handle any errors
Log.e("HelloWorld", "1", e); // log the error
// Also let the user know something went wrong
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
class ButtonListener implements View.OnClickListener{
@Override
public void onClick(View v) {
setContentView(R.layout.main);
}
}
}
At the line btn1.setOnClickListener(new ButtonListener()); , logcat is saying java.lang.NullPointerException
What wrong am I doing ?
According to what you have written,
When this button is clicked, content is set to pic.xml, which has two buttons, btn1 and btn2your btn1 and btn2 are located in R.layout.pic, but your are trying to find them in R.layout.main layout bybtn1 = (Button) findViewById(R.id.button1);btn2 = (Button) findViewById(R.id.button2);You should set values to btn1 and btn2 variables (and onClickListener of course too) only after
setContentView(R.layout.pic), cause only then your layout will contain these buttons