如何使用共享preferences从alertbox? [英] how to use sharedPreferences from alertbox?

查看:217
本文介绍了如何使用共享preferences从alertbox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我创建了一个媒体播放器。当我的媒体播放器应用程序中加载那个时候我的对话框也是第一个显示....但现在我只期待我的一次对话box..if我运行新设备第一次加载时我的应用程序打开的对话​​框中,否则只显示视频缩略图。 .....我弄得请帮我......

我的编码:

 公共类videothumb扩展活动
{
私人最终静态乌里MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    私人最终静态字符串_ID = MediaStore.Video.Media._ID;
    私人最终静态字符串MEDIA_DATA = MediaStore.Video.Media.DATA;
    私有静态最后弦乐NAME = NULL;
    //标志哪一个用于图像的选择
    私人画廊_gallery;
    私人光标_cursor;
    私人诠释_columnIndex;
    私人诠释[] _videosId;
    私人乌里_contentUri;
    //私人诠释video_column_index;
    受保护的语境_context;
    布尔点击= TRUE;
    布尔setSilent;
    TextView的电视;    / **当第一次创建活动调用。 * /
    @覆盖
公共无效的onCreate(捆绑州){
        super.onCreate(州);        _context = getApplicationContext();         的setContentView(R.layout.main);
         AlertDialog.Builder alertbox =新AlertDialog.Builder(本);         //设置为显示该消息
         alertbox.setMessage(免责声明弹出窗口样本..);         //设置正/ Yes按钮,并创建一个侦听器
         alertbox.setPositiveButton(同意/关闭,新DialogInterface.OnClickListener(){             单击该按钮时//做一些事情
             公共无效的onClick(DialogInterface对话框,INT ARG1){
                 dialog.cancel();             }
         });         //设置了负/否按钮,创建一个侦听器
         alertbox.setNegativeButton(买入,新DialogInterface.OnClickListener(){             单击该按钮时//做一些事情
             公共无效的onClick(DialogInterface为arg0,ARG1 INT){
                 arg0.cancel();
             }
         });         //显示框
         alertbox.show();
         //设置GridView控件的画廊
         _gallery =(图库论坛)findViewById(R.id.videoGrdVw);
        //设置默认为外部/ SD卡URI
        _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
        //初始化视频URI
        // showToast(_contentUri.getPath());
        initVideosId();
        //设置库适配器        setGalleryAdapter();        //使用这个解雇根据自己的需要...
        // popUp.dismiss();        }
  / * @覆盖
    公共布尔的onkeydown(INT键code,KeyEvent的事件){
        如果((键code == KeyEvent.KEY code_MENU)){
            Log.d(this.getClass()的getName(),菜单按钮pressed);
          // popUp.dismiss();
               返回false;}
        返回super.onKeyDown(键code,事件);
    } * /私人无效setGalleryAdapter(){
        _gallery.setAdapter(新VideoGalleryAdapter(_context));
        _gallery.setOnItemClickListener(videogridlistener);
        }
    @覆盖
    保护无效的onStop(){
       super.onStop();      //我们需要一个编辑器对象,以preference变化。
      //所有的对象都是从android.context.Context
      共享preferences设置= getShared preferences(preFS_NAME,0);
      共享preferences.Editor编辑= settings.edit();    editor.putBoolean(SILENTMODE,mSilentMode);      //提交的编辑!
      editor.commit();
    }    私人无效initVideosId(){
        尝试
        {
            //这里我们设置缩略图ID列的字符串数组,我们想回去
            的String [] = PROJ {_ ID};
            //现在我们创建光标指向外部缩略图店
            _cursor = managedQuery(_contentUri,
                    PROJ,//哪些列返回
                    空,// WHERE子句;该行返回(所有行)
                    空,// WHERE子句选择参数(无)
                    空值); //订单by子句(按名称升序)
            诠释计数= _cursor.getCount();
            的System.out.println(总+ _ cursor.getCount());
            //我们现在得到的缩略图ID的列索引
            _columnIndex = _cursor.getColumnIndex(_ID);
            //初始化
            _videosId =新INT [计数]
            //移动位置,第一个元素
            _cursor.moveToFirst();
            的for(int i = 0; I<计数;我++)
            {
                INT ID = _cursor.getInt(_columnIndex);
                //
                _videosId [I] = ID;
                //
                _cursor.moveToNext();
                //
            }
        }赶上(异常前)
        {
            showToast(ex.getMessage()的toString());
        }    }
    保护无效showToast(弦乐味精)
    {
        Toast.makeText(_context,味精,Toast.LENGTH_LONG).show();
    }
    私人AdapterView.OnItemClickListener videogridlistener =新OnItemClickListener(){
公共无效onItemClick(适配器视图父母,视图V,INT位置,长的id){
            //现在我们要真正得到的文件的数据位置
            的String [] = PROJ {MEDIA_DATA};
            //我们再次要求我们的光标
            _cursor = managedQuery(_contentUri,
                    PROJ,//哪些列返回
                    空,// WHERE子句;该行返回(所有行)
                    空,// WHERE子句选择参数(无)
                    空值);
              //System.gc();
             // video_column_index = _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
              _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);                //让移动到所选择的项目光标
                _cursor.moveToPosition(位置);
              字符串文件名= _cursor.getString(_columnIndex);
              意向意图=新意图(videothumb.this,ViewVideo.class);
              intent.putExtra(videofilename,文件名);
              startActivity(意向);
              // showToast(文件名);
             // Toast.makeText(videothumb.this,+位置,Toast.LENGTH_SHORT).show();        }
    };
    私有类VideoGalleryAdapter延伸BaseAdapter
    {
        INT mGalleryItemBackground;
        公共VideoGalleryAdapter(上下文C)
        {            _context = C;            TypedArray A = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground,0);
            a.recycle();
        }
        公众诠释getCount将()
        {
            返回_videosId.length;
        }
        公共对象的getItem(INT位置)
        {
            返回的位置;
        }
        众长getItemId(INT位置)
        {
            返回的位置;
        }
        公共查看getView(INT位置,查看convertView,父母的ViewGroup)
        {
            ImageView的imgVw =新ImageView的(_context);
            尝试
            {
                如果(convertView!= NULL)
                {
                    imgVw =(ImageView的)convertView;
                }
                imgVw.setImageBitmap(的getImage(_videosId [位置]));
                imgVw.setAdjustViewBounds(真);
                //imgVw.setBackgroundColor(Color.WHITE);
                imgVw.setLayoutParams(新Gallery.LayoutParams(750,530));
                (1,1,1,1)imgVw.setPadding;
                imgVw.setScaleType(ImageView.ScaleType.FIT_XY);        }
            赶上(异常前)
            {
                的System.out.println(StartActivity:getView() - 1:前+ ex.getClass()+,+ ex.getMessage());
            }
            返回imgVw;
        }        //动态创建缩略图
        私人位图的getImage(INT ID){            位图originalImage = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),身份证,MediaStore.Video.Thumbnails.MICRO_KIND,NULL);
                    的System.out.println(FF+ MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),身份证,MediaStore.Video.Thumbnails.MICRO_KIND,NULL));
                    //位图BMP2 = BitmapFactory.de codeResource(getResources()
                    // R.drawable.ccc);
                    最终诠释reflectionGap = 4;                    INT宽度= originalImage.getWidth();
                    INT高度= originalImage.getHeight();
                    //这不会规模,但会翻转Y轴
                            字模=新的Matrix();
                            矩阵preSCALE(1,-1)。                            //创建应用了翻盖MATIX位图。
                            //我们只想图像的下半部分
                            位图reflectionImage = Bitmap.createBitmap(originalImage,0,高度/ 2,宽度,高度/ 2,矩阵,假);
                            //创建一个具有相同的宽度,但高以适应反映新位图
                            位图bitmapWithReflection = Bitmap.createBitmap(宽
                              (高度+高度/ 2),Config.ARGB_8888);                           //创建这是足够大的位图新的画布
                           //图像加上缺口加反思
                           帆布帆布=新的Canvas(bitmapWithReflection);
                           //在原始图像中绘制
                           canvas.scale((浮点)1.0,(浮点)1.0);
                           canvas.drawBitmap(originalImage,0,0,NULL);
                           canvas.drawBitmap(originalImage,新的Matrix(),NULL);
                          // canvas.drawBitmap(BMP2,新的Matrix(),NULL);                           canvas.save();
                           //canvas.drawBitmap(originalImage,0,0,NULL);
                           //在间隙绘制
                           涂料deafaultPaint =新的油漆();
                           canvas.drawRect(0,高度,宽度,高度+ reflectionGap,deafaultPaint);
                           //在反射抽奖
                           canvas.drawBitmap(reflectionImage,0,高度+ reflectionGap,NULL);                           //创建着色器是覆盖反射的线性梯度
                           涂料粉刷=新的油漆();
                           的LinearGradient着色器=新的LinearGradient(0,originalImage.getHeight(),0,
                             bitmapWithReflection.getHeight()+ reflectionGap,0x70ffffff,至0x00FFFFFF,
                             TileMode.CLAMP);
                           //设置油漆使用着色器(线性渐变)
                           paint.setShader(着色器);
                           //设置传输模式是搬运工达夫和目的地
                           paint.setXfermode(新PorterDuffXfermode(Mode.DST_IN));
                           //使用描绘一个矩形,与我们的线性渐变
                           canvas.drawRect(0,高度,宽度,
                             bitmapWithReflection.getHeight()+ reflectionGap,油漆);                           返回bitmapWithReflection;
        }    }}


