开发者

how to use sharedPreferences from alertbox?

开发者 https://www.devze.com 2023-04-10 19:17 出处:网络
Hi i created one media player. when my media player application load that time my dialog box also first display.... but now i am expecting only load once my dialog box..if i run 1st time in new device

Hi i created one media player. when my media player application load that time my dialog box also first display.... but now i am expecting only load once my dialog box..if i run 1st time in new device my application open dialog box otherwise show only video thumbnails......i confused please help me......

My coding:

public class videothumb extends Activity  
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    private final static String _ID = MediaStore.Video.Media._ID;
    private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
    private static final String NAME = null;
    //flag for which one is used for images selection
    private Gallery _gallery;
    private Cursor _cursor;
    private int _columnIndex;
    private int[] _videosId;
    private Uri _contentUri;
    //private int video_column_index;
    protected Context _context;
    boolean click = true;
    boolean setSilent;
    TextView tv;

    /** Called when the activity is first created. */
    @Override
public void onCreate(Bundle State) {
        super.onCreate(State);

        _context = getApplicationContext();

         setContentView(R.layout.main);
         AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

         // set the message to display
         alertbox.setMessage("Disclaimer popup window sample..");

         // set a positive/yes button and create a listener
         alertbox.setPositiveButton("Agree/Close", new DialogInterface.OnClickListener() {

             // do something when the button is clicked
             public void onClick(DialogInterface dialog, int arg1) {
                 dialog.cancel();

             }
         });

         // set a negative/no button and create a listener
         alertbox.setNegativeButton("Buy", new DialogInterface.OnClickListener() {

             // do something when the button is clicked
             public void onClick(DialogInterface arg0, int arg1) {
                 arg0.cancel();
             }
         });

         // display box
         alertbox.show();
         //set GridView for gallery
         _gallery = (Gallery) findViewById(R.id.videoGrdVw);


        //set default as external/sdcard uri
        _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
        //initialize the videos uri
        //showToast(_contentUri.getPath());
        initVideosId();
        //set gallery adapter

        setGalleryAdapter();

        // Use this to dismiss as per your need...
        // popUp.dismiss();



        }
  /*  @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
            Log.d(this.getClass().getName(), "menu button pressed");
          //  popUp.dismiss();
               return false;}
        return super.onKeyDown(keyCode, event);


    }*/      private void setGalleryAdapter() {
        _gallery.setAdapter(new VideoGalleryAdapter(_context));
        _gallery.setOnItemClickListener(videogridlistener);
        }
    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();

    editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }

    private void initVideosId() {
        try
        {
            //Here we set up a string array of the thumbnail ID column we want to get back
            String [] proj={_ID};
            // Now we create the cursor pointing to the external thumbnail store
            _cursor = managedQuery(_contentUri,
                    proj, // Which columns to return
                    null,       // WHERE clause; which rows to return (all rows)
                    null,       // WHERE clause selection arguments (none)
                    null); // Order-by clause (ascending by name)
            int count= _cursor.getCount();
            System.out.println("total"+_cursor.getCount());
            // We now get the column index of the thumbnail id
            _columnIndex = _cursor.getColumnIndex(_ID);
            //initialize
            _videosId = new int[count];
            //move position to first element
            _cursor.moveToFirst();           
            for(int i=0;i<count;i++)
            {           
                int id = _cursor.getInt(_columnIndex);
                //
                _videosId[i]= id;
                //
                _cursor.moveToNext();
                //
            }
        }catch(Exception ex)
        {
            showToast(ex.getMessage().toString());           
        }

    }
    protected void showToast(String msg)
    {
        Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
    }
    private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
            // Now we want to actually get the data location of the file
            String [] proj={MEDIA_DATA};
            // We request our cursor again
            _cursor = managedQuery(_contentUri,
                    proj, // Which columns to return
                    null,       // WHERE clause; which rows to return (all rows)
                    null,       // WHERE clause selection arguments (none)
                    null);
              //System.gc();
             // video_column_index = _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
              _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);

                // Lets move to the selected item in the cursor
                _cursor.moveToPosition(position);
              String filename = _cursor.getString(_columnIndex);
              Intent intent = new Intent(videothumb.this, ViewVideo.class);
              intent.putExtra("videofilename", filename);
              startActivity(intent);
              //showToast(filename);
             // Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();

        }
    };
    private class VideoGalleryAdapter extends BaseAdapter
    {
        int mGalleryItemBackground;
        public VideoGalleryAdapter(Context c)
        {

            _context = c;

            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();
        }
        public int getCount()
        {
            return _videosId.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 imgVw= new ImageView(_context);
            try
            {
                if(convertView!=null)
                {
                    imgVw= (ImageView) convertView;
                }
                imgVw.setImageBitmap(getImage(_videosId[position]));
                imgVw.setAdjustViewBounds(true);
                //imgVw.setBackgroundColor(Color.WHITE);
                imgVw.setLayoutParams(new Gallery.LayoutParams(750, 530));
                imgVw.setPadding(1,1,1,1);
                imgVw.setScaleType(ImageView.ScaleType.FIT_XY);

        }
            catch(Exception ex)
            {
                System.out.println("StartActivity:getView()-1    : ex " + ex.getClass() +", "+ ex.getMessage());
            }
            return imgVw;
        }

        // Create the thumbnail on the fly
        private Bitmap getImage(int id) {

            Bitmap originalImage = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
                    System.out.println("ff"+MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
                    //Bitmap bmp2 = BitmapFactory.decodeResource(getResources(),
                    //        R.drawable.ccc);
                    final int reflectionGap = 4;

                    int width = originalImage.getWidth();
                    int height = originalImage.getHeight();
                    //This will not scale but will flip on the Y axis
                            Matrix matrix = new Matrix();
                            matrix.preScale(1, -1);

                            //Create a Bitmap with the flip matix applied to it.
                            //We only want the bottom half of the image
                            Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);


                            //Create a new bitmap with same width but taller to fit reflection
                            Bitmap bitmapWithReflection = Bitmap.createBitmap(width
                              , (height + height/2), Config.ARGB_8888);

                           //Create a new Canvas with the bitmap that's big enough for
                           //the image plus gap plus reflection
                           Canvas canvas = new Canvas(bitmapWithReflection);
                           //Draw in the original image
                           canvas.scale((float) 1.0, (float) 1.0);
                           canvas.draw开发者_如何学CBitmap(originalImage, 0, 0, null);
                           canvas.drawBitmap(originalImage, new Matrix(), null);
                          // canvas.drawBitmap(bmp2, new Matrix(), null);

                           canvas.save();
                           //canvas.drawBitmap(originalImage, 0, 0, null);
                           //Draw in the gap
                           Paint deafaultPaint = new Paint();
                           canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
                           //Draw in the reflection
                           canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);

                           //Create a shader that is a linear gradient that covers the reflection
                           Paint paint = new Paint();
                           LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
                             bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
                             TileMode.CLAMP);
                           //Set the paint to use this shader (linear gradient)
                           paint.setShader(shader);
                           //Set the Transfer mode to be porter duff and destination in
                           paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
                           //Draw a rectangle using the paint with our linear gradient
                           canvas.drawRect(0, height, width,
                             bitmapWithReflection.getHeight() + reflectionGap, paint);

                           return bitmapWithReflection;
        }

    }

}


