Useful code snippets - Java for Android App Development

Here are few useful code snippets to help android app developers.
How to get CPU architecture:
This could be useful when you include native libraries or binaries with your app to determine what CPU architecture device is.
Code:
public static String getAbi(){
String abi = android.os.Build.CPU_ABI;
if(abi.contains("armeabi")){
return "arm";
}
else if(abi.contains("x86")){
return "x86";
}
else if(abi.contains("mips")){
return "mips";
}
else{
return "arm";
}
}
It returns arm if CPU its not any these three, which might be wrong, but it works for me so...
Convert size in byte to Human Readable String
Code:
public static String byteToHumanReadableSize(long size)
{
String hrSize = "";
long b = size;
double k = size / 1024.0;
double m = size / 1048576.0;
double g = size / 1073741824.0;
double t = size / 1099511627776.0;
DecimalFormat dec = new DecimalFormat("0.00");
if (t > 1)
{
hrSize = dec.format(t).concat("TB");
}
else if (g > 1)
{
hrSize = dec.format(g).concat("GB");
}
else if (m > 1)
{
hrSize = dec.format(m).concat("MB");
}
else if (k > 1)
{
hrSize = dec.format(k).concat("KB");
}
else if (b > 1)
{
hrSize = dec.format(b).concat("B");
}
return hrSize;
}
Get free/total/used memory on SD and internal storage.
Code:
public static long getAvailableSpaceInBytesOnInternalStorage()
{
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availableSpace;
}
public static long getUsedSpaceInBytesOnInternalStorage()
{
long usedSpace = -1L;
StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
usedSpace = ((long) stat.getBlockCount() - stat.getAvailableBlocks())
* (long) stat.getBlockSize();
return usedSpace;
}
public static long getTotalSpaceInBytesOnInternalStorage()
{
long usedSpace = -1L;
StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
usedSpace = ((long) stat.getBlockCount()) * (long) stat.getBlockSize();
return usedSpace;
}
public static long getAvailableSpaceInBytesOnExternalStorage()
{
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
availableSpace = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availableSpace;
}
public static long getUsedSpaceInBytesOnExternalStorage()
{
long usedSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
usedSpace = ((long) stat.getBlockCount() - stat.getAvailableBlocks())
* (long) stat.getBlockSize();
return usedSpace;
}
public static long getTotalSpaceInBytesOnExternalStorage()
{
long usedSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
usedSpace = ((long) stat.getBlockCount()) * (long) stat.getBlockSize();
return usedSpace;
}
Basic stuff really, but it could be useful to some.
Please share if you have anything good
Sent from my Evo 3D GSM using Tapatalk 2

add Samsung MultiWindow support for your app
With this code snippet you can add multiwindow support for samsung devices.
open your AndroidManifest.xml.
Search for your main activity: (example)
Code:
<activity
android:name="com.myapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
and change it to:
Code:
<activity
android:name="com.myapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
</intent-filter>
</activity>
<uses-library
name="com.sec.android.app.multiwindow"
required="false" >
</uses-library>
For more examples and options see http://developer.samsung.com/androi...-Desk-Chapter-7-Applying-Multi-Window-Feature
(You can set max and min windowsize and so on.)

Very useful website that should be bookmarked: http://www.androidsnippets.com/

Split action bar to bottom on small screens:
Code:
android:uiOptions="splitActionBarWhenNarrow"
Pause app instead of exiting it when back is pressed:
Code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Sent from my Evo 3D GSM using Tapatalk 2

Add this if its helpful:
get file path as string from its uri
Code:
//Get file path as string from its uri useful when recieving files from pickers using startActivityForIntent
public String getFilePath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Get screen resolution as int
Code:
//this call reqires AP13
Inside an activity:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
else where:
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
if in AP13 or below
Use these depriciated calls:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

Related

WM6 - how to Query WLAN "connection" status

