Search Results

Search found 156 results on 7 pages for 'bitmapfactory'.

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

  • Android Bitmap: Collision Detecting

    - by Aekasitt Guruvanich
    I am writing an Android game right now and I would need some help in the collision of the Pawns on screen. I figured I could run a for loop on the Player class with all Pawn objects on the screen checking whether or not Width*Height intersects with each other, but is there a more efficient way to do this? And if you do it this way, many of the transparent pixel inside the rectangular area will also be considered as collision as well. Is there a way to check for collision between Bitmap on a Canvas that disregard transparent pixels? The class for player is below and the Pawn class uses the same method of display. Class Player { private Resources res; // Used for referencing Bitmap from predefined location private Bounds bounds; // Class that holds the boundary of the screen private Bitmap image; private float x, y; private Matrix position; private int width, height; private float velocity_x, velocity_y; public Player (Resources resources, Bounds boundary) { res = resources; bounds = boundary; image = BitmapFactory.decodeResource(res, R.drawable.player); width = image.getWidth(); height = image.getHeight(); position = new Matrix(); x = bounds.xMax / 2; // Initially puts the Player in the middle of screen y = bounds.yMax / 2; position.preTranslate(x,y); } public void draw(Canvas canvas) { canvas.drawBitmap(image, position, null); } }

    Read the article

  • Android save Checkbox State in ListView with Cursor Adapter

    - by Ricardo
    I cant find a way to save the checkbox state when using a Cursor adapter. Everything else works fine but if i click on a checkbox it is repeated when it is recycled. Ive seen examples using array adapters but because of my lack of experience im finding it hard to translate it into using a cursor adapter. Could someone give me an example of how to go about it. Any help appreciated. private class PostImageAdapter extends CursorAdapter { private static final int s = 0; private int layout; Bitmap bm=null; private String PostNumber; TourDbAdapter mDbHelper; public PostImageAdapter (Context context, int layout, Cursor c, String[] from, int[] to, String Postid) { super(context, c); this.layout = layout; PostNumber = Postid; mDbHelper = new TourDbAdapter(context); mDbHelper.open(); } @Override public View newView(Context context, final Cursor c, ViewGroup parent) { ViewHolder holder; LayoutInflater inflater=getLayoutInflater(); View row=inflater.inflate(R.layout.image_post_row, null); holder = new ViewHolder(); holder.Description = (TextView) row.findViewById(R.id.item_desc); holder.cb = (CheckBox) row.findViewById(R.id.item_checkbox); holder.DateTaken = (TextView) row.findViewById(R.id.item_date_taken); holder.Photo = (ImageView) row.findViewById(R.id.item_thumb); row.setTag(holder); int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE); String Date = c.getString(DateCol); int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION); String Description = c.getString(DescCol); int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME); final String FileName = c.getString(FileNameCol); int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID); String RowID = c.getString(PostRowCol); String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg"; Bitmap bm = BitmapFactory.decodeFile(Path, null); holder.Photo.setImageBitmap(bm); holder.DateTaken.setText(Date); holder.Description.setText(Description); holder.cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cBox = (CheckBox) v; if (cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, PostNumber); } else if (!cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, ""); } } }); return row; }; @Override public void bindView(View row, Context context, final Cursor c) { ViewHolder holder; holder = (ViewHolder) row.getTag(); int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE); String Date = c.getString(DateCol); int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION); String Description = c.getString(DescCol); int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME); final String FileName = c.getString(FileNameCol); int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID); String RowID = c.getString(PostRowCol); String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg"; Bitmap bm = BitmapFactory.decodeFile(Path, null); File x = null; holder.Photo.setImageBitmap(bm); holder.DateTaken.setText(Date); holder.Description.setText(Description); holder.cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cBox = (CheckBox) v; if (cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, PostNumber); } else if (!cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, ""); } } }); } } static class ViewHolder{ TextView Description; ImageView Photo; CheckBox cb; TextView DateTaken; } }

    Read the article

  • CustomListAdapter Problem in Android? Getting ClassCast Exception? How???

    - by Praveen Chandrasekaran
    i want to improve the list view's performance. this is the code for my getView method in my Adapter? public View getView(int arg0, View text_view_name, ViewGroup parent) { try { if (text_view_name == null) { text_view_name = mInflater.inflate( R.layout.bs_content_list_item1, null); text_view_name.setTag(R.id.text1_detail1, text_view_name .findViewById(R.id.text1_detail1)); text_view_name.setTag(R.id.text3_detail1, text_view_name .findViewById(R.id.text3_detail1)); text_view_name.setTag(R.id.eve_img_detail1, text_view_name .findViewById(R.id.eve_img_detail1)); } text1 = (TextView) text_view_name.getTag(R.id.text1_detail1); // text2 = (TextView) text_view_name.getTag(R.id.text2); text3 = (TextView) text_view_name.getTag(R.id.text3_detail1); img = (ImageView) text_view_name.getTag(R.id.eve_img_detail1); text1.setText(VAL1[arg0]); text3.setText(VAL3[arg0]); if (!mBusy) { img_value = new URL(VAL4[arg0]); mIcon11 = BitmapFactory.decodeStream(img_value.openConnection() .getInputStream()); img.setImageBitmap(mIcon11); text_view_name.setTag(R.id.eve_img_detail1, null); } else { img.setImageResource(R.drawable.icon); text_view_name.setTag(R.id.eve_img_detail1, text_view_name .findViewById(R.id.eve_img_detail1)); } } catch (Exception e) { name = "Exception in MultiLine_bar_details1 getView"; Log.v(TAG, name + e); } return text_view_name; } this is the code for scrollstatechanged method: public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: try { MultiLine_bar_details1.mBusy = false; int first = view.getFirstVisiblePosition(); int count = view.getCount(); for (int i = 0; i < count; i++) { ImageView t = (ImageView) view.getChildAt(i);// here getting the ClassCastException if (t.getTag(R.id.eve_img_detail1) != null) { MultiLine_bar_details1.img_value = new URL( MultiLine_bar_details1.VAL4[first + i]); MultiLine_bar_details1.mIcon11 = BitmapFactory .decodeStream(MultiLine_bar_details1.img_value .openConnection().getInputStream()); MultiLine_bar_details1.img.setImageBitmap(MultiLine_bar_details1.mIcon11); t.setTag(R.id.eve_img_detail1, null); } } } catch (Exception e) { Log.v(TAG, "Idle" + e); } // mStatus.setText("Idle"); break; case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: MultiLine_bar_details1.mBusy = true; break; case OnScrollListener.SCROLL_STATE_FLING: MultiLine_bar_details1.mBusy = true; break; } } getting the Exception in Idle state: 05-03 16:47:15.201: VERBOSE/BS_Bars(258): Idlejava.lang.ClassCastException: android.widget.LinearLayout this is very complicated for me to get the output properly. actually i have the listview with custom adapter. that icons makes the listview scroll very slow.i am getting the images for icons from the image urls. upto this(above code) i can improve the scroll performance of my list view. but the image icons are not proper in the corresponding order. its dynamically changing when i scroll the listview.. i refered the commonsware busy coder guide and this blog. My very Big question is "How can we access the single view in scrollstatechanged parameter AbsListView? " what is the problem in it? how to do it better? Any Idea?

    Read the article

  • CustomListAdapter Problem in Android? How???

    - by Praveen Chandrasekaran
    i want to improve the list view's performance. this is the code for my getView method in my Adapter? public View getView(int arg0, View text_view_name, ViewGroup parent) { try { if (text_view_name == null) { text_view_name = mInflater.inflate( R.layout.bs_content_list_item1, null); text_view_name.setTag(R.id.text1_detail1, text_view_name .findViewById(R.id.text1_detail1)); text_view_name.setTag(R.id.text3_detail1, text_view_name .findViewById(R.id.text3_detail1)); text_view_name.setTag(R.id.eve_img_detail1, text_view_name .findViewById(R.id.eve_img_detail1)); } text1 = (TextView) text_view_name.getTag(R.id.text1_detail1); // text2 = (TextView) text_view_name.getTag(R.id.text2); text3 = (TextView) text_view_name.getTag(R.id.text3_detail1); img = (ImageView) text_view_name.getTag(R.id.eve_img_detail1); text1.setText(VAL1[arg0]); text3.setText(VAL3[arg0]); if (!mBusy) { img_value = new URL(VAL4[arg0]); mIcon11 = BitmapFactory.decodeStream(img_value.openConnection() .getInputStream()); img.setImageBitmap(mIcon11); text_view_name.setTag(R.id.eve_img_detail1, null); } else { img.setImageResource(R.drawable.icon); text_view_name.setTag(R.id.eve_img_detail1, text_view_name .findViewById(R.id.eve_img_detail1)); } } catch (Exception e) { name = "Exception in MultiLine_bar_details1 getView"; Log.v(TAG, name + e); } return text_view_name; } this is the code for scrollstatechanged method: public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: try { MultiLine_bar_details1.mBusy = false; int first = view.getFirstVisiblePosition(); int count = view.getCount(); for (int i = 0; i < count; i++) { ImageView t = (ImageView) view.getChildAt(i); if (t.getTag(R.id.eve_img_detail1) != null) { MultiLine_bar_details1.img_value = new URL( MultiLine_bar_details1.VAL4[first + i]); MultiLine_bar_details1.mIcon11 = BitmapFactory .decodeStream(MultiLine_bar_details1.img_value .openConnection().getInputStream()); MultiLine_bar_details1.img.setImageBitmap(MultiLine_bar_details1.mIcon11); t.setTag(R.id.eve_img_detail1, null); } } } catch (Exception e) { Log.v(TAG, "Idle" + e); } // mStatus.setText("Idle"); break; case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: MultiLine_bar_details1.mBusy = true; break; case OnScrollListener.SCROLL_STATE_FLING: MultiLine_bar_details1.mBusy = true; break; } } this is very complicated for me to get the output properly. actually i have the listview with custom adapter. that icons makes the listview scroll very slow.i am getting the images for icons from the image urls. upto this(above code) i can improve the scroll performance of my list view. but the image icons are not proper in the corresponding order. its dynamically changing when i scroll the listview.. i refered the commonsware busy coder guide and this blog. My very Big question is "How can we access the single view in scrollstatechanged parameter AbsListView? " what is the problem in it? how to do it better? Any Idea?

    Read the article

  • Get the touch position inside the imageview in android

    - by Manikandan
    I have a imageview in my activity and I am able to get the position where the user touch the imageview, through onTouchListener. I placed another image where the user touch over that image. I need to store the touch position(x,y), and use it in another activity, to show the tags. I stored the touch position in the first activity. In the first activity, my imageview at the top of the screen. In the second activity its at the bottom of the screen. If I use the position stored from the first acitvity, it place the tag image at the top, not on the imageview, where I previously clicked in the first activity. Is there anyway to get the position inside the imageview. FirstActivity: cp.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub Log.v("touched x val of cap img >>", event.getX() + ""); Log.v("touched y val of cap img >>", event.getY() + ""); x = (int) event.getX(); y = (int) event.getY(); tag.setVisibility(View.VISIBLE); int[] viewCoords = new int[2]; cp.getLocationOnScreen(viewCoords); int imageX = x - viewCoords[0]; // viewCoods[0] is the X coordinate int imageY = y - viewCoords[1]; // viewCoods[1] is the y coordinate Log.v("Real x >>>",imageX+""); Log.v("Real y >>>",imageY+""); RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin); ImageView iv = new ImageView(Capture_Image.this); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.tag_icon_32); iv.setImageBitmap(bm); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = x; params.topMargin = y; rl.addView(iv, params); Intent intent= new Intent(Capture_Image.this,Tag_Image.class); Bundle b=new Bundle(); b.putInt("xval", imageX); b.putInt("yval", imageY); intent.putExtras(b); startActivity(intent); return false; } }); In TagImage.java I used the following: im = (ImageView) findViewById(R.id.img_cam22); b=getIntent().getExtras(); xx=b.getInt("xval"); yy=b.getInt("yval"); im.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int[] viewCoords = new int[2]; im.getLocationOnScreen(viewCoords); int imageX = xx + viewCoords[0]; // viewCoods[0] is the X coordinate int imageY = yy+ viewCoords[1]; // viewCoods[1] is the y coordinate Log.v("Real x >>>",imageX+""); Log.v("Real y >>>",imageY+""); RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin); ImageView iv = new ImageView(Tag_Image.this); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.tag_icon_32); iv.setImageBitmap(bm); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( 30, 40); params.leftMargin =imageX ; params.topMargin = imageY; rl.addView(iv, params); return true; } });

    Read the article

  • Get item from spinner into url

    - by ShadowCrowe
    I searched for an answer but couldn't find it. The problem: Depending on the selected spinner-item the application should show a different image. At this moment I can't get it to work. The Url works like this: "my.site.com/images/" imc_met ".png" were imc_met is the filename. I can't get it to work. Btw the app isn't finished yet package example.myapplication; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; public class itemsActivity extends Activity { private Spinner spinner1, spinner2; private Button btnSubmit; private Bitmap image; private ImageView imageView; private String imc_met, imc; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.items); addItemsOnSpinner2(); addListenerOnButton(); addListenerOnSpinnerItemSelection(); } // add items into spinner dynamically public void addItemsOnSpinner2() { spinner2 = (Spinner) findViewById(R.id.spinner2); List<String> list = new ArrayList<String>(); list.add("list 1"); list.add("list 2"); list.add("list 3"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(dataAdapter); } public void addListenerOnSpinnerItemSelection() { spinner1 = (Spinner) findViewById(R.id.spinner1); spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener()); } // get the selected dropdown list value public void addListenerOnButton() { spinner1 = (Spinner) findViewById(R.id.spinner1); spinner2 = (Spinner) findViewById(R.id.spinner2); btnSubmit = (Button) findViewById(R.id.btnSubmit); spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(spinner1.getSelectedItem()!=null){ imc_met = spinner1.getSelectedItem().toString(); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); imageView = (ImageView)findViewById(R.id.ImageView01); btnSubmit.setOnClickListener(new OnClickListener() { public void onClick(View v) { URL url = null; try { url = new URL("my.site.com"); //here should the right link appear. } catch (MalformedURLException e) { e.printStackTrace(); } try { if (url != null) { image = BitmapFactory.decodeStream(url.openStream()); } } catch (IOException e) { e.printStackTrace(); } imageView.setImageBitmap(image); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

    Read the article

  • OutOfMemoryError: bitmap size exceeds VM budget :- Android

    - by Shalini Singh
    Hi! i am downloading images from Url and displaying them,,, at the downloading time it is giving "out of memory error : bitmap size exceeds VM budget" i am using drawable ... code is giving bellow: HttpClient httpclient= new DefaultHttpClient(); HttpResponse response=(HttpResponse)httpclient.execute(httpRequest); HttpEntity entity= response.getEntity(); BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); Bitmap bm = BitmapFactory.decodeStream(instream);` Bitmap useThisBitmap = Bitmap.createScaledBitmap(bm,bm.getWidth(),bm.getHeight(), true); bm.recycle(); BitmapDrawable bt= new BitmapDrawable(useThisBitmap); System.gc(); Error: 05-28 14:55:47.251: ERROR/AndroidRuntime(4188): java.lang.OutOfMemoryError: bitmap size exceeds VM budget Please help me,,,,

    Read the article

  • Android - Read PNG image without alpha and decode as ARGB_8888 Android

    - by loki666
    I try to read an image from sdcard (in emulator) and then create a Bitmap image with the "BitmapFactory.decodeByteArray" method. I set the options: options.inPrefferedConfig = Bitmap.Config.ARGB_8888 options.inDither = false Then I extract the pixels into a ByteBuffer. ByteBuffer buffer = ByteBuffer.allocateDirect(width*height*4) bitmap.copyPixelsToBuffer(buffer) I use this ByteBuffer then in the JNI to convert it into RGB format and want to calculate on it. But always I get false data - I test without modifying the ByteBuffer. Only thing I do is to put it into the native method into JNI. Then cast it into a unsigned char* and convert it back into a ByteBuffer before returning it back to Java. Before displaying the image I get data back with bitmap.copyPixelsFromBuffer( buffer ) But then it has wrong data in it. My Question is if this is because the image is internally converted into RGB 565 or what is wrong here? May anybody has an idea, it would be great!

    Read the article

  • Resizing and rotating an image in Android

    - by kingrichard2005
    I'm trying to rotate and resize an image in Android. The code I have is as follows, (taken from this tutorial): Bitmap originalSprite = BitmapFactory.decodeResource(getResources(), R.drawable.android); int orgHeight = a.getHeight(); int orgWidth = a.getWidth(); //Create manipulation matrix Matrix m = new Matrix(); // resize the bit map m.postScale(.25f, .25f); // rotate the Bitmap by the given angle m.postRotate(180); //Rotated bitmap Bitmap rotatedBitmap = Bitmap.createBitmap(originalSprite, 0, 0, orgWidth, orgHeight, m, true); return rotatedBitmap; The image seems to rotate just fine, but it doesn't scale like I expect it to. I've tried different values, but the image only gets more pixelized as I reduce the scale values, but remains that same size visually; whereas the goal I'm trying to achieve is to actually shrink it visually. I'm not sure what to do at this point, any help is appreciated.

    Read the article

  • Android: Changing LinearLayout in a widget.

    - by Profete162
    Hello all, I have this really annoying problem: In my widget, i would like to change the background by code. I noticed on the Google doc than I can easily change the background of an Imageview: remoteViews.setImageViewResource(R.id.my_iv, R.drawable.my_bg); Ok, too easy, i want to change now the Linear layout.. What I read about the remoteview id that I can change a Bitmap, Int, Bool, String, etc... but not a drawable. So i guess i cannot use: remoteViews.setBitmap(R.id.my_ll,"setBackgroundDrawable",BitmapFactory.decodeResource(context.getResources(), R.drawablemy_bg)); I am totally disapointed and tried a last idea: views.setInt(R.id.my_ll,"setBackgroundResource",R.drawable.my_bg); But The logcat told me: android.widget.RemoteViews$ActionException:view: android.widget.LinearLayout can't use method with RemoteViews: setBackgroundResource(int) I am totally lost and I really don't know what to do... I would really appreciate any help. Thank a lot!

    Read the article

  • Skia Decoder fails to decode remote Stream

    - by Samuh
    I am trying to open a remote Stream of a JPEG image and convert it into a Bitmap object: BitmapFactory.decodeStream( new URL("http://some.url.to/source/image.jpg") .openStream()); The decoder returns null and in the logs I get the following message: DEBUG/skia(xxxx): --- decoder->decode returned false Note: 1. the content length is non-zero and content type is image/jpeg 2. When I open the URL in browser I can see the image. What is that I am missing here? Please help. Thanks.

    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

  • Can you decode a mutable Bitmap from an InputStream?

    - by Daniel Lew
    Right now I've got an Android application that: Downloads an image. Does some pre-processing to that image. Displays the image. The dilemma is that I would like this process to use less memory, so that I can afford to download a higher-resolution image. However, when I download the image now, I use BitmapFactory.decodeStream(), which has the unfortunate side effect of returning an immutable Bitmap. As a result, I'm having to create a copy of the Bitmap before I can start operating on it, which means I have to have 2x the size of the Bitmap's memory allocated (at least for a brief period of time; once the copy is complete I can recycle the original). Is there a way to decode an InputStream into a mutable Bitmap?

    Read the article

  • how to retrieve data in image uri in sd card to read data in byte convertion

    - by narasimha
    hi sir i am implementing upload image click upload button then select into sdcard images i am getting uri File Img = new File(selectedImage.getPath()); System.out.println("2............."+Img); FileInputStream is = null; try { is = new FileInputStream(Img); is.read(buffer); BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm = BitmapFactory.decodeStream(is); bis.close(); is.close(); i got in image uri how can retrieve data in particular image uri in image path above code Img i am new in android then some suggition give me some reply

    Read the article

  • how can read data in image uri

    - by satyamurthy
    hi sir i am implementing image upload then i got image uri how can read data in image uri File Img = new File(selectedImage.getPath()+inFileType); System.out.println("2............."+Img); FileInputStream is = null; try { is = new FileInputStream(Img); is.read(buffer); BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm = BitmapFactory.decodeStream(is); bis.close(); is.close(); this code implementing i got uri how can read data

    Read the article

  • Error while applying overlay on a location on a Google map in Android

    - by Hiccup
    This is my Activity for getting Location: public class LocationActivity extends MapActivity{ Bundle bundle = new Bundle(); MapView mapView; MapController mc; GeoPoint p; ArrayList <String> address = new ArrayList<String>(); List<Address> addresses; private LocationManager locationManager; double lat, lng; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); mapView = (MapView) findViewById(R.id.mapView1); mapView.displayZoomControls(true); mc = mapView.getController(); LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); // criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); String strLocationProvider = lm.getBestProvider(criteria, true); //Location location = lm.getLastKnownLocation(strLocationProvider); Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); lat = (double) location.getLatitude(); lng = (double) location.getLongitude(); p = new GeoPoint( (int) (lat * 1E6), (int) (lng * 1E6)); mc.animateTo(p); mc.setZoom(17); MapOverlay mapOverlay = new MapOverlay(); List<Overlay> listOfOverlays = mapView.getOverlays(); listOfOverlays.clear(); listOfOverlays.add(mapOverlay); Geocoder gcd = new Geocoder(this, Locale.getDefault()); try { addresses = gcd.getFromLocation(lat,lng,1); if (addresses.size() > 0 && addresses != null) { address.add(addresses.get(0).getFeatureName()); address.add(addresses.get(0).getAdminArea()); address.add(addresses.get(0).getCountryName()); bundle.putStringArrayList("id1", address); } bundle.putDouble("lat", lat); bundle.putDouble("lon", lng); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class MapOverlay extends com.google.android.maps.Overlay { @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { super.draw(canvas, mapView, shadow); //---translate the GeoPoint to screen pixels--- Point screenPts = new Point(); mapView.getProjection().toPixels(p, screenPts); //---add the marker--- Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.logo); canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null); return true; } @Override public boolean onTouchEvent(MotionEvent event, MapView mapView) { //---when user lifts his finger--- if (event.getAction() == 1) { Bundle bundle = new Bundle(); ArrayList <String> address = new ArrayList<String>(); GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY()); Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocation( p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1); addOverLay(); MapOverlay mapOverlay = new MapOverlay(); Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.crumbs_logo); List<Overlay> listOfOverlays = mapView.getOverlays(); listOfOverlays.clear(); listOfOverlays.add(mapOverlay); String add = ""; if (addresses.size() > 0) { address.add(addresses.get(0).getFeatureName()); address.add(addresses.get(0).getLocality()); address.add(addresses.get(0).getAdminArea()); address.add(addresses.get(0).getCountryName()); bundle.putStringArrayList("id1", address); for(int i = 0; i <= addresses.size();i++) add += addresses.get(0).getAddressLine(i) + "\n"; } bundle.putDouble("lat", p.getLatitudeE6() / 1E6); bundle.putDouble("lon", p.getLongitudeE6() / 1E6); Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } return true; } else return false; } } public void onClick_mapButton(View v) { Intent intent = this.getIntent(); this.setResult(RESULT_OK, intent); intent.putExtras(bundle); finish(); } public void addOverLay() { MapOverlay mapOverlay = new MapOverlay(); List<Overlay> listOfOverlays = mapView.getOverlays(); listOfOverlays.clear(); listOfOverlays.add(mapOverlay); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } public void FindLocation() { LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // updateLocation(location); Toast.makeText( LocationActivity.this, String.valueOf(lat) + "\n" + String.valueOf(lng), 5000) .show(); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } } I face two problems here. One is that when I click (do a tap) on any location, the overlay is not changing to that place. Also, the app crashes when I am on the MapView page and I click on back button. What might be the error?

    Read the article

  • android steganography

    - by poo123
    Im doing steganography on android...my code is as below.. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.src); picw = mBitmap.getWidth(); pich = mBitmap.getHeight(); pix= new int[picw * pich]; mBitmap.getPixels(pix, 0, picw, 0, 0, picw, pich); try { FileOutputStream fos = super.openFileOutput("dest.png", MODE_WORLD_READABLE); mBitmap.compress(CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); }catch (Exception e) { tv.setText(e.getMessage()); } but whenever i save source image with Bitmap.compress() method pix[0] value before and after compression changed..so i'm unable to extract original data...please help me

    Read the article

  • Performance issues in android game

    - by user1446632
    I am making an android game, but however, the game is functioning like it should, but i am experiencing some performance issues. I think it has something to do with the sound. Cause each time i touch the screen, it makes a sound. I am using the standard MediaPlayer. The method is onTouchEvent() and onPlaySound1(). Could you please help me with an alternate solution for playing the sound? Thank you so much in advance! It would be nice if you also came up with some suggestions on how i can improve my code. Take a look at my code here: package com.mycompany.mygame; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; public class ExampleView extends SurfaceView implements SurfaceHolder.Callback { class ExampleThread extends Thread { private ArrayList<Parachuter> parachuters; private Bitmap parachuter; private Bitmap background; private Paint black; private boolean running; private SurfaceHolder mSurfaceHolder; private Context mContext; private Context mContext1; private Handler mHandler; private Handler mHandler1; private GameScreenActivity mActivity; private long frameRate; private boolean loading; public float x; public float y; public float x1; public float y1; public MediaPlayer mp1; public MediaPlayer mp2; public int parachuterIndexToResetAndDelete; public int canvasGetWidth; public int canvasGetWidth1; public int canvasGetHeight; public int livesLeftValue; public int levelValue = 1; public int levelValue1; public int parachutersDown; public int difficultySet; public boolean isSpecialAttackAvailible; public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler) { mSurfaceHolder = sHolder; mHandler = handler; mHandler1 = handler; mContext = context; mActivity = (GameScreenActivity) context; parachuters = new ArrayList<Parachuter>(); parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman); black = new Paint(); black.setStyle(Paint.Style.FILL); black.setColor(Color.GRAY); background = BitmapFactory.decodeResource(getResources(), R.drawable.gamescreenbackground); running = true; // This equates to 26 frames per second. frameRate = (long) (1000 / 26); loading = true; mp1 = MediaPlayer.create(getContext(), R.raw.bombsound); } @Override public void run() { while (running) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(); synchronized (mSurfaceHolder) { long start = System.currentTimeMillis(); doDraw(c); long diff = System.currentTimeMillis() - start; if (diff < frameRate) Thread.sleep(frameRate - diff); } } catch (InterruptedException e) { } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } protected void doDraw(Canvas canvas) { canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black); //Draw for (int i = 0; i < parachuters.size(); i++) { canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null); parachuters.get(i).tick(); } //Remove for (int i = 0; i < parachuters.size(); i++) { if (parachuters.get(i).getY() > canvas.getHeight()) { parachuters.remove(i); onPlaySound(); checkLivesLeftValue(); checkAmountOfParachuters(); } else if(parachuters.get(i).isTouched()) { parachuters.remove(i); } else{ //Do nothing } } } public void loadBackground(Canvas canvas) { //Load background canvas.drawBitmap(background, 0, 0, black); } public void checkAmountOfParachuters() { mHandler.post(new Runnable() { @Override public void run() { if(parachuters.isEmpty()) { levelValue = levelValue + 1; Toast.makeText(getContext(), "New level! " + levelValue, 15).show(); if (levelValue == 3) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); } else if (levelValue == 5) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); } else if (levelValue == 7) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); } else if (levelValue == 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else if (levelValue > 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else { //Draw normal 3 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); } } else { //Do nothing } } }); } private void checkLivesLeftValue() { mHandler.post(new Runnable() { @Override public void run() { Log.d("checkLivesLeftValue", "lives = " + livesLeftValue); // TODO Auto-generated method stub if (livesLeftValue == 3) { //Message to display: "You lost! Log.d("checkLivesLeftValue", "calling onMethod now"); parachuters.removeAll(parachuters); onMethod(); } else if (livesLeftValue == 2) { Toast.makeText(getContext(), "Lives left=1", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else if (livesLeftValue == 1) { Toast.makeText(getContext(), "Lives left=2", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else { //Set livesLeftValueText 3 Toast.makeText(getContext(), "Lives left=3", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } } }); } public void onMethod() { mHandler.post(new Runnable() { @Override public void run() { try { Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); ctx.startActivity(i); System.exit(0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //Exit activity and start playerLostMessageActivity Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); System.exit(0); ctx.startActivity(i); System.exit(0); } } }); } public void onPlaySound() { try { mp1.start(); } catch (Exception e) { e.printStackTrace(); mp1.release(); } } public void onDestroy() { try { parachuters.removeAll(parachuters); mp1.stop(); mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void onPlaySound1() { try { mp2 = MediaPlayer.create(getContext(), R.raw.airriflesoundeffect); mp2.start(); } catch (Exception e) { e.printStackTrace(); mp2.release(); } } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) releaseMediaPlayer(); x1 = event.getX(); y1 = event.getY(); checkAmountOfParachuters(); removeParachuter(); return false; } public void releaseMediaPlayer() { try { mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void removeParachuter() { try { for (Parachuter p: parachuters) { if (x1 > p.getX() && x1 < p.getX() + parachuter.getWidth() && y1 > p.getY() && y1 < p.getY() + parachuter.getHeight()) { p.setTouched(true); onPlaySound1(); parachutersDown = parachutersDown + 1; p.setTouched(false); } } } catch (Exception e) { e.printStackTrace(); } } public void initiateDrawParachuters() { drawParachutersGroup1(); } public void drawParachutersGroup1() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 77; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 14; y = 28; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 250; y = 94; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 275; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 280; y = 163; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 125; y = 118; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 126; y = 247; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 123; y = 77; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup2() { // TODO Auto-generated method stub //Parachuter group nr. 2 //Parachuter nr. 5 x = 153; y = 166; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 133; y = 123; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 170; y = 213; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 190; y = 121; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup3() { // TODO Auto-generated method stub //Parachuter group nr. 3 //Parachuter nr. 2 x = 267; y = 115; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 255; y = 183; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 170; y = 280; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 116; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 112; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 260; y = 89; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 260; y = 113; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 178; y = 25; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup4() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 166; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 118; y = 94; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 38; y = 55; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 57; y = 18; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 119; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 217; y = 113; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 245; y = 234; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 239; y = 44; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup5() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 59; y = 120; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 210; y = 169; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 199; y = 138; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 22; y = 307; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 195; y = 22; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 157; y = 132; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 183; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 130; y = 20; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup6() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 10; y = 10; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 20; y = 20; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 30; y = 30; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 60; y = 60; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 90; y = 90; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 120; y = 120; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 150; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 180; y = 180; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachuters() { Parachuter p = new Parachuter(x, y); parachuters.add(p); Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show(); } public void setRunning(boolean bRun) { running = bRun; } public boolean getRunning() { return running; } } /** Handle to the application context, used to e.g. fetch Drawables. */ private Context mContext; /** Pointer to the text view to display "Paused.." etc. */ private TextView mStatusText; /** The thread that actually draws the animation */ private ExampleThread eThread; public ExampleView(Context context) { super(context); // register our interest in hearing about changes to our surface SurfaceHolder holder = getHolder(); holder.addCallback(this); // create thread only; it's started in surfaceCreated() eThread = new ExampleThread(holder, context, new Handler() { @Override public void handleMessage(Message m) { // mStatusText.setVisibility(m.getData().getInt("viz")); // mStatusText.setText(m.getData().getString("text")); } }); setFocusable(true); } @Override public boolean onTouchEvent(MotionEvent event) { return eThread.onTouchEvent(event); } public ExampleThread getThread() { return eThread; } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { if (eThread.getState() == Thread.State.TERMINATED) { eThread = new ExampleThread(getHolder(), getContext(), getHandler()); eThread.start(); } else { eThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; eThread.setRunning(false); while (retry) { try { eThread.join(); retry = false; } catch (InterruptedException e) { } } } }

    Read the article

  • how to display complete Bitmap in android using Canvas?

    - by UMMA
    friends, i am using following onDraw method to display bitmap on screen. @Override public void onDraw(Canvas canvas) { Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.icon2); //ImageView img= new ImageView(Tutorial2D.this); //img.setImageBitmap(_scratch); canvas.drawColor(Color.BLACK); canvas.drawBitmap(_scratch, 0, 0, null); } image is displayed on the screen but some part because android screen is small how can i display complete image in whole android screen? can i set ScaleType of image to fitxy in canvas ? or can i add android layout image to this canvas so that i could set fitxy property or image there as i have commented the code? any help would be appreciated.

    Read the article

  • store image in sqlite

    - by bbkaaka
    i have the folloing code : final Gallery g = (Gallery) findViewById(R.id.gallery); g.setAdapter(new ImageAdapter(this)); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Bitmap b = null; b=BitmapFactory.decodeResource(getResources(),*********); b.compress(CompressFormat.PNG, 0, outputStream); AlertDialog.Builder builder = new AlertDialog.Builder(Edit.this); builder.setTitle("Comfirm"); builder.setMessage("Do you want to choose this picture?"); builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { image = outputStream.toByteArray(); } }); you see * which need type int like android.R.drawble.icon. i want to store the picture when users click to picture how can i get the picture

    Read the article

  • How do I get the raw dimensions of a bitmap in an ImageView?

    - by potatoe
    It seems like I might be overlooking something obvious, but I can't figure out how to retrieve the raw (unscaled) dimensions of a bitmap being displayed in an ImageView. For example, if I load a bitmap using Bitmap b = BitmapFactory.decodeResource(...), I can get those dimensions from b.getWidth() and b.getHeight(), and I could pass the bitmap into an ImageView using setImageBitmap(b). But if I have a subclass of ImageView, is there any way to retrieve those dimensions without having to pass them in explicitly? I guess I'm looking for a getImageBitmap() analog of ImageView's setImageBitmap() method, which would retrieve a Bitmap object that I can call getWidth() and getHeight() on. Any other way to retrieve the original dimensions would work too, though.

    Read the article

  • Get the current location of the Gps? Showing the default one

    - by Gagandeep
    Need help Urgent!!!!! Did changes with help but still unsuccessful... I have to request location updates, but I am unsuccessful in implementing that... i modified the code but need help so that i can see the current location. PLEASE look through my code and help please.. I am learning this and new to this concept and android.. any help would be appreciated here is my code: package com.GoogleMaps; import java.util.List; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; public class MapsActivity extends MapActivity { /** Called when the activity is first created. */ private MapView mapView; private LocationManager lm; private LocationListener ll; private MapController mc; GeoPoint p = null; Drawable defaultMarker = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView)findViewById(R.id.mapview); //show zoom in/out buttons mapView.setBuiltInZoomControls(true); //Standard view of the map(map/sat) mapView.setSatellite(false); // get zoom tool mapView.setBuiltInZoomControls(true); //get controller of the map for zooming in/out mc = mapView.getController(); // Zoom Level mc.setZoom(18); lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new MyLocationListener(); lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll); //Get the current location in start-up lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new MyLocationListener(); lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll); //Get the current location in start-up if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null){ GeoPoint p = new GeoPoint( (int)(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1000000), (int)(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000)); mc.animateTo(p); } MyLocationOverlay myLocationOverlay = new MyLocationOverlay(); List<Overlay> list = mapView.getOverlays(); list.add(myLocationOverlay); } protected class MyLocationOverlay extends com.google.android.maps.Overlay { @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { Paint paint = new Paint(); super.draw(canvas, mapView, shadow); GeoPoint p = null; // Converts lat/lng-Point to OUR coordinates on the screen. Point myScreenCoords = new Point(); mapView.getProjection().toPixels(p, myScreenCoords); paint.setStrokeWidth(1); paint.setARGB(255, 255, 255, 255); paint.setStyle(Paint.Style.STROKE); Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint); canvas.drawText("I am here...", myScreenCoords.x, myScreenCoords.y, paint); return true; } } private class MyLocationListener implements LocationListener{ public void onLocationChanged(Location argLocation) { // TODO Auto-generated method stub p = new GeoPoint((int)(argLocation.getLatitude()*1000000), (int)(argLocation.getLongitude()*1000000)); Toast.makeText(getBaseContext(), "New location latitude [" +argLocation.getLatitude() + "] longitude [" + argLocation.getLongitude()+"]", Toast.LENGTH_SHORT).show(); mc.animateTo(p); mapView.invalidate(); // call this so UI of map was updated } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } protected boolean isRouteDisplayed() { return false; } } catlog: 11-29 17:40:42.699: D/dalvikvm(371): GC_FOR_MALLOC freed 6074 objects / 369952 bytes in 74ms 11-29 17:40:42.970: I/MapActivity(371): Handling network change notification:CONNECTED 11-29 17:40:42.980: E/MapActivity(371): Couldn't get connection factory client 11-29 17:40:43.190: D/AndroidRuntime(371): Shutting down VM 11-29 17:40:43.190: W/dalvikvm(371): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 11-29 17:40:43.280: E/AndroidRuntime(371): FATAL EXCEPTION: main 11-29 17:40:43.280: E/AndroidRuntime(371): java.lang.NullPointerException 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.PixelConverter.toPixels(PixelConverter.java:71) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.PixelConverter.toPixels(PixelConverter.java:61) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.GoogleMaps.MapsActivity$MyLocationOverlay.draw(MapsActivity.java:106) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.MapView.onDraw(MapView.java:494) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6740) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1640) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1638) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6743) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.widget.FrameLayout.draw(FrameLayout.java:352) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1640) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1638) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6743) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.widget.FrameLayout.draw(FrameLayout.java:352) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1842) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.draw(ViewRoot.java:1407) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.performTraversals(ViewRoot.java:1163) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.os.Handler.dispatchMessage(Handler.java:99) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.os.Looper.loop(Looper.java:123) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.app.ActivityThread.main(ActivityThread.java:4627) 11-29 17:40:43.280: E/AndroidRuntime(371): at java.lang.reflect.Method.invokeNative(Native Method) 11-29 17:40:43.280: E/AndroidRuntime(371): at java.lang.reflect.Method.invoke(Method.java:521) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 11-29 17:40:43.280: E/AndroidRuntime(371): at dalvik.system.NativeStart.main(Native Method) 11-29 17:40:45.779: D/dalvikvm(371): GC_FOR_MALLOC freed 5970 objects / 506624 bytes in 1179ms 11-29 17:40:45.779: I/dalvikvm-heap(371): Grow heap (frag case) to 3.147MB for 17858-byte allocation 11-29 17:40:45.870: D/dalvikvm(371): GC_FOR_MALLOC freed 56 objects / 2304 bytes in 92ms 11-29 17:40:45.960: D/dalvikvm(371): GC_EXPLICIT freed 3459 objects / 196432 bytes in 74ms 11-29 17:40:48.310: D/dalvikvm(371): GC_EXPLICIT freed 116 objects / 41448 bytes in 68ms 11-29 17:40:49.540: I/Process(371): Sending signal. PID: 371 SIG: 9

    Read the article

  • while uploading image I get errors in logcat

    - by al0ne evenings
    I am uploading image and also sending some parameters with it. I am getting errors in my logcat while doing so. Here is my code public class Camera extends Activity { ImageView ivUserImage; Button bUpload; Intent i; int CameraResult = 0; Bitmap bmp; public String globalUID; UserFunctions userFunctions; String photoName; InputStream is; int serverResponseCode = 0; ProgressDialog dialog = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.camera); userFunctions = new UserFunctions(); globalUID = getIntent().getExtras().getString("globalUID"); Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show(); ivUserImage = (ImageView)findViewById(R.id.ivUserImage); bUpload = (Button)findViewById(R.id.bUpload); openCamera(); } private void openCamera() { i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, CameraResult); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK) { //set image taken from camera on ImageView Bundle extras = data.getExtras(); bmp = (Bitmap) extras.get("data"); ivUserImage.setImageBitmap(bmp); //Create new Cursor to obtain the file Path for the large image String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }; String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC"; //final String photoName = MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME; Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort); try { myCursor.moveToFirst(); //This will actually give you the file path location of the image. final String largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); //final String photoName = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)); //Log.e("URI", largeImagePath); File f = new File("" + largeImagePath); photoName = f.getName(); bUpload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true); new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { //tv.setText("uploading started....."); Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show(); } }); if(imageUpload(globalUID, largeImagePath)) { Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error uploading image", Toast.LENGTH_LONG).show(); } //Log.e("Response: ", response); //System.out.println("RES : " + response); } }).start(); } }); } finally { myCursor.close(); } //Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId)); //String imageUrl = getRealPathFromURI(uriLargeImage); } } public boolean imageUpload(String uid, String imagepath) { boolean success = false; //Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); Bitmap bitmapOrg = BitmapFactory.decodeFile(imagepath); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte [] ba = bao.toByteArray(); String ba1=Base64.encodeToString(ba, 0); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image",ba1)); nameValuePairs.add(new BasicNameValuePair("uid", uid)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if(response != null) { success = true; } is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); } dialog.dismiss(); return success; } Here is my logcat 06-23 11:54:48.555: E/AndroidRuntime(30601): FATAL EXCEPTION: Thread-11 06-23 11:54:48.555: E/AndroidRuntime(30601): java.lang.OutOfMemoryError 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.String.<init>(String.java:513) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:650) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.StringBuilder.toString(StringBuilder.java:664) 06-23 11:54:48.555: E/AndroidRuntime(30601): at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:170) 06-23 11:54:48.555: E/AndroidRuntime(30601): at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:71) 06-23 11:54:48.555: E/AndroidRuntime(30601): at com.zafar.login.Camera.imageUpload(Camera.java:155) 06-23 11:54:48.555: E/AndroidRuntime(30601): at com.zafar.login.Camera$1$1.run(Camera.java:119) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.Thread.run(Thread.java:1019) 06-23 11:54:53.960: E/WindowManager(30601): Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here 06-23 11:54:53.960: E/WindowManager(30601): android.view.WindowLeaked: Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here 06-23 11:54:53.960: E/WindowManager(30601): at android.view.ViewRoot.<init>(ViewRoot.java:266) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:174) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:117) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.Window$LocalWindowManager.addView(Window.java:424) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.Dialog.show(Dialog.java:241) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ProgressDialog.show(ProgressDialog.java:107) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ProgressDialog.show(ProgressDialog.java:90) 06-23 11:54:53.960: E/WindowManager(30601): at com.zafar.login.Camera$1.onClick(Camera.java:110) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.View.performClick(View.java:2538) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.View$PerformClick.run(View.java:9152) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Handler.handleCallback(Handler.java:587) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Handler.dispatchMessage(Handler.java:92) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Looper.loop(Looper.java:130) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ActivityThread.main(ActivityThread.java:3691) 06-23 11:54:53.960: E/WindowManager(30601): at java.lang.reflect.Method.invokeNative(Native Method) 06-23 11:54:53.960: E/WindowManager(30601): at java.lang.reflect.Method.invoke(Method.java:507) 06-23 11:54:53.960: E/WindowManager(30601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 06-23 11:54:53.960: E/WindowManager(30601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 06-23 11:54:53.960: E/WindowManager(30601): at dalvik.system.NativeStart.main(Native Method) 06-23 11:54:55.190: I/Process(30601): Sending signal. PID: 30601 SIG: 9

    Read the article

  • Sprite animation in openGL - Some frames are being skipped

    - by Sid
    Earlier, I was facing problems on implementing sprite animation in openGL ES. Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it. What I need : A sprite animation should stop at the last frame without skipping any frame. What I did : Collision Detection function and working properly. PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case. ------------------------ EDIT----------------------- My sprite sheet. Consider the animation from Left to right and then from top to bottom Here is an image for a better understanding. My spritesheet ... class FragileSquare{ FloatBuffer fVertexBuffer, mTextureBuffer; ByteBuffer mColorBuff; ByteBuffer mIndexBuff; int[] textures = new int[1]; public boolean beingHitFromBall = false; int numberSprites = 20; int columnInt = 4; //number of columns as int float columnFloat = 4.0f; //number of columns as float float rowFloat = 5.0f; int oldIdx; public FragileSquare() { // TODO Auto-generated constructor stub float vertices [] = {-1.0f,1.0f, //byte index 0 1.0f, 1.0f, //byte index 1 //byte index 2 -1.0f, -1.0f, 1.0f,-1.0f}; //byte index 3 float textureCoord[] = { 0.0f,0.0f, 0.25f,0.0f, 0.0f,0.20f, 0.25f,0.20f }; byte indices[] = {0, 1, 2, 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float byteBuffer.order(ByteOrder.nativeOrder()); fVertexBuffer = byteBuffer.asFloatBuffer(); fVertexBuffer.put(vertices); fVertexBuffer.position(0); ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4); byteBuffer2.order(ByteOrder.nativeOrder()); mTextureBuffer = byteBuffer2.asFloatBuffer(); mTextureBuffer.put(textureCoord); mTextureBuffer.position(0); } public void draw(GL10 gl){ gl.glFrontFace(GL11.GL_CW); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); if(MyRender.flag2==1){ /** Collision has taken place*/ int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); oldIdx = idx; } gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4 gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5 gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7 gl.glFrontFace(GL11.GL_CCW); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glLoadIdentity(); gl.glMatrixMode(GL10.GL_MODELVIEW); } public void loadFragileTexture(GL10 gl, Context context, int resource) { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource); gl.glGenTextures(1, textures, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); }

    Read the article

  • Switching my collision detection to array lists caused it to stop working

    - by Charlton Santana
    I have made a collision detection system which worked when I did not use array list and block generation. It is weird why it's not working but here's the code, and if anyone could help I would be very grateful :) The first code if the block generation. private static final List<Block> BLOCKS = new ArrayList<Block>(); Random rnd = new Random(System.currentTimeMillis()); int randomx = 400; int randomy = 400; int blocknum = 100; String Title = "blocktitle" + blocknum; private Block block; public void generateBlocks(){ if(blocknum > 0){ int offset = rnd.nextInt(250) + 100; //500 is the maximum offset, this is a constant randomx += offset;//ofset will be between 100 and 400 int randomyoff = rnd.nextInt(80); //500 is the maximum offset, this is a constant randomy = platformheighttwo - 6 - randomyoff;//ofset will be between 100 and 400 block = new Block(BitmapFactory.decodeResource(getResources(), R.drawable.block2), randomx, randomy); BLOCKS.add(block); blocknum -= 1; } The second is where the collision detection takes place note: the block.draw(canvas); works perfectly. It's the blocks that don't work. for(Block block : BLOCKS) { block.draw(canvas); if (sprite.bottomrx < block.bottomrx && sprite.bottomrx > block.bottomlx && sprite.bottomry < block.bottommy && sprite.bottomry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } // bottom left touching block? if (sprite.bottomlx < block.bottomrx && sprite.bottomlx > block.bottomlx && sprite.bottomly < block.bottommy && sprite.bottomly > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } // top right touching block? if (sprite.toprx < block.bottomrx && sprite.toprx > block.bottomlx && sprite.topry < block.bottommy && sprite.topry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } //top left touching block? if (sprite.toprx < block.bottomrx && sprite.toprx > block.bottomlx && sprite.topry < block.bottommy && sprite.topry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } } The values eg bottomrx are in the block.java file..

    Read the article

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