Check this Code, I edited your code using Shared Preference :

What i did is that , I kept a Flag in Shared Preference ,if the Application is launched it checks for value in Shared Preference , true -- Will not show Dialog , False -- Calls the Dialog Method and at the End of the Method it will change the Value to true , so next time it will shows Dialog.

public class Map_View extends Activity {
    //Shared Preferences Variables //
    static SharedPreferences settings;
    public static SharedPreferences.Editor editor;
    public static final String PREFS_NAME = "TEST";
//End 

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle State) {
    super.onCreate(State);

    _context = getApplicationContext();

     setContentView(R.layout.main);
     
    settings=getSharedPreferences(PREFS_NAME, 0);
    editor = settings.edit();
    
    if(settings.getBoolean("Alert_Dialog", false)==false){
         alert_dialog();
    }
     //set GridView for gallery
     _gallery = (Gallery) findViewById(R.id.videoGrdVw);


    //set default as external/sdcard uri
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //initialize the videos uri
    //showToast(_contentUri.getPath());
    initVideosId();
    //set gallery adapter

    setGalleryAdapter();
    }
    
    private void alert_dialog() {
        // TODO Auto-generated method stub
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
        alertbox.setMessage("Disclaimer popup window sample..");
        alertbox.setPositiveButton("Agree/Close", new DialogInterface.OnClickListener() {
        // do something when the button is clicked
        public void onClick(DialogInterface dialog, int arg1) {
          dialog.cancel();
        }
  });

  // set a negative/no button and create a listener
  alertbox.setNegativeButton("Buy", new DialogInterface.OnClickListener() {

      // do something when the button is clicked
      public void onClick(DialogInterface arg0, int arg1) {
          arg0.cancel();
      }
  });

  // display box
  alertbox.show();
  editor.putBoolean("Alert_Dialog", true);
  editor.commit();
}
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号