I am desperately trying to work around some unknown problem caused by our NDIS IM driver on WM6 and HTC TyTn ( TyTn at least, but most likely other devices as well ). I started some other threads regarding different facets of this problem, and no help is coming. Now I am just trying to work around it.
in short the problem is when power events happen the WLAN will never connect.
The work around is programmatically open the control panel with STControlPanel class and press the down button 1 time then the f1 key ( right dash ). This "presses connect" on the last configured access point. This works around my problem, however, I need to detect when the access point has connected. There is a "connecting" and "connected" message for the access point in this control panel dialog ( control panel # 17 ).
My Question: Is there some way to get this text "connecting" or "connected" from the control panel #17?
I have tried wzc, ndisuio, winsock, and other "non control panel" ways to detect connected state, but the IM problem fools all these methods. The only thing I have ever seen that successfully shows when the problem has occurred is the "connecting"/"connected" status in the control panel 17.
Please Help Someone.
p.s. If I can get this worked around, we sell a commercial grade ndis intermediate driver toolkit letting you easily write plugins without any of the hard driver details. We have redirectors, transparent proxy, tunnelers, virtual adapters, lots of good stuff. Also the same plugin will work on all windows desktop platforms vista - 98, WM5/6 and CE and also linux and solaris...
Hello skk
What about notification API?
Here is the solution (simple concept) for Your problem. Interesting parts are in bold.
SNapiTest.cpp
Code:
#include "stdafx.h"
#include "SNapiTest.h"
#include <windows.h>
#include <commctrl.h>
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE g_hInst; // current instance
HWND g_hWndMenuBar; // menu bar handle
[b]
const DWORD WM_WIFISTATUS = WM_USER + 1;
bool g_connecting;
bool g_connected;
HREGNOTIFY g_hNotify;
HREGNOTIFY g_hNotify2;
[/b]
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE, LPTSTR);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable;
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SNAPITEST));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SNAPITEST));
wc.hCursor = 0;
wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING]; // title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name
g_hInst = hInstance; // Store instance handle in our global variable
// SHInitExtraControls should be called once during your application's initialization to initialize any
// of the device specific controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_SNAPITEST, szWindowClass, MAX_LOADSTRING);
//If it is already running, then focus on the window, and exit
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// set focus to foremost child window
// The "| 0x00000001" is used to bring any owned windows to the foreground and
// activate them.
SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return 0;
}
if (!MyRegisterClass(hInstance, szWindowClass))
{
return FALSE;
}
hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
// When the main window is created using CW_USEDEFAULT the height of the menubar (if one
// is created is not taken into account). So we resize the window after creating it
// if a menubar is present
if (g_hWndMenuBar)
{
RECT rc;
RECT rcMenuBar;
GetWindowRect(hWnd, &rc);
GetWindowRect(g_hWndMenuBar, &rcMenuBar);
rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
static SHACTIVATEINFO s_sai;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
break;
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
SHMENUBARINFO mbi;
memset(&mbi, 0, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = hWnd;
mbi.nToolBarId = IDR_MENU;
mbi.hInstRes = g_hInst;
if (!SHCreateMenuBar(&mbi))
{
g_hWndMenuBar = NULL;
}
else
{
g_hWndMenuBar = mbi.hwndMB;
}
// Initialize the shell activate info structure
memset(&s_sai, 0, sizeof (s_sai));
s_sai.cbSize = sizeof (s_sai);
[b]
g_connecting = false;
g_connected = false;
{HRESULT hr = RegistryNotifyWindow(SN_WIFISTATECONNECTING_ROOT,
SN_WIFISTATECONNECTING_PATH, SN_WIFISTATECONNECTING_VALUE,
hWnd, WM_WIFISTATUS, 0, NULL, &g_hNotify);}
{HRESULT hr2 = RegistryNotifyWindow(SN_WIFISTATECONNECTING_ROOT,
SN_WIFISTATECONNECTED_PATH, SN_WIFISTATECONNECTED_VALUE,
hWnd, WM_WIFISTATUS, 0, NULL, &g_hNotify2);}
[/b]
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
[b]
case WM_WIFISTATUS:
{
DWORD newValue = (DWORD) wParam;
WCHAR caption[] = L"Wifi Status";
if ((newValue & SN_WIFISTATECONNECTED_BITMASK) == SN_WIFISTATECONNECTED_BITMASK)
{
if (!g_connected)
{
g_connected = true;
g_connecting = false;
MessageBox(hWnd, L"Connected!!", caption, MB_OK);
}
break;
}
if ((newValue & SN_WIFISTATECONNECTING_BITMASK) == SN_WIFISTATECONNECTING_BITMASK)
{
if (!g_connecting)
{
g_connecting = true;
g_connected =false;
MessageBox(hWnd, L"Connecting...", caption, MB_OK);
}
}
break;
}
[/b]
case WM_DESTROY:
CommandBar_Destroy(g_hWndMenuBar);
[B]
RegistryCloseNotification(g_hNotify);
RegistryCloseNotification(g_hNotify2);
[/B]
PostQuitMessage(0);
break;
case WM_ACTIVATE:
// Notify shell of our activate message
SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
break;
case WM_SETTINGCHANGE:
SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
// Create a Done button and size it.
SHINITDLGINFO shidi;
shidi.dwMask = SHIDIM_FLAGS;
shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU;
shidi.hDlg = hDlg;
SHInitDialog(&shidi);
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
break;
case WM_CLOSE:
EndDialog(hDlg, message);
return TRUE;
}
return (INT_PTR)FALSE;
}
Needed includes:
// TODO: reference additional headers your program requires here
#include <snapi.h>
#include <regext.h>
snapi.h
Thank you so much for your post. I just found snapi.h, I assume this is snapitest.h?
IT WORKS!
It works! You are my hero RStein. You are a god among men.
Great. ) Thanks for sharing the results.

