Hi,
i am developing an Android application and i'm facing a curious bug :
a button can randomly take the action of another button.
when i touch a button to open a page, suddenly the menu opens !
I have check all button and their actions (some are configured in the xml layout with the onclick property and others from the Activity with the OnClickListener)
Anyone have an idea to solve the bug ?
Thanks
Yes, read this guide:
http://forum.xda-developers.com/showthread.php?t=2325164
Zatta said:
Yes, read this guide:
http://forum.xda-developers.com/showthread.php?t=2325164
Click to expand...
Click to collapse
Thank you for the link.
No error is logged. It appears to be the normal behavior. But actions are correctly set.
I have never had this problem in any of my apps. If you want to post some of your code. (button definition in your xml and your button click event), they it would be easier to help out.
zalez said:
I have never had this problem in any of my apps. If you want to post some of your code. (button definition in your xml and your button click event), they it would be easier to help out.
Click to expand...
Click to collapse
Menu item button definition :
Code:
<ImageButton
android:id="@+id/menu_button_accueil"
style="@style/fitImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:onClick="onClickMenuItem"
android:src="@drawable/menu_button_accueil" />
<ImageButton
android:id="@+id/menu_button_magasin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:adjustViewBounds="true"
android:background="@null"
android:onClick="onClickMenuItem"
android:scaleType="centerInside"
android:src="@drawable/menu_button_magasin" />
<ImageButton
android:id="@+id/menu_button_carnet_mode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:adjustViewBounds="true"
android:background="@null"
android:onClick="onClickMenuItem"
android:scaleType="centerInside"
android:src="@drawable/menu_button_carnet_mode" />
Menu button toggle definition
Code:
<Button
android:id="@+id/menu_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:background="@drawable/menu_button" />
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
mSlideHolder = (SlideHolder) findViewById(R.id.slideHolder);
mSlideHolder.setDirection(SlideHolder.DIRECTION_RIGHT);
mSlideHolder.setEnabled(false);
menuButton = (Button) findViewById(R.id.menu_button);
menuButton.setOnClickListener(this);
}
[user=439709]@override[/user]
public void onClick(View v) {
Log.d("MainActivity", "toggle menu");
mSlideHolder.toggle();
}
Code:
public void onClickMenuItem(int id) {
Intent i = null;
if(id == currentPage) {
mSlideHolder.toggle();
return;
}
switch(id) {
case R.id.menu_button_accueil:
i = new Intent(MainActivity.this, HomeActivity.class);
break;
case R.id.menu_button_magasin:
i = new Intent(MainActivity.this, MagasinActivity.class);
break;
case R.id.menu_button_carnet_mode:
i = new Intent(MainActivity.this, CarnetModeActivity.class);
break;
case R.id.menu_button_videos:
i = new Intent(MainActivity.this, VideosActivity.class);
break;
case R.id.menu_button_alertes:
i = new Intent(MainActivity.this, AlertesActivity.class);
break;
case R.id.menu_button_aide:
i = new Intent(MainActivity.this, AideActivity.class);
break;
case R.id.menu_button_mentions:
i = new Intent(MainActivity.this, MentionsActivity.class);
break;
default:
Log.d("MainActivity", "not a value in switch");
break;
}
if(i != null) {
MainActivity.currentPage = id;
startActivity(i);
// if(id != R.id.menu_button_accueil)
// finish();
}
else
Log.e("MainActivity", "intent null !!");
}
public void onClickMenuItem(View v) {
this.onClickMenuItem(v.getId());
}
Related
Is there a way to get the entire surfaceView screen to function like a button which start/atop a video recording process whenever it sees fit by the user? The function is somewhat similar to youTube's start/stop play function but instead this time it is used to start/stop the video recording process.
Is the code suppose to be coded in the .xml file or my .java file to accomplish the task? Sorry i'm rather new to android/java and given only 6 more weeks to finish this assignment by my lecturer to complete an app which act like a car blackbox yet i'm a total beginner in programming... Any help would be appreciated... Thanks in advance...
This is what i tried so far, can someone guide me i'm really in a desperate situation, PLEASE HELP ME :'(
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My serviceRecording.java file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
private boolean RecordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
RecordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (RecordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
RecordingStatus = false;
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.unlock();
}
catch(Exception e){
ServiceCamera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
RecordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
ServiceCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
RecordingStatus = false;
}
}
My .xml file
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:text="Video"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Button>
<Button
android:text="Setting"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
></Button>
<Button
android:text="Back"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
></Button>
<Button
android:text="Start"
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
></Button>
<Button
android:text="Stop"
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
></Button>
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="480dp"
android:layout_height="320dp"
android:layout_toRightOf="@+id/button2"
></SurfaceView>
<TextView
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/button2"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
></TextView>
</RelativeLayout>
</FrameLayout>
someone answer me please, i really need your guys help...
why isn't someone answering is my question so unwelcoming?
Haiz can anyone help me, i really need some guidance and help here...
You want to
Code:
implement OnClickListener
add method
Code:
onClick(View v)
then you want to add
Code:
surfaceView.setOnClickListener(this);
When surface is clicked onClick is called
By any chance could you explain how should i implement the above said functions into my codes because like implement onclicklistener and this and that i don't quite understand where should i place these above codes??
And how should this above function handle my startService and stopService intents? Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked? Could you guide me in this in much more details, sorry if i'm kinna stupid to understand your explanations...
Ok
CameraTest.java
Add
Code:
public void onClick(View v){
}
Replace
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
with
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback, OnClickListener {
After
Code:
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
Add
Code:
surfaceView.setOnClickListener(this);
how should this above function handle my startService and stopService intents?
Click to expand...
Click to collapse
Your intent function calls the CameraTest.surfaceView so everything will work with whatever code you put in the onClick function.
Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked?
Click to expand...
Click to collapse
Need better explanation on what you are asking.
The last part is probably like how when you tap a YouTube video on the video itself it kinda flashes the play or pause button over the video.
Sent from my MIUI SCH-i500
Which of these should i import?
Code:
import android.content.DialogInterface.OnClickListener;
import android.view.View.OnClickListener;
Should i put startService and stopService intent together, but it seems not appropriate as both statement seems to conflict each other when i click to start/stop my service? Or i need add some sort of if.. else logic statement to differentiate the start/stop service alternating when being clicked?
Code:
public void onClick(View v){
startService(new Intent(getApplicationContext(), ServiceRecording.class));
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
Yes that was what i meant for the last part of my question the sort of effect it will display when being clicked, sorry if i could not explain well which might cause you some confusion.. Thanks for your help
Or should i be implementing some sort of imagebutton to emulate the above effect i mention or is there some other way to do it?
Can someone answer me??
Can someone please guide me on my above problem to get the result similar to what was like youtube??
Hello,
I have a project in which an object moves by tapping it on a scrolling background, I can not despite my best efforts to resolve a problem, the screen remains blank after the screenshot
this is my xml
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LayoutRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>
java
Code:
public class MainActivity extends Activity {
BallBounces ball;
File imageFile;
public RelativeLayout CamView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CamView =(RelativeLayout) findViewById(R.id.LayoutRoot);
ball = new BallBounces(this);
setContentView(ball);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.Menu:
//newGame();
case R.id.screenshot:
//showHelp();
TakeScreenshot();
// ScreenshotCapture();
Context context=getApplicationContext();
CharSequence text="screenshot";
int duration=Toast.LENGTH_LONG;
Toast toast=Toast.makeText(context, text, duration);
toast.show();
return true;
case R.id.About:
//showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void TakeScreenshot()
{
Random num = new Random();
int nu=num.nextInt(1000);
CamView.setDrawingCacheEnabled(true);
CamView.buildDrawingCache(true);
Bitmap bmp = Bitmap.createBitmap(CamView.getDrawingCache()); // Here i have null!
CamView.setDrawingCacheEnabled(false); // clear drawing cache
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId=String.valueOf(nu);
String myfile="Ghost"+picId+".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory()+File.separator+"ImageTouch");
dir_image.mkdirs();
try {
File tmpFile = new File(dir_image,myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0)
{
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
"Saved",Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
I tried in every way but I can not get out
Someone can give me a hand?
Thanks
The problem is that with a surface view, the getDrawingCache() method always returns null or a black bitmap...
I got it working in my app by creating a new Canvas with the same size as your surface view and then call surfaceView.onDraw(canvas), passing the new one. You can then write it to a file via its bitmap.
And remember, depending on how intense your onDraw method is you may need to do the saving in an Async task.
Hi guys I have a problem with the cool lib from nhaarman
I integrated successfully his lib with an activity extends ListActivity
Code:
public class MainActivity extends ListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setDivider(null);
MyAdapter adapter = new MyAdapter();
//setListAdapter(adapter);
ScaleInAnimationAdapter swingRightInAnimationAdapter = new ScaleInAnimationAdapter(adapter);
swingRightInAnimationAdapter.setAbsListView(getListView());
setListAdapter(swingRightInAnimationAdapter);
for(int i = 0 ; i<10; i++)
{
adapter.add("task" + String.valueOf(i));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyAdapter extends ArrayAdapter<String>
{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = (TextView) convertView;
if (tv == null) {
tv = new TextView(MainActivity.this);
}
tv.setText(getItem(position));
return tv;
}
}
}
This code above is working fine. The list_rows are fading in the screen.
But now I want to integrate this lib into a fragment with a listview within:
Code:
public class FragmentTask extends Fragment{
ListView listView;
MyAdapter adapter;
View view;
public FragmentTask() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(new Exception().getStackTrace()[0].getClassName(), new Exception().getStackTrace()[0].getMethodName());
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_tasks, container, false);
Button button = (Button) view.findViewById(R.id.btn_newTask);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("task");
adapter.notifyDataSetChanged();
}
});
listView = (ListView) view.findViewById(R.id.taskListView);
listView.setDivider(null);
adapter = new MyAdapter(view.getContext());
ScaleInAnimationAdapter swingRightInAnimationAdapter = new ScaleInAnimationAdapter(adapter);
swingRightInAnimationAdapter.setAbsListView(listView);
listView.setAdapter(swingRightInAnimationAdapter);
return view;
}
private class MyAdapter extends ArrayAdapter<String>
{
Context context;
private MyAdapter(Context context) {
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_row,parent, false);
TextView title = (TextView) row.findViewById(R.id.textView);
title.setText(getItem(position));
return row;
}
}
}
Now I have the effect that the rows only fade in if i "spam" new rows so that I have to scroll down. So the list items which were hided appear now with the fade-effect. But the other list items which have room in the listview without scrolling are not fading.
Do you understand me?
Please help me
edit: here is my fragment_tasks.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout .....">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Task"
android:id="@+id/btn_newTask"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/taskListView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/btn_newTask"
/>
</RelativeLayout>
Hello there
I got 2 problems:
Firstly, if I launch the following code on my device, I'm getting a nullpointer, and I got no idea why. ( I know it's sorta basic stuff)
Secondly, I want toset the screen height and lenght to wrap_content, it's red marked in the code...that is also not working..
Could you maybe help out a noob?
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
int y = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
For the wrap_content one, you need to set that property to the view that holds the integer text, you can't set a height and width properties to an integer, only a view or other widgets such as buttons. So for you you should set the properties of the view with ID start_time to wrap_content for width and height - recommend doing this in the layout XML instead of java code.
I'm guessing that if you sort that out your null pointer will disappear.
Additionally in your public onClick(View v) method you should check the ID of the view before doing any function code, this means you can have multiple objects using the same listener.
So this:
Code:
@Override
public void onClick(View v) {
Random r = new Random();
... etc
Should become this:
Code:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_time:
Random r = new Random();
... etc
tahnks @Jonny for your answer, I changed the code, but now, my button isn't placed randomly on each click anymore, and I'm getting the nullpointer again. have a look:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(+1);
int y = r.nextInt(+1);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.wrap_content);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the xml
Code:
<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"
android:clickable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.asddd.af.Game" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
thank you. I'm really happy, there exists such great help
i have now changed the view start_time to a button...because it actually IS a button (im stupid) but now, when I click on the button, it moves completely out of the screen, and if not, instead of getting the time, the app stopps again with nullpointer. It should stay in the screen, placed randomly on click and after some clicks, I want to recieve the elapsed time. what is this?
code:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(R.id.wrap_content);
int y = r.nextInt(R.id.wrap_content);
long startTime = SystemClock.elapsedRealtime();
i++;
Button b = (Button) findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the xml:
Code:
<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"
android:clickable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="chdfss.dsfwegg.trhhGame" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</View>
</RelativeLayout>
I'm not familiar with the nextInt() function (I can look it upp later when I'm home) but I'm pretty sure you shouldn't be parsing a views ID as one of its conditions - eg you're doing nextInt(R.id.wrap_content), are you sure that's right?
HEY friends i want help in coding... i want to do simple task.. for eg. "A×25=B" in that task A is edit text number 25 is fix number n B is textview(out put) i want to do this task with out any button... just on edit start at"A" the result shown in "B"... if A change than B is change... sorry m new to coding soooo plz plz plz help me.... which activity or which method i have to follow???
kishnachauhan said:
HEY friends i want help in coding... i want to do simple task.. for eg. "A×25=B" in that task A is edit text number 25 is fix number n B is textview(out put) i want to do this task with out any button... just on edit start at"A" the result shown in "B"... if A change than B is change... sorry m new to coding soooo plz plz plz help me.... which activity or which method i have to follow???
Click to expand...
Click to collapse
Easy I think, I am also a newbie but got this in my mind use this. Create a method.
private addition(){
if(a!=0){
b=a+25;
textview2.settext(b);
}
}
Don't know if its right, just try.
I did this code for you, it works perfectly and there isn't button :good:
Your main activity:
Code:
public class Main extends Activity {
EditText editTextA;
TextView textViewB;
long A, B;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextA = (EditText) findViewById(R.id.editText1);
textViewB = (TextView) findViewById(R.id.textView1);
editTextA.addTextChangedListener(new TextWatcher() { // Add listener to EditText
public void afterTextChanged(Editable s) {
if(!editTextA.getText().toString().equals("")) { // If EditText isn't blank
A = Long.parseLong(editTextA.getText().toString()); // Get number of EditText
B = A * 25; // Task
textViewB.setText("" + B); // Set result to TextView
}
else
textViewB.setText("");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
}
Add this in your layout, inside a RelativeLayout (main.xml):
Code:
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:gravity="center" />