setOnSeekBarChangeListener NullPointerException android - android

class PlayAreaView extends View{
private static final String DEBUG_TAG = "PlayAreaView";
private SeekBar sizeSlider;
private int xMin = 0;
private int xMax;
private int yMin = 0;
private int yMax;
private Rect rect;
private GestureDetector gestures;
private Paint p = new Paint();
private int side = 50;
public PlayAreaView(Context context){
super(context);
rect = new Rect(0,0,side,side);
p.setARGB(255, 255, 255, 255);
GestureListener listener = new GestureListener(this);
gestures = new GestureDetector(listener);
sizeSlider = (SeekBar) findViewById(R.id.seek);
//sizeSlider.setOnSeekBarChangeListener(listener);
}
I am new to developing on Android and am having trouble figuring out what is wrong here. I am getting a NullPointerException at the commented out line. I believe it is because I am asking to findViewById in a class that is not the main activity. If this is indeed the problem how can I access UI elements from this class.

As you have set up, findViewById(R.id.seek) will search for a subview with ID equal to R.id.seek within PlayAreaView, which does not exist since you seem to have the SeekBar in your main layout.
If you must access The SeekBar from within this view, pass in a reference to it while instantiating it, e.g., in the main activity
SeekBar sizeSlider = (SeekBar)findViewById(R.id.seek);
PlayAreaView areaView = new PlayAreaView(this, sizeSlider);
and in PlayAreaView,
SeekBar sizeSlider;
public PlayAreaView(Context context, SeekBar seekBar) {
super(context);
sizeSlider = seekBar;
...
seekBar.setOnSeekBarChangeListener(...);
}
then, the SeekBar instance can be accessed through the instance variable sizeSlider from PlaAreaView.

Related

android: How to draw on a canvas of a view from another customized class?

I will be very grateful is somebody can help.
I have created a grid of views with a TableLayout in my xml file.
In the corresponding java file, I retrieve the id of all views in an array view.
I have another class which receive in its constructor a reference to an above created view, in order to draw on its canvas.
public class Mosaique extends Activity {
Box [][]box = new Box[NL][NC];
View [][] boxMosaique = new View[NL][NC];
//...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mosaique);
boxMosaique[0][0] = findViewById(R.id.b_00);
boxMosaique[0][1] = findViewById(R.id.b_01);
boxMosaique[0][2] = findViewById(R.id.b_02);
//…
for (int lig=0;lig<NL;lig++)
for(int col=0;col<NC;col++)
box[lig][col] = new Box(boxMosaique[lig][col], bckgrnd_color, lig,col);
}
//...
}
// The constructor of the another class which access the views for drawing
public Box(View aView, int backGroundColor, int lig, int col){
this.aView = aView;
this.lig = lig;
this.col = col;
this.backGroundColor = backGroundColor;
// How to access the canvas of aView for drawing ?
}
I would recommend writing Box class as View.
Box extends View{
float lig;
float col;
Clolr backGroundColor;
...
#Override
protected void onDraw(Canvas canvas) {
//draw here on canvas
...
}
public drawBox(int backGroundColor, int lig, int col){
this.aView = aView;
this.lig = lig;
this.col = col;
this.backGroundColor = backGroundColor;
invalidate()
}
instead of adding constructors, add a method to set box values and call invalidate() once the values are set.

Can't animate Custom View

I was creating my textview which use as a header in my MainActivity file and everything was okay until I thought I'd better move the code to another class.
While it works and displays the text however when I try to animate it it doesn't work.
The code I was using is in the init() method.
The code is very simple and I'm pasting it here:
public class TextViewHeader extends TextView {
private static final String TAG = "TextViewHeader".toUpperCase();
private Context context;
private FrameLayout frameLayoutWhiteTowerContainer;
private String text;
private int whiteTowerContainerHeight;
private int tower_height;
public TextViewHeader(Context context) {
super(context);
}
public TextViewHeader(Context context, String text, FrameLayout frameLayoutWhiteTowerContainer,
int whiteTowerContainerHeight, int tower_height) {
super(context);
this.context = context;
this.text = text;
this.frameLayoutWhiteTowerContainer = frameLayoutWhiteTowerContainer;
this.whiteTowerContainerHeight = whiteTowerContainerHeight;
this.tower_height = tower_height;
init();
}
public TextViewHeader(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init() {
TextView textView = new TextView(context);
textView.setText(text);
textView.setTextSize(25);
textView.setTextColor(Color.parseColor("#FF545454"));
Typeface typefaceCondensed = Typeface.create("sans-serif-condensed", Typeface.BOLD);
textView.setTypeface(typefaceCondensed);
FrameLayout.LayoutParams tv_header_params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
int topMargin = whiteTowerContainerHeight / 2 - tower_height / 2 - 100;
tv_header_params.topMargin = topMargin;
tv_header_params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(tv_header_params);
frameLayoutWhiteTowerContainer.addView(textView, tv_header_params);
}
}
The code in MainActivity is :
tvHeader = new TextViewHeader(MainActivity.this, "TOWER", flWhiteTowerContainer,
whiteTowerContainerHeight, tower_height ); // create inside onCreate method
tvHeader.animate().y(515).setDuration(1500).start(); //and the animation happens later onMapReady
You are starting an animation before the TextViewHeader is laid out.
Try:
tvHeader = new TextViewHeader(MainActivity.this, "TOWER", flWhiteTowerContainer,
whiteTowerContainerHeight, tower_height );
tvHeader.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
// Layout complete but not drawn yet
tvHeader.getViewTreeObserver().removeOnPreDrawListener(this);
tvHeader.animate().y(515).setDuration(1500).start();
return false;
}
});
The problem is that I'm implementing the TextView but I don't use it. Instead I just create another TextView in the class and I use this instead of my class.
In other words the code :
TextView textView = new TextView(context);
shouldn't exist and just use this to setText, setTextSize, color, etc.
this.setText(text);
this.setTextSize(25);
this.setTextColor(Color.parseColor("#FF545454"));