解决方案

勾选此code,我编辑使用共享preference您code:

我所做的是,我一直一个标志共享preference,如果应用程序启动它的共享preference检查值,
真实的 - 不会显示对话框,
假 - 调用对话的方法,并在方法结束,将值更改为真,那么下一次它会显示一个对话框

 公共类Map_View延伸活动{
    //共享preferences变量//
    静态共享preferences设置;
    公共静态共享preferences.Editor编辑;
    公共静态最后弦乐preFS_NAME =TEST;
//结束/ **当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑州){
    super.onCreate(州);    _context = getApplicationContext();     的setContentView(R.layout.main);    设置= getShared preferences(preFS_NAME,0);
    编辑= settings.edit();    如果(settings.getBoolean(Alert_Dialog,假)== FALSE){
         alert_dialog();
    }
     //设置GridView控件的画廊
     _gallery =(图库论坛)findViewById(R.id.videoGrdVw);
    //设置默认为外部/ SD卡URI
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //初始化视频URI
    // showToast(_contentUri.getPath());
    initVideosId();
    //设置库适配器    setGalleryAdapter();
    }    私人无效alert_dialog(){
        // TODO自动生成方法存根
        AlertDialog.Builder alertbox =新AlertDialog.Builder(本);
        alertbox.setMessage(免责声明弹出窗口样本..);
        alertbox.setPositiveButton(同意/关闭,新DialogInterface.OnClickListener(){
        单击该按钮时//做一些事情
        公共无效的onClick(DialogInterface对话框,INT ARG1){
          dialog.cancel();
        }
  });  //设置了负/否按钮,创建一个侦听器
  alertbox.setNegativeButton(买入,新DialogInterface.OnClickListener(){      单击该按钮时//做一些事情
      公共无效的onClick(DialogInterface为arg0,ARG1 INT){
          arg0.cancel();
      }
  });  //显示框
  alertbox.show();
  editor.putBoolean(Alert_Dialog,真正的);
  editor.commit();
}
  }

让,如果你发现任何困难我知道..

由于Venky ..

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.drawBitmap(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();
}
  }

Let me know if you find any Difficulty..

Thanks Venky..

这篇关于如何使用共享preferences从alertbox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