Search Results

Search found 135 results on 6 pages for 'layoutparams'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • camera preview portrait problem in android application

    - by sujitjitu
    Hi this is my code for simple camera application in android .i have copied it from unlocking android e-book . Everything is working fine in emulator but when i am installing it in device the camera preview is working only in landscape mode. I have tried many thing but could not find any solution. Please see the code below and if you have any solution for it than it will be helpful to me. this is the code....... public class SimpleCamera extends Activity implements SurfaceHolder.Callback { private Camera camera; private boolean isPreviewRunning = false; private SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS"); private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Uri targetResource = Media.EXTERNAL_CONTENT_URI; public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().setFormat(PixelFormat.TRANSLUCENT); setContentView(R.layout.main); surfaceView = (SurfaceView)findViewById(R.id.surface); surfaceHolder = surfaceView.getHolder(); surfaceHolder.getSurface(); // Surface.setOrientation(Display.DEFAULT_DISPLAY,Surface.ROTATION_180); //didn't work at all surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public boolean onCreateOptionsMenu(android.view.Menu menu) { MenuItem item = menu.add(0, 0, 0, "View Pictures"); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(Intent.ACTION_VIEW, targetResource); startActivity(intent); return true; } }); return true; } protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } Camera.PictureCallback mPictureCallbackRaw = new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera c) { camera.startPreview(); } }; Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() { public void onShutter() { } }; public boolean onKeyDown(int keyCode, KeyEvent event) { ImageCaptureCallback camDemo = null; if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { try { String filename = timeStampFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(Media.TITLE, filename); values.put(Media.DESCRIPTION, "Image from Android Emulator"); Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); camDemo = new ImageCaptureCallback( getContentResolver().openOutputStream(uri)); } catch(Exception ex ){ } } if (keyCode == KeyEvent.KEYCODE_BACK) { return super.onKeyDown(keyCode, event); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { camera.takePicture(mShutterCallback, mPictureCallbackRaw, camDemo); return true; } return false; } protected void onResume() { Log.e(getClass().getSimpleName(), "onResume"); super.onResume(); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } protected void onStop() { super.onStop(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (isPreviewRunning) { camera.stopPreview(); } Camera.Parameters p = camera.getParameters(); p.setPreviewSize(w,h); //p.set("rotation","90"); // it didn't work //P.setRotation(90); // only work in 2.0 or later SDK but i am using 1.5 camera.setParameters(p); try { camera.setPreviewDisplay(holder); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } camera.startPreview(); isPreviewRunning = true; } public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); } public void surfaceDestroyed(SurfaceHolder holder) { camera.stopPreview(); isPreviewRunning = false; camera.release(); } } any help will be appreciated..

    Read the article

  • How to implement a custom AlertDialog View

    - by stormin986
    In the Android docs on AlertDialog, it gives the following instruction and example for setting a custom view in an AlertDialog: If you want to display a more complex view, look up the FrameLayout called "body" and add your view to it: FrameLayout fl = (FrameLayout) findViewById(R.id.body); fl.add(myView, new LayoutParams(FILL_PARENT, WRAP_CONTENT)); First off, it's pretty obvious that add() is a typo and is meant to be addView(). I'm confused by the first line using R.id.body. It seems that it's the body element of the AlertDialog ... but I can't just enter that in my code b/c it gives a compile error. Where does R.id.body get defined or assigned or whatever?

    Read the article

  • Android: how to hide and then show View with animation effect?

    - by tomash
    I have similar question like this one: http://stackoverflow.com/questions/2079074/update-layout-with-the-animation Basically: I have one vertical LinearLayout View with edittext, button and then list. I'd like to hide exittext after pressing button to make more space for list (button will go up). On second press edittext should be visible again. Edittext and button have "wrap_content" height. I'd like to hide and show edittext with animation. I succeeded to animate hiding by overloading Animation's applyTransformation: final float edittextheight= edittext.getHeight(); [....] @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); android.view.ViewGroup.LayoutParams lp = edittext.getLayoutParams(); lp.height = (int)(edittextheight*(1.0-interpolatedTime)); edittext.setLayoutParams(lp); } Problem: I don't know how to calculate height to animate showing - edittext.getHeight(); returns 0 when widget is hidden and in layout definition I'm using "wrap_content". Help?

    Read the article

  • Android draw using SurfaceView and Thread

    - by Morten Høgseth
    I am trying to draw a ball to my screen using 3 classes. I have read a little about this and I found a code snippet that works using the 3 classes on one page, Playing with graphics in Android I altered the code so that I have a ball that is moving and shifts direction when hitting the wall like the picture below (this is using the code in the link). Now I like to separate the classes into 3 different pages for not making everything so crowded, everything is set up the same way. Here are the 3 classes I have. BallActivity.java Ball.java BallThread.java package com.brick.breaker; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class BallActivity extends Activity { private Ball ball; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); ball = new Ball(this); setContentView(ball); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); setContentView(null); ball = null; finish(); } } package com.brick.breaker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Ball extends SurfaceView implements SurfaceHolder.Callback { private BallThread ballThread = null; private Bitmap bitmap; private float x, y; private float vx, vy; public Ball(Context context) { super(context); // TODO Auto-generated constructor stub bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball); x = 50.0f; y = 50.0f; vx = 10.0f; vy = 10.0f; getHolder().addCallback(this); ballThread = new BallThread(getHolder(), this); } protected void onDraw(Canvas canvas) { update(canvas); canvas.drawBitmap(bitmap, x, y, null); } public void update(Canvas canvas) { checkCollisions(canvas); x += vx; y += vy; } public void checkCollisions(Canvas canvas) { if(x - vx < 0) { vx = Math.abs(vx); } else if(x + vx > canvas.getWidth() - getBitmapWidth()) { vx = -Math.abs(vx); } if(y - vy < 0) { vy = Math.abs(vy); } else if(y + vy > canvas.getHeight() - getBitmapHeight()) { vy = -Math.abs(vy); } } public int getBitmapWidth() { if(bitmap != null) { return bitmap.getWidth(); } else { return 0; } } public int getBitmapHeight() { if(bitmap != null) { return bitmap.getHeight(); } else { return 0; } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub ballThread.setRunnable(true); ballThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub boolean retry = true; ballThread.setRunnable(false); while(retry) { try { ballThread.join(); retry = false; } catch(InterruptedException ie) { //Try again and again and again } break; } ballThread = null; } } package com.brick.breaker; import android.graphics.Canvas; import android.view.SurfaceHolder; public class BallThread extends Thread { private SurfaceHolder sh; private Ball ball; private Canvas canvas; private boolean run = false; public BallThread(SurfaceHolder _holder,Ball _ball) { sh = _holder; ball = _ball; } public void setRunnable(boolean _run) { run = _run; } public void run() { while(run) { canvas = null; try { canvas = sh.lockCanvas(null); synchronized(sh) { ball.onDraw(canvas); } } finally { if(canvas != null) { sh.unlockCanvasAndPost(canvas); } } } } public Canvas getCanvas() { if(canvas != null) { return canvas; } else { return null; } } } Here is a picture that shows the outcome of these classes. I've tried to figure this out but since I am pretty new to Android development I thought I could ask for help. Does any one know what is causing the ball to be draw like that? The code is pretty much the same as the one in the link and I have tried to experiment to find a solution but no luck. Thx in advance for any help=)

    Read the article

  • Thread Blocks During Call

    - by user578875
    I have a serious problem, I'm developing an application that mesures on call time during a call; the problem presents when, with the phone on the ear, the thread that the timer has, blocks and no longer responds before taking off my ear. The next log shows the problem. 01-11 16:14:19.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:20.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:21.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:22.597 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:23.608 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:24.017 1106 1106 D iddd : select() < 0, Probably a handled signal: Interrupted system call 01-11 16:14:24.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:05.500 1106 1106 D iddd : select() < 0, Probably a handled signal: Interrupted system call 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service I've been trying with Services, Timers, Threads, AyncTasks and they all present the same problem. My Code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); HangUpService.setMainActivity(this); objHangUpService = new Intent(this, HangUpService.class); Runnable rAccion = new Runnable() { public void run() { TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); objVibrator = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE); final ListView lstLlamadas = (ListView) findViewById(R.id.lstFavoritos); final EditText txtMinutos = (EditText) findViewById(R.id.txtMinutos); final EditText txtSegundos = (EditText) findViewById(R.id.txtSegundos); ArrayList<Contacto> cContactos = new ArrayList<Contacto>(); ContactoAdapter caContactos = new ContactoAdapter(HangUp.this, R.layout.row,cContactos); Cursor curContactos = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.TIMES_CONTACTED + " DESC"); while (curContactos.moveToNext()){ String strNombre = curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String strID = curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts._ID)); String strHasPhone=curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); String strStarred=curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.STARRED)); if (Integer.parseInt(strHasPhone) > 0 && Integer.parseInt(strStarred) ==1 ) { Cursor CursorTelefono = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = " + strID, null, null); while (CursorTelefono.moveToNext()) { String strTipo=CursorTelefono.getString(CursorTelefono.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); String strTelefono=CursorTelefono.getString(CursorTelefono.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); strNumero=strTelefono; String args[]=new String[1]; args[0]=strNumero; Cursor CursorCallLog = getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.NUMBER + "=?", args, android.provider.CallLog.Calls.DATE+ " DESC"); if (Integer.parseInt(strTipo)==2) { caContactos.add( new Contacto( strNombre, strTelefono ) ); } } CursorTelefono.close(); } } curContactos.close(); lstLlamadas.setAdapter(caContactos); lstLlamadas.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView a, View v, int position, long id) { Contacto mContacto=(Contacto)lstLlamadas.getItemAtPosition(position); i = new Intent(HangUp.this, Llamada.class); Log.i("Estado","Declaro Intent"); Bundle bundle = new Bundle(); bundle.putString("telefono", mContacto.getTelefono()); i.putExtras(bundle); startActivityForResult(i,SUB_ACTIVITY_ID); Log.i("Estado","Inicio Intent"); blActivo=true; try { String strMinutos=txtMinutos.getText().toString(); String strSegundos=txtSegundos.getText().toString(); if(!strMinutos.equals("") && !strSegundos.equals("")){ int Tiempo = ( (Integer.parseInt(txtMinutos.getText().toString())*60) + Integer.parseInt(txtSegundos.getText().toString()) )* 1000; handler.removeCallbacks(rVibrate); cTime = System.currentTimeMillis(); cTime=cTime+Tiempo; objHangUpAsync = new HangUpAsync(cTime,objVibrator,objPowerManager,objKeyguardLock); objHangUpAsync.execute(); objPowerManager.userActivity(Tiempo+3000, true); objHangUpService.putExtra("cTime", cTime); //startService(objHangUpService); } catch (Exception e) { e.printStackTrace(); } finally { } } }); } }; } AsyncTask: @Override protected String doInBackground(String... arg0) { blActivo = true; mWakeLock = objPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag"); objKeyguardLock.disableKeyguard(); Log.i("Estado", "Entro a doInBackground"); timer.scheduleAtFixedRate( new TimerTask() { public void run() { if (blActivo){ if (cTime blActivo=false; objVibrator.vibrate(1000); Log.i("Estado","Vibrar desde Async"); this.cancel(); }else{ try{ mWakeLock.acquire(); mWakeLock.release(); Log.i("Estado","postDelayed Async Service"); }catch(Exception e){ Log.i("Estado","Error: " + e.getMessage()); } } } } }, 0, INTERVAL); return null; }

    Read the article

  • Android 2.2: Screen brightness/timeout question

    - by Johan
    Im using the following code to adjust the brightness of the screen: public void SetBright(float value) { Window mywindow = getWindow(); WindowManager.LayoutParams lp = mywindow.getAttributes(); lp.screenBrightness = value; mywindow.setAttributes(lp); } But i want the brightness to be 0% for a specific time. But when i use SetBright(0.0f), i cant change it back. I made a timer that runs for a minute with 0% brightness, then turns it back to 100%. Works when i use 10% for example. But when i turn it to 0% i cant seem to wake it up again. Any ideas how to solve this?

    Read the article

  • ImageView Force closes my application

    - by BlueFireLady
    Hi there I am really a beginner, and I have been fighting with this problem for 3 days. :( I am able to get an image to show using a grid view and an adapter as in the grid view tutorial, but I wanted to be able to just use ImageView in the xml. public class HelloImage extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView gridview = (ImageView) findViewById(R.id.gridview); gridview.setLayoutParams(new GridView.LayoutParams(85, 85)); gridview.setScaleType(ImageView.ScaleType.CENTER_CROP); gridview.setPadding(8, 8, 8, 8); gridview.setImageResource(R.drawable.hand_tool); } } When I run this it causes the app to force close when loading.

    Read the article

  • BroadCast Receiver calling intent after some time android

    - by khushi
    public class myReceiver extends BroadcastReceiver { public static boolean wasScreenOn = true; @Override public void onReceive(final Context context, Intent recievedIntent) { if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { wasScreenOn = false; Intent intent = new Intent(context, myActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); context.startActivity(intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_ON)) { wasScreenOn = true; } } } The activity display after when action screen on is call.

    Read the article

  • Axis value changes in barchart while swapping the phone using Achartengine

    - by Vasu
    Hi I have included the Barchart using AchartEngine API .When I swap the orientation of the screen the yaxis value is altered as same values. For eg. initially it is (0,10) , (10,25) but after swapping its changes to (0,10), (10,10) i could not understand why it is happening . And I have place string in x axis instead of numbers , I used addtextlabel method but the string is overlapped on the number . I need to display only the names. could you help on this. I have included my code here. public class Analytics extends Activity implements OnClickListener { private Button settings_btn; private RelativeLayout relativeLayout3; private boolean isClicked = false; private static final int SERIES_NR = 1; static int multiple_of_five; private GraphicalView mChartView; XYMultipleSeriesRenderer renderer; static int value=20; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.analytics); settings_btn = (Button) findViewById(R.id.settings_btn); relativeLayout3 = (RelativeLayout) findViewById(R.id.relativeLayout3); settings_btn.setOnClickListener(this); if (SharedValues.isClicked) { relativeLayout3.setVisibility(View.VISIBLE); } else { relativeLayout3.setVisibility(View.GONE); } renderer = getBarDemoRenderer(); setChartSettings(renderer); if (mChartView == null) { RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativeLayout5); // mChartView= ChartFactory.getLineChartView(this, getDemoDataset(), getDemoRenderer()); mChartView = ChartFactory.getBarChartView(getApplicationContext(),getBarDemoDataset(),renderer,Type.DEFAULT); layout.addView(mChartView,new LayoutParams(LayoutParams.FILL_PARENT, 280)); } else { mChartView.repaint(); } // Intent intent = ChartFactory.getLineChartIntent(this, getDemoDataset(), getDemoRenderer()); // intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), renderer, Type.DEFAULT); // startActivity(intent); } @Override protected void onResume() { super.onResume(); } public XYMultipleSeriesRenderer getBarDemoRenderer() { XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); renderer.setAxisTitleTextSize(16); renderer.setChartTitleTextSize(20); renderer.setLabelsTextSize(15); renderer.setLegendTextSize(15); // renderer.setApplyBackgroundColor(true); // renderer.setBackgroundColor(R.color.chart_bg); // renderer.setMarginsColor(R.color.settings_bg_color); // renderer.setBackgroundColor(getResources().getColor(R.color.background)); renderer.setPanEnabled(false, false); renderer.setZoomEnabled(false, false); renderer.setMargins(new int[] {0, 10, 0, 0}); SimpleSeriesRenderer r = new SimpleSeriesRenderer(); // r.setColor(Color.MAGENTA); // renderer.addSeriesRenderer(r); r = new SimpleSeriesRenderer(); r.setColor(Color.CYAN); renderer.addSeriesRenderer(r); return renderer; } private void setChartSettings(XYMultipleSeriesRenderer renderer) { // renderer.setChartTitle("Chart demo"); // renderer.setXTitle("x values"); // renderer.setYTitle("y values"); renderer.setXAxisMin(2); renderer.setMarginsColor(Color.parseColor("#00F5DA81")); renderer.addXTextLabel(1.0, "Q1"); renderer.addXTextLabel(3.0, "Q2"); renderer.addXTextLabel(5.0, "Q3"); renderer.addXTextLabel(7.0, "Q4"); renderer.addXTextLabel(9.0, "Q5"); renderer.setXAxisMax(20); renderer.setYAxisMin(0); renderer.setYAxisMax(100); renderer.setZoomEnabled(false, false); // renderer.setApplyBackgroundColor(true); // renderer.setMarginsColor(R.color.settings_bg_color); renderer.setBackgroundColor(Color.TRANSPARENT); // renderer.setBackgroundColor(R.color.chart_bg); } private XYMultipleSeriesDataset getDemoDataset() { XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); final int nr = 10; Random r = new Random(); for (int i = 0; i < SERIES_NR; i++) { XYSeries series = new XYSeries(""); for (int k = 0; k < nr; k++) { if(k%2==1) { series.add(0, 0); } else { series.add(k, 20); } } dataset.addSeries(series); } return dataset; } private XYMultipleSeriesRenderer getDemoRenderer() { XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); renderer.setAxisTitleTextSize(6); renderer.setChartTitleTextSize(10); renderer.setLabelsTextSize(5); renderer.setLegendTextSize(5); renderer.setPointSize(5f); // renderer.setMarginsColor(R.color.settings_bg_color); // renderer.setApplyBackgroundColor(true); // renderer.setBackgroundColor(R.color.chart_bg); renderer.setMargins(new int[] {20, 30, 15, 0}); XYSeriesRenderer r = new XYSeriesRenderer(); r.setColor(Color.BLUE); r.setPointStyle(PointStyle.SQUARE); r.setFillBelowLine(true); r.setFillBelowLineColor(Color.WHITE); r.setFillPoints(true); renderer.addSeriesRenderer(r); r = new XYSeriesRenderer(); r.setPointStyle(PointStyle.CIRCLE); r.setColor(Color.GREEN); r.setFillPoints(true); renderer.addSeriesRenderer(r); renderer.setAxesColor(Color.DKGRAY); renderer.setLabelsColor(Color.LTGRAY); return renderer; } private XYMultipleSeriesDataset getBarDemoDataset() { XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); final int nr = 10; Random r = new Random(); for (int i = 0; i < SERIES_NR; i++) { CategorySeries series = new CategorySeries("Quadrant"); for (int k = 0; k < nr; k++) { value=value+5; // multiple_of_five=k+5; // Log.i("multiple_of_five", ""+multiple_of_five); // series.add(20 +multiple_of_five ); if(k%2==1){ series.add(value ); } else { series.add(0); } } dataset.addSeries(series.toXYSeries()); } return dataset; } @Override public void onClick(View v) { if (v == settings_btn) { if (SharedValues.isClicked) { relativeLayout3.setVisibility(View.GONE); SharedValues.isClicked = false; } else { relativeLayout3.setVisibility(View.VISIBLE); SharedValues.isClicked = true; } } } }

    Read the article

  • Android App Crashes On Second Run

    - by user1091286
    My app runs fine on first run. On the Menu I added two choices options and quit. options which set up a new intent who goes to a PreferenceActivity and quit which simply call: "android.os.Process.killProcess(android.os.Process.myPid());" On the second time I run my app (after I quit from inside the emulator) it crashes.. Ideas? the menu is called by the foolowing code: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu , menu); return true; } - @Override public boolean onOptionsItemSelected(MenuItem item) { // Set up a new intent between the updater service and the main screen Intent options = new Intent(this, OptionsScreenActivity.class); // Switch case on the options switch (item.getItemId()) { case R.id.options: startActivity(options); return true; case R.id.quit: android.os.Process.killProcess(android.os.Process.myPid()); return true; default: return false; } Code for SeekBarPreference: package com.testapp.logic; import com.testapp.R; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { private final String TAG = getClass().getName(); private static final String ANDROIDNS="http://schemas.android.com/apk/res/android"; private static final String PREFS="com.testapp.logic"; private static final int DEFAULT_VALUE = 5; private int mMaxValue = 100; private int mMinValue = 1; private int mInterval = 1; private int mCurrentValue; private String mUnitsLeft = ""; private String mUnitsRight = ""; private SeekBar mSeekBar; private TextView mStatusText; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); initPreference(context, attrs); } public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initPreference(context, attrs); } private void initPreference(Context context, AttributeSet attrs) { setValuesFromXml(attrs); mSeekBar = new SeekBar(context, attrs); mSeekBar.setMax(mMaxValue - mMinValue); mSeekBar.setOnSeekBarChangeListener(this); } private void setValuesFromXml(AttributeSet attrs) { mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100); mMinValue = attrs.getAttributeIntValue(PREFS, "min", 0); mUnitsLeft = getAttributeStringValue(attrs, PREFS, "unitsLeft", ""); String units = getAttributeStringValue(attrs, PREFS, "units", ""); mUnitsRight = getAttributeStringValue(attrs, PREFS, "unitsRight", units); try { String newInterval = attrs.getAttributeValue(PREFS, "interval"); if(newInterval != null) mInterval = Integer.parseInt(newInterval); } catch(Exception e) { Log.e(TAG, "Invalid interval value", e); } } private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { String value = attrs.getAttributeValue(namespace, name); if(value == null) value = defaultValue; return value; } @Override protected View onCreateView(ViewGroup parent){ RelativeLayout layout = null; try { LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = (RelativeLayout)mInflater.inflate(R.layout.seek_bar_preference, parent, false); } catch(Exception e) { Log.e(TAG, "Error creating seek bar preference", e); } return layout; } @Override public void onBindView(View view) { super.onBindView(view); try { // move our seekbar to the new view we've been given ViewParent oldContainer = mSeekBar.getParent(); ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer); if (oldContainer != newContainer) { // remove the seekbar from the old view if (oldContainer != null) { ((ViewGroup) oldContainer).removeView(mSeekBar); } // remove the existing seekbar (there may not be one) and add ours newContainer.removeAllViews(); newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } catch(Exception ex) { Log.e(TAG, "Error binding view: " + ex.toString()); } updateView(view); } /** * Update a SeekBarPreference view with our current state * @param view */ protected void updateView(View view) { try { RelativeLayout layout = (RelativeLayout)view; mStatusText = (TextView)layout.findViewById(R.id.seekBarPrefValue); mStatusText.setText(String.valueOf(mCurrentValue)); mStatusText.setMinimumWidth(30); mSeekBar.setProgress(mCurrentValue - mMinValue); TextView unitsRight = (TextView)layout.findViewById(R.id.seekBarPrefUnitsRight); unitsRight.setText(mUnitsRight); TextView unitsLeft = (TextView)layout.findViewById(R.id.seekBarPrefUnitsLeft); unitsLeft.setText(mUnitsLeft); } catch(Exception e) { Log.e(TAG, "Error updating seek bar preference", e); } } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newValue = progress + mMinValue; if(newValue > mMaxValue) newValue = mMaxValue; else if(newValue < mMinValue) newValue = mMinValue; else if(mInterval != 1 && newValue % mInterval != 0) newValue = Math.round(((float)newValue)/mInterval)*mInterval; // change rejected, revert to the previous value if(!callChangeListener(newValue)){ seekBar.setProgress(mCurrentValue - mMinValue); return; } // change accepted, store it mCurrentValue = newValue; mStatusText.setText(String.valueOf(newValue)); persistInt(newValue); } public void onStartTrackingTouch(SeekBar seekBar) {} public void onStopTrackingTouch(SeekBar seekBar) { notifyChanged(); } @Override protected Object onGetDefaultValue(TypedArray ta, int index){ int defaultValue = ta.getInt(index, DEFAULT_VALUE); return defaultValue; } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if(restoreValue) { mCurrentValue = getPersistedInt(mCurrentValue); } else { int temp = 0; try { temp = (Integer)defaultValue; } catch(Exception ex) { Log.e(TAG, "Invalid default value: " + defaultValue.toString()); } persistInt(temp); mCurrentValue = temp; } } } Logcat: E/AndroidRuntime( 4525): FATAL EXCEPTION: main E/AndroidRuntime( 4525): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ui.testapp/com.logic.testapp.SeekBarPreferen ce}: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty constructor E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879) E/AndroidRuntime( 4525): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) E/AndroidRuntime( 4525): at android.app.ActivityThread.access$600(ActivityThread.java:122) E/AndroidRuntime( 4525): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) E/AndroidRuntime( 4525): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 4525): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime( 4525): at android.app.ActivityThread.main(ActivityThread.java:4340) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) E/AndroidRuntime( 4525): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime( 4525): Caused by: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty construc tor E/AndroidRuntime( 4525): at java.lang.Class.newInstanceImpl(Native Method) E/AndroidRuntime( 4525): at java.lang.Class.newInstance(Class.java:1319) E/AndroidRuntime( 4525): at android.app.Instrumentation.newActivity(Instrumentation.java:1023) E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870) E/AndroidRuntime( 4525): ... 11 more W/ActivityManager( 84): Force finishing activity com.ui.testapp/com.logic.testapp.SeekBarPreference W/ActivityManager( 84): Force finishing activity com.ui.testapp/.MainScreen I/WindowManager( 84): createSurface Window{41a90320 paused=false}: DRAW NOW PENDING W/ActivityManager( 84): Activity pause timeout for ActivityRecord{4104a848 com.ui.testapp/com.logic.testapp.SeekBarPreference} W/NetworkManagementSocketTagger( 84): setKernelCountSet(10021, 1) failed with errno -2 I/WindowManager( 84): createSurface Window{412bcc10 com.android.launcher/com.android.launcher2.Launcher paused=false}: DRAW NOW PENDING W/NetworkManagementSocketTagger( 84): setKernelCountSet(10045, 0) failed with errno -2 I/Process ( 4525): Sending signal. PID: 4525 SIG: 9 I/ActivityManager( 84): Process com.ui.testapp (pid 4525) has died. I/WindowManager( 84): WIN DEATH: Window{41a6c9c0 com.ui.testapp/com.ui.testapp.MainScreen paused=true}

    Read the article

  • NetworkOnMainThreadException while using AsyncTask

    - by Fansher
    Im making an app that uses the internet to retrive information. I get an NetworkOnMainThreadException as i tried to run it on 3.0 and above and have therefore tried to set it up using AsyncTask, but it still gives the exception and i don't know what is wrong. Oddly enough i read on this thread Android NetworkOnMainThreadException inside of AsyncTask that if you just removes the android:targetSdkVersion="10" statement from the manifest file it will be able to run. This works but i don't find it as the right solution to solve the problem this way. So if anyone can tell me what im doing wrong with the AsyncTask i will really appriciate it. Also if there is anybody that knows why removing the statement in the manifest makes it work, im really interested in that also. My code looks like this: public class MainActivity extends Activity { static ArrayList<Tumblr> tumblrs; ListView listView; TextView footer; int offset = 0; ProgressDialog pDialog; View v; String responseBody = null; HttpResponse r; HttpEntity e; String searchUrl; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { setContentView(R.layout.main); try { tumblrs = getTumblrs(); listView = (ListView) findViewById(R.id.list); View v = getLayoutInflater().inflate(R.layout.footer_layout, null); footer = (TextView) v.findViewById(R.id.tvFoot); listView.addFooterView(v); listView.setAdapter(new UserItemAdapter(this, R.layout.listitem)); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } new GetChicks().execute(); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new loadMoreListView().execute(); } }); } else { setContentView(R.layout.nonet); } } public class UserItemAdapter extends ArrayAdapter<Tumblr> { public UserItemAdapter(Context context, int imageViewResourceId) { super(context, imageViewResourceId, tumblrs); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listitem, null); } Tumblr tumblr = tumblrs.get(position); if (tumblr != null) { ImageView image = (ImageView) v.findViewById(R.id.avatar); if (image != null) { image.setImageBitmap(getBitmap(tumblr.image_url)); } } return v; } } public Bitmap getBitmap(String bitmapUrl) { try { URL url = new URL(bitmapUrl); return BitmapFactory.decodeStream(url.openConnection() .getInputStream()); } catch (Exception ex) { return null; } } public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException, IOException, JSONException { searchUrl = "http://api.tumblr.com/v2/blog/"webside"/posts?api_key=API_KEY"; ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>(); return tumblrs; } private class GetChicks extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... unused) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { public void run() { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(searchUrl); HttpResponse r = null; try { r = client.execute(get); int status = r.getStatusLine().getStatusCode(); if (status == 200) { e = r.getEntity(); responseBody = EntityUtils.toString(e); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject jsonObject; try { jsonObject = new JSONObject(responseBody); JSONArray posts = jsonObject.getJSONObject("response") .getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONArray photos = posts.getJSONObject(i) .getJSONArray("photos"); for (int j = 0; j < photos.length(); j++) { JSONObject photo = photos.getJSONObject(j); String url = photo.getJSONArray("alt_sizes") .getJSONObject(0).getString("url"); Tumblr tumblr = new Tumblr(url); tumblrs.add(tumblr); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return null; } } public class Tumblr { public String image_url; public Tumblr(String url) { this.image_url = url; } } private class loadMoreListView extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { // Showing progress dialog before sending http request pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("More chicks coming up.."); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... unused) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { public void run() { // increment current page offset += 2; // Next page request tumblrs.clear(); String searchUrl = "http://api.tumblr.com/v2/blog/"webside"/posts?api_key=API_KEY&limit=2 + offset; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(searchUrl); HttpResponse r = null; try { r = client.execute(get); int status = r.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity e = r.getEntity(); responseBody = EntityUtils.toString(e); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject jsonObject; try { jsonObject = new JSONObject(responseBody); JSONArray posts = jsonObject.getJSONObject("response") .getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONArray photos = posts.getJSONObject(i) .getJSONArray("photos"); for (int j = 0; j < photos.length(); j++) { JSONObject photo = photos.getJSONObject(j); String url = photo.getJSONArray("alt_sizes") .getJSONObject(0).getString("url"); Tumblr tumblr = new Tumblr(url); tumblrs.add(tumblr); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Setting new scroll position listView.setSelectionFromTop(0, 0); } }); return null; } protected void onPostExecute(Void unused) { pDialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(android.view.Menu menu) { // TODO Auto-generated method stub super.onCreateOptionsMenu(menu); MenuInflater blowUp = getMenuInflater(); blowUp.inflate(R.menu.cool_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.aboutUs: Intent i = new Intent("com.example.example.ABOUT"); startActivity(i); break; case R.id.refresh: Intent f = new Intent(MainActivity.this, MainActivity.class); startActivity(f); finish(); break; case R.id.exit: finish(); break; } return false; } } Thanks for helping out.

    Read the article

  • Android beginner: Touch events in android gridview

    - by jja
    I am using the following code to do things with gridview(slightly modified from http://developer.android.com/resources/tutorials/views/hello-gridview.html). I want to replace the onClicklistener and the onClick() method with their "touch" equivalents i.e. touchlistener and onTouch() so that when i touch an element in the gridview the image of the element changes and a double touch on the same element takes it back to the orginal state. How do I do this? I can't get my code to do this. The clicklistener works to some extent but the touch isn't. Please help. public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(position==0) { //do this } else { //do this } } }); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 }; }

    Read the article

  • Inflated ImageView to put in GalleryView isn't the right size

    - by Richard
    I am trying to inflate an ImageView that scales a Drawable that I can display in a GalleryView. My code to inflate the view seems to work fine, except that the attributes of the ImageView are not applied. Specifically, the inflated ImageView does not have the width/height that I set for it via the android:layout params in XML. Can someone show me what I'm doing wrong? I want to set the width/height of the image in dp, so that it is the correct size across multiple screen dpis and support Android 1.5+. As a result I cannot use something like: i.setLayoutParams(new Gallery.LayoutParams(150, 116) My layout definition is: <?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="150dp" android:layout_height="116dp" android:background="@drawable/gallery_item_background" android:scaleType="fitXY" /> </ImageView> And the snippet I am using to inflate the ImageView is: public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); ImageView i = (ImageView) inflater.inflate(R.layout.gallery_item, null); i.setImageResource(mImageIds.get(position)); i.setScaleType(ImageView.ScaleType.FIT_XY); return i; }

    Read the article

  • How to change one Button background in a gridview? -- Android

    - by Tstop Studios
    I have a GridView with 16 ImageView buttons. My program makes a random number and when the user clicks a button in the gridview, i want it to take the random number (0-15) and set the background of the tile with the same position as the random number (0-15) to a different image. How can I just change one of the buttons background? Here's my code so far: public class ButtonHider extends Activity { Random random = new Random(); int pos; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.button_hider); pos = random.nextInt(15); GridView gridview = (GridView) findViewById(R.id.gvBH); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { pos = random.nextInt(16); if (position == pos) { Toast.makeText(ButtonHider.this, "Found Me!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ButtonHider.this, "Try Again!!", Toast.LENGTH_SHORT).show(); } } }); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return 16; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some // attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(15, 15, 15, 15); } else { imageView = (ImageView) convertView; } imageView.setImageResource(R.drawable.bh_b); return imageView; } } }

    Read the article

  • Reuse Client java Socket in a Java Server

    - by user1394983
    I'm devoloping an Java server two control an android online game. It's possible save the client socket of myserversocket.accept() in a variable in Client class? This are very util because this way, server can communicate with client when server wants and no when client contact server. My actual code are: import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.UUID; import sal.app.shared.Packet; public class Server { private ArrayList<GameSession> games = new ArrayList<GameSession>(); private ArrayList<Client> pendent_clients = new ArrayList<Client>(); private Packet read_packet= new Packet(); private Packet sent_packet = new Packet(); private Socket clientSocket = null; public static void main(String[] args) throws ClassNotFoundException{ ServerSocket serverSocket = null; //DataInputStream dataInputStream = null; //DataOutputStream dataOutputStream = null; ObjectOutputStream oos=null; ObjectInputStream ois=null; Server myServer = new Server(); try { serverSocket = new ServerSocket(7777); System.out.println("Listening :7777"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(true){ try { myServer.clientSocket = new Socket(); myServer.clientSocket = serverSocket.accept(); myServer.read_packet = new Packet(); myServer.sent_packet = new Packet(); oos = new ObjectOutputStream(myServer.clientSocket.getOutputStream()); ois = new ObjectInputStream(myServer.clientSocket.getInputStream()); //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((myServer.read_packet = (Packet) ois.readObject()) != null) { myServer.handlePacket(myServer.read_packet); break; }*/ myServer.read_packet=(Packet) ois.readObject(); myServer.handlePacket(myServer.read_packet); //oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if( myServer.clientSocket!= null){ /*try { //myServer.clientSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } /*if( ois!= null){ try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( oos!= null){ try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ } } } public void handlePacket(Packet hp) throws IOException { if(hp.getOpCode() == 1) { registPlayer(hp); } } public void registPlayer(Packet p) throws IOException { Client registClient = new Client(this.clientSocket); this.pendent_clients.add(registClient); if(pendent_clients.size() == 2) { initAGame(); } else { ObjectOutputStream out=null; Packet to_send = new Packet(); to_send.setOpCode(4); out = new ObjectOutputStream(registClient.getClientSocket().getOutputStream()); out.writeObject(to_send); } } public void initAGame() throws IOException { Client c1 = pendent_clients.get(0); Client c2 = pendent_clients.get(1); Packet to_send = new Packet(); ObjectOutputStream out=null; GameSession incomingGame = new GameSession(c1,c2); games.add(incomingGame); to_send.setGameId(incomingGame.getGameId()); to_send.setOpCode(5); out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); out = new ObjectOutputStream(c2.getClientSocket().getOutputStream()); out.writeObject(to_send); pendent_clients.clear(); } public Client getClientById(UUID given_id) { for(GameSession gs: games) { if(gs.getClient1().getClientId().equals(given_id)) { return gs.getClient1(); } else if(gs.getClient2().getClientId().equals(given_id)) { return gs.getClient2(); } } return null; } } With this code i got this erros: java.net.SocketException: Broken pipe at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847) at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756) at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1257) at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1211) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1395) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1547) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:333) at Server.initAGame(Server.java:146) at Server.registPlayer(Server.java:120) at Server.handlePacket(Server.java:106) at Server.main(Server.java:63) This error ocurre when second client connect and server try to send an Packet to previous client 1 in function initGame() in this code: out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); my android code is this: package sal.app; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import sal.app.logic.DataBaseManager; import sal.app.shared.Packet; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class MultiPlayerWaitActivity extends Activity{ private DataBaseManager db; public void onCreate(Bundle savedInstanceState) { super.requestWindowFeature(Window.FEATURE_NO_TITLE); super.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.multiwaitlayout); db=DataBaseManager.getSalDatabase(this); db.teste(); try { db.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Socket socket = null; ObjectOutputStream outputStream = null; ObjectInputStream inputStream = null; //System.out.println("dadadad"); try { socket = new Socket("192.168.1.4", 7777); //Game = new MultiPlayerGame(new ServerManager("192.168.1.66"),new Session(), new Player("")); outputStream = new ObjectOutputStream(socket.getOutputStream()); inputStream = new ObjectInputStream(socket.getInputStream()); //dataOutputStream.writeUTF(textOut.getText().toString()); //textIn.setText(dataInputStream.readUTF()); Packet p = new Packet(); Packet r = new Packet(); p.setOpCode(1); outputStream.writeObject(p); /*try { r=(Packet)inputStream.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //while(true){ //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((r= (Packet) inputStream.readObject()) != null) { handPacket(r); break; }*/ r=(Packet) inputStream.readObject(); handPacket(r); //oos.close(); //} /*System.out.println(r.getOpCode()); if(r.getOpCode() == 5) { this.finish(); }*/ } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*finally{ if (socket != null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outputStream != null){ try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }*/ //catch (ClassNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); //} catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void handPacket(Packet hp) { if(hp.getOpCode() == 5) { this.finish(); } this.finish(); } } Regards

    Read the article

  • How to change size of Android ScrollView

    - by user611923
    I have a layout like this (abstracted): Scrollview - fill_parent LinearLayout - wrap_content ImageView 1 - wrap_content ImageView 2 - ... ImageView 3 ... In the course of user interaction some images are replaced by larger or smaller ones, shortening or lenghtening the area to be scrolled. And that is the problem. The Scrollview (SV) does not know about the change, so either it scrolls over a lot of empty space at the bottom, or cuts off a picture or two at the bottom. Question 1: Can I somehow make the SV readapt to the changed hight of the LiearLayout (LL)? Question 2: I can obtain the current size through getHight on the LL. But supplyong it to the SV via changed LayoutParams does not work - of course, that would only change the height of the SV on the screen. Is there a way to put the changed height of the LL into the SV in the code, somehow? Question 3: I havn't tried it yet. Would creating the SV, LL and its children in code and then adding/removing children of changed size as required, make the SV adapt to the changes? And last question: Is there a better aüpproach, except using ListViews?

    Read the article

  • Android - overlay small check icon over specific image in gridview or change border

    - by oscar
    I've just asked a question about an hour ago, while waiting for replies, I've thought maybe I can achieve what I want differently. I was thinking of changing the image but it would be better if I could perhaps overlay something over the top of complete levels in the gridview i.e a small tick icon At the moment, when a level has been completed I am storing that with sharedpreferences So I have a gridView layout to display images that represent levels. Let's just say for this example I have 20 levels. When one level is complete is it possible to overlay the tick icon or somehow highlight the level image. Maybe change the border of the image?? Here are the image arrays I use int[] imageIDs = { R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six etc....... and then I have my code to set the images in gridView. Obviously there is more code in between. public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(140, 140)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(5, 5, 5, 5); } else { imageView = (ImageView) convertView; } imageView.setImageResource(imageIDs[position]); return imageView; would it be possible to do any of the above, even the border method would be fine. Thanks for any help

    Read the article

  • ViewGroup{TextView,...}.getMeasuredHeight gives wrong value is smaller than real height.

    - by Dewr
    ViewGroup(the ViewGroup is containing TextViews having long text except line-feed-character).getMeasuredHeight returns wrong value... that is smaller than real height. how to get rid of this problem? here is the java code: ;public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; int count = listAdapter.getCount(); for (int i = 0; i < count; i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } ; and here is the list_item_comments.xml:; {RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" } {RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="8dip" android:layout_marginRight="8dip" } {TextView android:id="@+id/list_item_comments_nick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" style="@style/WhiteText" /} {TextView android:id="@+id/list_item_comments_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textSize="16sp" style="@style/WhiteText" /} {TextView android:id="@+id/list_item_comments_content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/list_item_comments_nick" android:autoLink="all" android:textSize="24sp" style="@style/WhiteText" /} {/RelativeLayout} {/RelativeLayout} ;

    Read the article

  • retrieve image from gallery in android

    - by smsys
    I have created an Activity where i have a Button. By pressing the button an android Gallery opens. When i choose an image from the gallery it is shows it in an ImageView of my Activity but after choosing second time the following error occuring 01-13 17:55:25.323: ERROR/AndroidRuntime(14899): java.lang.OutOfMemoryError: bitmap size exceeds VM budget Here is the source code i am using: public class MyImage extends Activity { /** Called when the activity is first created. */ Gallery gallery; private Uri[] mUrls; String[] mFiles=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); File images = Environment.getDataDirectory(); File[] imagelist = images.listFiles(); mFiles = new String[imagelist.length]; for(int i= 0 ; i< imagelist.length; i++) { mFiles[i] = imagelist[i].getAbsolutePath(); } mUrls = new Uri[mFiles.length]; for(int i=0; i < mFiles.length; i++) { mUrls[i] = Uri.parse(mFiles[i]); } Gallery g = (Gallery) findViewById(R.id.Gallery01); g.setAdapter(new ImageAdapter(this)); g.setFadingEdgeLength(40); } public class ImageAdapter extends BaseAdapter{ int mGalleryItemBackground; public ImageAdapter(Context c) { mContext = c; } public int getCount(){ return mUrls.length; } public Object getItem(int position){ return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent){ ImageView i = new ImageView(mContext); i.setImageURI(mUrls[position]); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams(new Gallery.LayoutParams(260, 210)); return i; } private Context mContext; } }

    Read the article

  • Programming powering off and powering on in one single OnClick function on android

    - by user1060919
    I would like to write an activity that after clicking on a button turns off the screen and then turns it back on after 2 secs. I tried using the following code in order to power off the screen: WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = 0/(float)255; getWindow().setAttributes(lp); But it would only take effect when then onClick function returns. I tried running it into a handler but with no success. I need to find a way to force the setting to get applied before the function returns so that I can call the power on function 2 secs later on the same onClick call. I also found it very hard to wakeup the device afterwards. While this code works if I power off the screen using the physical button it doesn't seem to work when the phone is powered off using the technique described previously. PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE ,"Dev Tag"); try { wl.acquire(); wl.release(); } catch (Exception e) { Toast.makeText(this, e.getMessage(),20).show(); } Thanks you in advance for your help!

    Read the article

  • Color banding only on Android 4.0+

    - by threeshinyapples
    On emulators running Android 4.0 or 4.0.3, I am seeing horrible colour banding which I can't seem to get rid of. On every other Android version I have tested, gradients look smooth. I have a SurfaceView which is configured as RGBX_8888, and the banding is not present in the rendered canvas. If I manually dither the image by overlaying a noise pattern at the end of rendering I can make the gradients smooth again, though obviously at a cost to performance which I'd rather avoid. So the banding is being introduced later. I can only assume that, on 4.0+, my SurfaceView is being quantized to a lower bit-depth at some point between it being drawn and being displayed, and I can see from a screen capture that gradients are stepping 8 values at a time in each channel, suggesting a quantization to 555 (not 565). I added the following to my Activity onCreate function, but it made no difference. getWindow().setFormat(PixelFormat.RGBA_8888); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER); I also tried putting the above in onAttachedToWindow() instead, but there was still no change. (I believe that RGBA_8888 is the default window format anyway for 2.2 and above, so it's little surprise that explicitly setting that format has no effect on 4.0+.) Which leaves the question, if the source is 8888 and the destination is 8888, what is introducing the quantization/banding and why does it only appear on 4.0+? Very puzzling. I wonder if anyone can shed some light?

    Read the article

  • Android - Turn off display without triggering sleep/lock screen - Turn on with Touchscreen

    - by NebulaSleuth
    I have been trying to find a way to turn off the display, and wake up from the user touching the touch screen. The device is in an embedded environment where the device is a tablet and the user does not have access to anything except the touch screen (no buttons at all). It is connected to power so the battery won't be a problem, but when I detect no activity I want to turn off the screen so it isn't staring them in the face all day and doesn't reduce the life the LCD backlight. I maintain a wakelock permanently and decide when to sleep myself. The problem is that when I turn off the screen using : WindowManager.LayoutParams params = getWindow().getAttributes(); params.screenBrightness = 0; getWindow().setAttributes(params); The activity gets paused and stopped. And the unit does not respond to a touch to wake it up. You need to press the power button. At that point the "slide to unlock" shows up. I want to turn off the display, and then stay running so I can detect a touch screen event and turn the display back on. I also tried turning the display to a brightness of 0.1, which works on some devices, but the device I need it to work on, only "dims" the display. I also tried this: // First Remove my FULL wakelock //then aquire a partial wake lock (which should turn off the display) PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag"); wl.acquire(); however this method does not turn off the display.

    Read the article

  • Android Gallery View Update Images

    - by xger86x
    Hi, i have a question about using GalleryView. At first, i set five "default images" to show from drawable directory. But after, i want to run an Async Task in which i download the images, save them and show them in the gallery. For that i created the following Adapter: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private ArrayList<Integer> mImageIds = new ArrayList<Integer>(); private ArrayList<Drawable> mImageDrawables = new ArrayList<Drawable>(); public ImageAdapter(Context c) { mContext = c; TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); } public void setPlaces(int count) { for (int i = 0; i < count; i++) { mImageIds.add(R.drawable.tournoimg); mImageDrawables.add(null); } } public void setDrawable(String resource, int position) { Drawable image = Drawable.createFromPath(resource); mImageDrawables.add(position, image); } public int getCount() { return mImageIds.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); if (mImageDrawables.get(position) == null) i.setImageResource(mImageIds.get(position)); else i.setImageDrawable(mImageDrawables.get(position)); i.setLayoutParams(new Gallery.LayoutParams(60, 78)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setBackgroundResource(mGalleryItemBackground); return i; } } } and the following Async Task private class FillImages extends AsyncTask<ArrayList<Place>, Void, Void> { protected Void doInBackground(ArrayList<Place>... listplaces) { ArrayList<Place> places = listplaces[0]; Iterator<Place> it = places.iterator(); int position = 0; while (it.hasNext()) { Place p = it.next(); saveImage(p.getImage(), p.getURLImage()); // Gallery g = (Gallery) findViewById(R.id.gallery); mImageAdapter.setDrawable(p.getImage(), position); position++; mImageAdapter.notifyDataSetChanged(); } return (null); } But when i run it i have this error: Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Any idea? Thanks

    Read the article

  • ListView item won't extend width to fill_parent

    - by slybloty
    I have a custom ViewGroup that inflates a ListView from an xml layout. The list item layout is inflated from another xml file. All of the views are set to fill_parent. The ListView fills its parent, but the ListView items don't. I've tried putting the ListView in a LinearLayout and assigning weight to it. Tried RelativeLayout as well. Also, I've built the ListView programmaticaly, without using the xml layout. Even changed the LayoutParams before adding the view to the ViewGroup. I've also taken in consideration these posts as well: Width of clickable area in ListView w/ onListItemClick, In Android, how can I set a ListView item's height and width?, Android Listview width prob. Any ideas to why the items don't extend to fill width? And how to extend them? MyViewGroup class: public class MyViewGroup extends ViewGroup { public MyViewGroup(Context context, AttributeSet attrs) { super(context, attrs); generateMyViewGroup(); } private void generateMyViewGroup() { ListView main = (ListView) View.inflate(getContext(), R.layout.layout_main, null); main.setAdapter(new MyAdapter(getContext())); this.addView(main); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { this.getChildAt(0).layout(l, t, r, b); } } ListView xml layout: <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="3dp" android:background="#77000000" android:cacheColorHint="#00000000" android:divider="#00000000" android:dividerHeight="0dp" android:drawSelectorOnTop="false" android:scrollbars="vertical" > </ListView> ListView item layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_main_category" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/mainBackground" android:gravity="fill_horizontal|center_vertical" android:orientation="vertical" > <TextView android:id="@+id/main_category" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:paddingBottom="7dp" android:paddingLeft="20dp" android:paddingRight="5dp" android:paddingTop="20dp" android:text="test" android:textColor="@color/mainCategory" android:textSize="15sp" android:textStyle="bold" /> </LinearLayout>

    Read the article

  • Gridview get image from JSON using AsyncTask

    - by kongkea
    This project I've done with image in my drawable but now I want to get image url from JSON by using Asynctask and display it. and I make php that provide a json string like below. I want to get path of image(url) by using AsyncTask from JSON. I want to use data from json instead of public mThumbId = {...}; {"count":"28","data": [{"id":"1", "first_name":"man", "last_name":"woman", "username":"man", "password":"4f70432e636970de9929bcc6f1b72412", "email":"[email protected]", "url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"}, {"id":"2", "first_name":"first", "last_name":"Last Name", "username":"user", "password":"1a1dc91c907325c69271ddf0c944bc72", "email":"[email protected]", "url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"}, {"id":"3", "first_name":"first", "last_name":"Last Name", "username":"user", "password":"1a1dc91c907325c69271ddf0c944bc72", "email":"0", "url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]} AndroidGridLayoutActivity GridView gridView = (GridView) findViewById(R.id.grid_view); gridView.setAdapter(new ImageAdapter(this)); gridView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent i = new Intent(getApplicationContext(), FullImageActivity.class); i.putExtra("id", position); startActivity(i); } }); ImageAdapter public class ImageAdapter extends BaseAdapter { private Context mContext; // Keep all Images in array public Integer[] mThumbIds = { R.drawable.pic_1, R.drawable.pic_2, R.drawable.pic_3, R.drawable.pic_4, R.drawable.pic_5, R.drawable.pic_6, R.drawable.pic_7, R.drawable.pic_8, R.drawable.pic_9, R.drawable.pic_10, R.drawable.pic_11, R.drawable.pic_12, R.drawable.pic_13, R.drawable.pic_14, R.drawable.pic_15 }; // Constructor public ImageAdapter(Context c){ mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return mThumbIds[position]; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(mThumbIds[position]); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setLayoutParams(new GridView.LayoutParams(70, 70)); return imageView; } } FullImageActivity Intent i = getIntent(); int position = i.getExtras().getInt("id"); ImageAdapter imageAdapter = new ImageAdapter(this); ImageView imageView = (ImageView) findViewById(R.id.full_image_view); imageView.setImageResource(imageAdapter.mThumbIds[position]);

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >