Hey All,
I've fixed quite some bugs, annoyances and crashes in our Android App and so far it looks good but a new crash has appeared which didn't occur before (probably because in the past it crashed before it even reached that point).
I tried to reproduce this crash on multiple different phones (Nexus 5, Nexus 4, Xiaomi Mi4C, Samsung Galaxy S5, HTC One A9 and A8) by rotating, switching tabs, turning screen off/on and switching tabs and rotating and so on but I just couldn't reproduce it .
Stacktrace:
Code:
java.lang.IllegalStateException: No host
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1194)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1189)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(SourceFile:2001)
at android.support.v4.app.Fragment.performActivityCreated(SourceFile:1976)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1051)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1207)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1189)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(SourceFile:2001)
at android.support.v4.app.Fragment.performActivityCreated(SourceFile:1976)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1051)
at android.support.v4.app.FragmentManagerImpl.attachFragment(SourceFile:1385)
at android.support.v4.app.BackStackRecord.run(SourceFile:728)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(SourceFile:1572)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(SourceFile:545)
at myPackageName.FragmentTabsActivity$TabManager.onTabChanged(SourceFile:183)
at android.widget.TabHost.invokeOnTabChangeListener(TabHost.java:468)
at android.widget.TabHost.setCurrentTab(TabHost.java:447)
at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:170)
at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:550)
at android.view.View.performClick(View.java:5106)
at android.view.View$PerformClick.run(View.java:20329)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5912)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
FragmentTabsActivity manifest entry:
Code:
<activity
android:name="myPackageName.FragmentTabsActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
onTabChanged implementation from FragmentTabsActivity (I left a bit more than what is probably needed):
Code:
public static class TabManager implements TabHost.OnTabChangeListener {
private final FragmentActivity mActivity;
private final TabHost mTabHost;
private final int mContainerId;
private final Map<String, TabInfo> mTabs= new HashMap<String, TabInfo>();
TabInfo mLastTab;
static final class TabInfo {
private final String mTag;
private final Class<?> mClss;
private final Bundle mArgs;
private Fragment mFragment;
TabInfo(String tag, Class<?> clazz, Bundle args) {
mTag= tag;
mClss= clazz;
mArgs= args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext= context;
}
@Override
public View createTabContent(String tag) {
View v= new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
mActivity= activity;
mTabHost= tabHost;
mContainerId= containerId;
mTabHost.setOnTabChangedListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mActivity));
String tag= tabSpec.getTag();
TabInfo info= new TabInfo(tag, clss, args);
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
info.mFragment= mActivity.getSupportFragmentManager().findFragmentByTag(tag);
if (info.mFragment != null && !info.mFragment.isDetached()) {
FragmentTransaction ft= mActivity.getSupportFragmentManager().beginTransaction();
ft.detach(info.mFragment);
ft.commitAllowingStateLoss();
}
mTabs.put(tag, info);
mTabHost.addTab(tabSpec);
}
@Override
public void onTabChanged(String tabId) {
TabInfo newTab= mTabs.get(tabId);
if (mLastTab != newTab) {
FragmentTransaction ft= mActivity.getSupportFragmentManager().beginTransaction();
if (mLastTab != null) {
if (mLastTab.mFragment != null) {
ft.detach(mLastTab.mFragment);
}
}
if (newTab != null) {
if (newTab.mFragment == null) {
newTab.mFragment= Fragment.instantiate(mActivity, newTab.mClss.getName(), newTab.mArgs);
ft.add(mContainerId, newTab.mFragment, newTab.mTag);
} else {
ft.attach(newTab.mFragment);
}
}
if (newTab.mFragment != null && newTab.mFragment instanceof MyMapFragment) {
MyMapFragment mapFragment= (MyMapFragment) newTab.mFragment;
mapFragment.clearBundleOnTabChange();
}
if (mLastTab != null && mLastTab.mFragment != null && mLastTab.mFragment instanceof MyMapFragment) {
MyMapFragment mapFragment= (MyMapFragment) mLastTab.mFragment;
mapFragment.clearBundleOnTabChange();
}
mLastTab= newTab;
ft.commitAllowingStateLoss();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
}
FragmentTabsActivity is hosting 3 tabs where as every tab has one assigned Fragment.
If anyone knows how to reproduce/solve this I would be really happy about an answer. I've already found 2 or 3 possible solutions while googling but without being able to test which one actually solves my problem I feel uncomfortable :/
If needed and if it helps I can also add and describe the lifecycle of the FragmentTabsActivity and the hosted fragments
No ideas?
Related
Hi Community,
I have problems with the ACTION_MEDIA_BUTTON - Intent. I can't get my App receiving those actions and react on them.
In my AndroidManifest.xml I added the Intent-filter:
Code:
<intent-filter android:priority="42">
<action android:name="android.intent.action.MEDIA_BUTTON">
</intent-filter>
And in the onCreate-Method I registered a Receiver:
Code:
BroadcastReceiver receiver;
if (receiver == null) {
receiver = new ButtonReceiver();
}
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(receiver, filter);
And the corresponding ButtonReceiver-class:
Code:
class ButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
String intentAction = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction))
{
Log.d("ButtonReceiver", "I will handle buttons here");
//handle buttons
}
}
}
The app compiles fine and is also running without problems, BUT I never get to the "//handle buttons"-section.
For testing purpose I'm using my Jabra BT2015 and the provided earphones from HTC. Both don't work.
Every hint is very appreciated.
Greez
LordAlien
i have a problem with ListView, i don't view line separator for each item, why ? see where is mouse pointer:
h_t_t_p://tinyurl.com/2vqg52n
and this is source code:
Java Class:
Code:
public class ScienzeInfoNewsActivity extends Activity {
private class Link {
private String title;
private String href;
public Link(String title, String href) {
this.title = title;
this.href = href;
}
public String toString() {
return title;
}
public String getHref() {
return href;
}
}
private FeedReader feedReader;
private ArrayAdapter<Link> adapter;
private ListView list;
public void initialize() {
adapter = new ArrayAdapter<Link>(this, R.layout.textview);
list = (ListView) findViewById(R.id.ListView01);
list.setAdapter(adapter);
}
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
loadFeeds(adapter);
setAllListener();
}
private void setAllListener() {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String link = adapter.getItem((int) id).getHref();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);
}
});
Button exit = (Button) findViewById(R.id.Button02);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ScienzeInfoNewsActivity.this.finish();
}
});
Button refresh = (Button) findViewById(R.id.Button01);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
loadFeeds(adapter);
}
});
}
private void loadFeeds(ArrayAdapter<Link> adapter) {
if (adapter != null)
adapter.clear();
try {
feedReader = new FeedReader(new URL(
"rss.php"));
String feeds[][] = feedReader.getFeeds();
for (int i = 0; i < feeds.length; i++) {
adapter.add(new Link(feeds[i][0], feeds[i][1]));
}
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
R.layout.textview:
Code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="h_t_t_p://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I load entry item with this function loadFeeds()
If i select one of the items without a separator, it just one item.
Thanks for any reply.
First of all, this is my first post here so hello everyone.
I'm writing an app that requires displaying a semi-transparent PNG layer over a camera preview. Everything was fine until I wanted to publish it and make sure it works also on Android 2.x. It seems that on older versions of Android, the camera preview causes the drawable (in my case, a subclass of ImageView) to not show. The whole screen is white, but the buttons are visible. When I get rid of the preview, it works just fine - the drawable is visible as it should. It works like this both on the emulator and on real devices.
Here is my code (the whole project is in the attachment). The most interesting and probably guilty class is CameraPreview. The code doesn't crash, there's also no exceptions or other behavior like this.
MainActivity.java
Code:
public class MainActivity extends Activity
{
CameraPreview mPreview;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mPreview = (CameraPreview)this.findViewById(R.id.cameraPreview);
}
[user=439709]@override[/user]
protected void onResume()
{
super.onResume();
mPreview.resume();
}
[user=439709]@override[/user]
protected void onPause()
{
super.onPause();
mPreview.pause();
}
}
CameraPreview.java
Code:
class CameraPreview extends ViewGroup implements SurfaceHolder.Callback
{
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Context mContext;
int currentCamera = 0;
int noOfCameras = 0;
public CameraPreview(Context context)
{
super(context);
}
[user=1299008]@supp[/user]ressLint("NewApi")
[user=1299008]@supp[/user]ressWarnings("deprecation")
public CameraPreview(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
mContext = context;
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// checking what cameras we have
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO)
{
noOfCameras = Camera.getNumberOfCameras();
CameraInfo cameraInfo = new CameraInfo();
for(int i=0; i<noOfCameras; i++)
{
Camera.getCameraInfo(i, cameraInfo);
if(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK)
{
currentCamera = i;
break;
}
}
}
}
public CameraPreview(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public void setCamera(Camera camera)
{
if(mCamera != null && camera == null)
mCamera.release();
mCamera = camera;
if(mCamera != null)
{
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
[user=439709]@override[/user]
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if(mSupportedPreviewSizes != null)
mPreviewSize = getOptimalPreviewSize(width, height);
}
[user=439709]@override[/user]
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
if(changed && getChildCount() > 0)
{
final View child = mSurfaceView;
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if(mPreviewSize != null)
{
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight)/2, width, (height + scaledChildHeight) / 2);
}
}
public void surfaceCreated(SurfaceHolder holder)
{
try
{
if(mCamera != null)
mCamera.setPreviewDisplay(holder);
}
catch(IOException exception)
{
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
if(mCamera != null)
mCamera.stopPreview();
}
// Chooses such preview's size that it just one "step" wider
// than needed. This ensures sharpness of the preview.
private Size getOptimalPreviewSize(int w, int h)
{
Size optimalSize = null;
int optimalWidth = 0;
for(Size size : mSupportedPreviewSizes)
{
if(size.width > optimalWidth)
{
optimalSize = size;
if(size.width >= w)
break;
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
public void resume()
{
setCamera(Camera.open());
}
public void pause()
{
setCamera(null);
}
}
CustomImageView.java
Code:
// aligns the content image to the top
public class CustomImageView extends ImageView
{
public CustomImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
[user=439709]@override[/user]
protected boolean setFrame(int l, int t, int r, int b)
{
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth()/(float)getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
}
activity_main.xml
Code:
<FrameLayout xmlns:android="h t t p:// schemas.android.com /apk/res/android"
xmlns:tools="h t t p:/ /schemas.android.com /tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity"
android:background="#ffe9eaed" >
<com.example.drawabletest.CameraPreview
android:id="@+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FFFF" />
<com.example.drawabletest.CustomImageView
android:id="@+id/fbTemplate"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:src="@drawable/template2" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</FrameLayout>
Also, I'm not sure why the preview itself doesn't work. I've read that on Android 2.x emulators, the test image from the emulated camera is just this plain white by design, so I assumed it's ok. However, my friend tested the app on his phone with Android 2.3 and the preview appeared to be plain black. I guess it's a subject for a separate question, but maybe you'll notice something in the code.
I've spent a few days now to solve these two problems, so any clues would be really helpful. Thank you!
First of all, welcome to the forum.
Please do it as described here: http://forum.xda-developers.com/showthread.php?t=2439748
Post the code within
Code:
tags in the thread. Makes it easier for us. ;)
That way you'd get much more help (maybe from me ;)).
Could you provide at least a working example of camera preview for Android 2.x? I don't believe it can't be done. Does it need some kind of deprecated API to work correctly?
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.
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?