[Q] Drawable not visible when camera preview is present

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?

[Q] Animation with surfaceview cant capture screenshot

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.

Dealing with Custom ListView and Fragments

Hi guys! Well, i am facing an issue when trying to develop my app. Let me explain what i have done:
1) Create a Login to connect to a MySQL Database to validate the user (Works great)
2) Create a Main activity
3) Create a Drawer, with a Drawer Adapter, to show the options of my dramer menu. (works great)
As you know the drawer works with fragments, so i have one fragment for each menu option.
4) Well, here starts my problem...
The first option on my menu is "Fixture" where i want to show a list of matchs with the differents results. That list, is on a MySql DB.
So, on my fragment (FixtureFragment) i have this code:
Code:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lxp.app.adapter.FixtureAdapter;
import com.lxp.app.model.FixtureItem;
import com.lxp.app.tools.JSONParser;
import com.lxp.app.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FixtureFragment extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// url to get all products list
private static String url_fixture = "http://www.myweb.com/myFixtureData.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIXUTRE = "fixture";
private static final String TAG_EQUIPO1 = "id_equipo_1";
private static final String TAG_EQUIPO2 = "id_equipo_2";
private static final String TAG_GEQUIPO1 = "goles_equipo_1";
private static final String TAG_GEQUIPO2 = "goles_equipo_2";
private static final String TAG_ID_PARTIDO = "id_partido";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray partidos = null;
ArrayList<HashMap<Integer, FixtureItem>> fixtureList;
ListView lv;
public FixtureFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
/**
* Background Async Task to Load the fixture by making HTTP Request
* */
class LoadFixture extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando el Fixture...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting the Fixture from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_fixture, "GET", params);
// Check your log cat for JSON reponse
Log.d("Fixture: ", json.toString());
FixtureItem objFixture = new FixtureItem();
try {
// Checking for SUCCESS TAG
int success = 0;
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
partidos = json.getJSONArray(TAG_FIXUTRE);
// looping through All Products
for (int i = 0; i < partidos.length(); i++) {
JSONObject c = partidos.getJSONObject(i);
Log.e("Json = ", c.toString());
// Storing each json item in variable
String equipo1 = c.getString(TAG_EQUIPO1);
String equipo2 = c.getString(TAG_EQUIPO2);
String golesEq1 = c.getString(TAG_GEQUIPO1);
String golesEq2 = c.getString(TAG_GEQUIPO2);
Integer idPartido = c.getInt(TAG_ID_PARTIDO);
// creating new HashMap
HashMap<Integer, FixtureItem> map = new HashMap<Integer, FixtureItem>();
// adding each child node to HashMap key => value
objFixture.setGolesEquipo1(golesEq1);
objFixture.setGolesEquipo2(golesEq2);
objFixture.setIdequipo1(equipo1);
objFixture.setIdequipo2(equipo2);
objFixture.setIdPartido(idPartido);
map.put(idPartido, objFixture);
fixtureList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
}
}
}
Well, as you could see, i've created a hashmap to load my fixture data, and then i sent this data (fixtureList) to the custom adapter.
When running this code i am getting this error.
Code:
04-05 16:20:27.899 23500-23500/com.lxp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lxp.app, PID: 23500
java.lang.NullPointerException
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:175)
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:632)
Line 175 --> lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
These are the layouts files:
Fragment_Fixture.xml
Code:
<LinearLayout 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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/fixture_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fixture_item.xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/idpartido"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:visibility="gone"/>
<TextView
android:id="@+id/golesequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="0"/>
<TextView
android:id="@+id/golesequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="1"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/idequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Argentinos"/>
<TextView
android:id="@+id/idequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Lanus"/>
</LinearLayout>
</LinearLayout>
My fixtureitem class
Code:
public class FixtureItem {
private Integer idPartido;
private String idequipo1;
private String idequipo2;
private String golesEquipo1;
private String golesEquipo2;
public Integer getIdPartido() {
return idPartido;
}
public void setIdPartido(Integer idPartido) {
this.idPartido = idPartido;
}
public String getIdequipo1() {
return idequipo1;
}
public String getIdequipo2() {
return idequipo2;
}
public String getGolesEquipo1() {
return golesEquipo1;
}
public String getGolesEquipo2() {
return golesEquipo2;
}
public void setIdequipo1(String idequipo1) {
this.idequipo1 = idequipo1;
}
public void setIdequipo2(String idequipo2) {
this.idequipo2 = idequipo2;
}
public void setGolesEquipo1(String golesEquipo1) {
this.golesEquipo1 = golesEquipo1;
}
public void setGolesEquipo2(String golesEquipo2) {
this.golesEquipo2 = golesEquipo2;
}
}
and my fixture adapter
Code:
public class FixtureAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
public FixtureAdapter(Context context, ArrayList listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.fixture_item, null);
holder = new ViewHolder();
holder.idequipo1 = (TextView) convertView.findViewById(R.id.idequipo1);
holder.idequipo2 = (TextView) convertView.findViewById(R.id.idequipo2);
holder.golesequipo1 = (TextView) convertView.findViewById(R.id.golesequipo1);
holder.golesequipo2 = (TextView) convertView.findViewById(R.id.golesequipo2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FixtureItem fixtureItem = (FixtureItem) listData.get(position);
holder.idequipo1.setText(fixtureItem.getGolesEquipo1());
holder.idequipo2.setText(fixtureItem.getGolesEquipo2());
holder.golesequipo1.setText(fixtureItem.getGolesEquipo1());
holder.golesequipo2.setText(fixtureItem.getGolesEquipo1());
return convertView;
}
static class ViewHolder {
TextView idequipo1;
TextView idequipo2;
TextView golesequipo1;
TextView golesequipo2;
}
}
I think i am getting wrong because i couldnt find an example of loading data in an asyncronous way for a list inside a fragment, i know is too expecific this example, but i tried differents ways to do it and i couldnt solve it.
If an experienced dev could give me a hand, i will be glad. Or if you have examples of an app working with "Drawer/Fragment/Custom List inside Fragments/Data Loaded from a MySql for the Custom List" it will be great.
If you need more data, just let me know.
Hey i made two apps with remote mysql database . May be i can help .
Sent from my SM-G900T using Tapatalk
Change
Try changing this:
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
// Loading products in Background Thread
new LoadFixture().execute();
return fixtureView;
}
from
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
Same problem
I have the same problem, not able to solve?
Resolved!!
Missed make reference to listView after inflate places:
lv = (ListView) view.findViewById(R.id.fixture_list);
Click to expand...
Click to collapse
Hugs,
Léo
can anybody help me im trying to display the results in the fragment from customlistview adapter ,there is no error at all but its not also displaying the results..

[Q] nullpointer and wrap_content problems

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?

Categories

Resources