ScrollView with a SurfaceView

Currently I have a custom SurfaceView for a specific size of Panels that I used for my project. But I'm looking into expanding it hence I need a ScrollView to scroll it accordingly. But I'm not sure how do I merge the 2 together.
My SurfaceView is using a .java file to create its layout. It is not using .xml to create the layout.
//MySurfaceView.class
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback , Runnable{
private SurfaceHolder surfaceHolder;
private boolean isDestroyed = false;
private Canvas canvas;
private Paint paint;
private int maxWidth;
private int maxHeight;
private Resources resources;
int offset;
final byte ON=1;
final byte OFF=0;
int[] ledPositionControl = new int[97];
int ledBmpSize;
int positionControlSize;
int maxControl=96;
int sizeControl=0;
int row;
int col;
public MySurfaceView(Context context) {
super(context);
resources = context.getResources();
init(); //load pictures
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
paint =new Paint();
}
This is the class that runs the SurfaceView.
//Class that runs the SurfaceView Layout
public class drawingMode extends Activity implements OnClickListener {
public static int screenWidth;
public static int screenHeight;
private SharedPreferences sPrefs;
final byte ON = 1;
final byte OFF = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(new MySurfaceView(this));
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
screenWidth = metric.widthPixels;
screenHeight = metric.heightPixels;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Now how do I merge this SurfaceView into a ScrollView Layout? I have a .xml file that has a ScrollView inside but I tried to put the SurfaceView via tag wise through .xml but it didn't worked. I also tried the .addView and it didn't work too gave me some errors.
//I put this in a the onCreate of a class.
myScrollView = new ScrollView(getApplicationContext());
myScrollView.addView(new MySurfaceView(this));
setContentView(R.layout.scrollsurfaceview);
Firstly, you didn't specify LayoutParams. Secondly, you had a wrong setContentView. The best way is to place ScrollView in layout.xml. If you rather prefer to do in in the code, here is a hint:
ScrollView myScrollView = new ScrollView(this);
myScrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, MATCH_PARENT));
MySurfaceView myView = new MySurfaceView(this);
myView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, myHeight));
myScrollView.addView(myView);
setContentView(myScrollView); // !!!!!!

Android: Adding text to a View

I'm trying to add a text element to a view that's been created. I've found some answers online, but haven't been able to tailor them. I'm using the TouchPaint example code. Every-time I run the app with the text element, the app fails. Would appreciate some help.
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and attach the view that is responsible for painting.
mView = new MyView(this);
setContentView(mView);
mView.requestFocus();
TextView tvX= (TextView)findViewById(R.id.pointSize);
tvX.setText("TestText");
// Restore the fading option if we are being thawed from a
// previously saved state. Note that we are not currently remembering
// the contents of the bitmap.
mFading = savedInstanceState != null ? savedInstanceState.getBoolean("fading", true) : true;
}
View class
public class MyView extends View {
private static final int FADE_ALPHA = 0x06;
private static final int MAX_FADE_STEPS = 256/FADE_ALPHA + 4;
private Bitmap mBitmap;k
private Canvas mCanvas;
private final Rect mRect = new Rect();
private final Paint mPaint;
private final Paint mFadePaint;
private boolean mCurDown;
private int mCurX;
private int mCurY;
private float mCurPressure;
private float mCurSize;
private int mCurWidth;
private int mFadeSteps = MAX_FADE_STEPS;
public MyView(Context c) {
super(c);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setARGB(255, 255, 255, 255);
mFadePaint = new Paint();
mFadePaint.setDither(true);
mFadePaint.setARGB(FADE_ALPHA, 0, 0, 0);
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:id="#+id/pointSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#FF0000"
android:visibility="visible" />
</RelativeLayout>
Try this:
LinearLayout lv = new LinearLayout(this);
tvX.setText("TestText");
lv .addView(tvX);
setContentView(lv);

Android - How to define value by call seekbar method?

I'm trying to set a value by calling the method from seekbar.
I call the method getProgress() and it crashes the app.
I'm doing it in a activity that extends View.
The seekbar values are set on the MainActivity.
public class Draw extends View
{
public Draw(Context context)
{
super(context);
}
Paint prop = new Paint();
Random color = new Random();
SeekBar bar = (SeekBar) findViewById(R.id.skbContrast);
int value = bar.getProgress();// it crashes here
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int oriwidth = 0;
int oriheight = 0;
for (int x = 0; x < 20; x++)
{
int red = color.nextInt(value);
int green = color.nextInt(value);
int blue = color.nextInt(value);
prop.setARGB(255, red, green, blue);
canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10, height -= 10, prop);
}
}
}
Any help? Thanks, and sorry for the english.
SeekBar bar = (SeekBar) findViewById(R.id.skbContrast);
This will return null when you try to reference it into View.
Rather you should take following approach.
move below statements to your Activity.
SeekBar bar = (SeekBar) findViewById(R.id.skbContrast);
int value = bar.getProgress();
Create a method into your view class.
public void setSeekBarValue(long seekBarValue)
{
this.seekBarValue=seekBarValue;
}
And from MainActivity whenever you want to pass the values to view write following snippet.
SeekBar bar = (SeekBar) findViewById(R.id.skbContrast);
int value = bar.getProgress();
viewObject.setSeekBarValue(value);
This is not the fullproof solution just an idea to help you get started.

Categories

Resources