问:
Recycler view is not refreshed when i delete an item from recycler view?
When I try to delete an item from recyclerview (Full Image Activity), I call onfinish() method to go back to previous activity i.e recyclerview(GalleryActivity).

But the image which I delete is still visible and when I exit the gallery Activity and enter again then it is refreshed.

Any Solution to it, so that it can refresh when the item is deleted.When i delete an image this thing appears

This is my Recyclerview Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter {

```<code>private ArrayList<String> yeniliste;
private Context context;

public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
    this.yeniliste = itemList;
    this.context = context;
}

@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
    return rcv;
}

@Override
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) {
    Bitmap bitmap = BitmapFactory.decodeFile(yeniliste.get(position));
    holder.countryPhoto.setImageBitmap(bitmap);
    holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(),GalleryFullImage.class);
            intent.putExtra("realid",String.valueOf(holder.getAdapterPosition()));
            v.getContext().startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return this.yeniliste.size();
}

public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView countryPhoto;

    public RecyclerViewHolders(View itemView) {
        super(itemView);
        countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();

    }

}

public void removeItem(int position)
{
    yeniliste.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, yeniliste.size());
}}
</code>```

removeItem method is also not Working.
This is my Full Image Activity. When I delete Image from here. It is not refreshing GalleryActivity.

```<code>public class GalleryFullImage extends AppCompatActivity {
String idPath;
String realid;
ArrayList<String> stringList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_fullimage);

    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    Intent i = getIntent();
    idPath = i.getStringExtra("realid");
    realid = stringList.get(Integer.parseInt(idPath));
    Log.d("wow",realid);
    File imgFile = new  File(realid);
    if(imgFile.exists()) {
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        ImageView myImage = (ImageView) findViewById(R.id.gallery_fullimg);
        myImage.setImageBitmap(myBitmap);
        myImage.setOnTouchListener(new ImageMatrixTouchHandler(getApplicationContext()));
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.delete, menu);

    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    final int id = item.getItemId();

    if (id == R.id.action_delete) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(GalleryFullImage.this);
        alertDialog.setTitle("Confirm Delete...");
        alertDialog.setMessage("Are you sure you want delete this?");
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
                rcAdapter.removeItem(Integer.parseInt(idPath));
                File file = new File(realid);
                boolean deleted = file.delete();
                Log.v("log_tag","deleted: " + deleted);
                Toast.makeText(GalleryFullImage.this,"File Deleted", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        alertDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}}
</code>```

This is GalleryActivity
.

```<code>public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gallery);
    setTitle("Gallery");
    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
    rView.setHasFixedSize(true);
    rView.setLayoutManager(layoutManager);
    RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
    rView.setAdapter(rcAdapter);

}
@Override
protected void onResume() {
    super.onResume();
}}
</code>```

答:
set your code in setImage() method like that call this method in onCreate and onResume  :-

```<code>   public void setImage(){
   stringList.clear();
   String targetPath=
    Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
Arrays.sort( files, new Comparator()
{
    public int compare(Object o1, Object o2) {

        if (((File)o1).lastModified() > ((File)o2).lastModified()) {
            return -1;
        } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
            return +1;
        } else {
            return 0;
        }
    }

});
for (File file : files){
    stringList.add(file.getAbsolutePath());
}

RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
rView.setAdapter(rcAdapter);

}
</code>```

Hope this is Helpful;

Body:
When I try to delete an item from recyclerview (Full Image Activity), I call onfinish() method to go back to previous activity i.e recyclerview(GalleryActivity).

But the image which I delete is still visible and when I exit the gallery Activity and enter again then it is refreshed.

Any Solution to it, so that it can refresh when the item is deleted.When i delete an image this thing appears

This is my Recyclerview Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter {

private ArrayList<String> yeniliste;
private Context context;

public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
    this.yeniliste = itemList;
    this.context = context;
}

@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
    return rcv;
}

@Override
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) {
    Bitmap bitmap = BitmapFactory.decodeFile(yeniliste.get(position));
    holder.countryPhoto.setImageBitmap(bitmap);
    holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(),GalleryFullImage.class);
            intent.putExtra("realid",String.valueOf(holder.getAdapterPosition()));
            v.getContext().startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return this.yeniliste.size();
}

public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView countryPhoto;

    public RecyclerViewHolders(View itemView) {
        super(itemView);
        countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();

    }

}

public void removeItem(int position)
{
    yeniliste.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, yeniliste.size());
}}

removeItem method is also not Working.
This is my Full Image Activity. When I delete Image from here. It is not refreshing GalleryActivity.

public class GalleryFullImage extends AppCompatActivity {
String idPath;
String realid;
ArrayList<String> stringList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_fullimage);

    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    Intent i = getIntent();
    idPath = i.getStringExtra("realid");
    realid = stringList.get(Integer.parseInt(idPath));
    Log.d("wow",realid);
    File imgFile = new  File(realid);
    if(imgFile.exists()) {
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        ImageView myImage = (ImageView) findViewById(R.id.gallery_fullimg);
        myImage.setImageBitmap(myBitmap);
        myImage.setOnTouchListener(new ImageMatrixTouchHandler(getApplicationContext()));
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.delete, menu);

    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    final int id = item.getItemId();

    if (id == R.id.action_delete) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(GalleryFullImage.this);
        alertDialog.setTitle("Confirm Delete...");
        alertDialog.setMessage("Are you sure you want delete this?");
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
                rcAdapter.removeItem(Integer.parseInt(idPath));
                File file = new File(realid);
                boolean deleted = file.delete();
                Log.v("log_tag","deleted: " + deleted);
                Toast.makeText(GalleryFullImage.this,"File Deleted", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        alertDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}}

This is GalleryActivity
.

public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gallery);
    setTitle("Gallery");
    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
    rView.setHasFixedSize(true);
    rView.setLayoutManager(layoutManager);
    RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
    rView.setAdapter(rcAdapter);

}
@Override
protected void onResume() {
    super.onResume();
}}

Body:
set your code in setImage() method like that call this method in onCreate and onResume  :-

   public void setImage(){
   stringList.clear();
   String targetPath=
    Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
Arrays.sort( files, new Comparator()
{
    public int compare(Object o1, Object o2) {

        if (((File)o1).lastModified() > ((File)o2).lastModified()) {
            return -1;
        } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
            return +1;
        } else {
            return 0;
        }
    }

});
for (File file : files){
    stringList.add(file.getAbsolutePath());
}

RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
rView.setAdapter(rcAdapter);

}

Hope this is Helpful;


来源: stackexchange

问:
Recyclerview in tablets is being called multiple times on lollipop or lower devices
I know this sounds kind of crazy, but my recyclerview adapter for tablets is behaving differently for different android versions. In my marshmallow tablet its working fine, i.e it only loads the views which are visible on the screen and loads the remaining views only when scrolling is done.

But when testing with other android versions(lollipop and below), it seems to be loading every view in my array without scrolling the recyclerview. And the whole array is loaded 4 or 5 times without doing anything.

This causes my app to freeze while scrolling in these devices.

I don't think its a problem with the code because it works perfectly in marshmallow tablets.

So can anyone please tell me what the problem might be??

I hope my question in clear enough.

Here is my adapter code, just in case.

```<code>public class MagazineTOC_Tab_Adapter extends
    RecyclerView.Adapter<MagazineTOC_Tab_Adapter.TOCHolder> {
private ArrayList<Category> magazineCategoryList;
private ArrayList<ArticlesItem> magazineArticleList;
private Context mContext;
private AccessPreference mAccessPreference;
private OnArticleclickListener mOnTOCclickListener;
private final int CATEGORY = 301,TYPE_THREE_AD = 601,TYPE_ONE_AD = 401,TYPE_TWO_AD = 501;

public MagazineTOC_Tab_Adapter(ArrayList<ArticlesItem> magazineArticleList, Context mContext) {
    this.magazineCategoryList = magazineCategoryList;
    this.magazineArticleList = magazineArticleList;
    this.mContext = mContext;
    this.mOnTOCclickListener = (OnArticleclickListener) mContext;
    this.mAccessPreference = new AccessPreference(mContext);

}

@Override
public TOCHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    switch(viewType)
    {
        case CATEGORY:
            View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_magazine_toc_tab, parent, false);
            TOCHolder myHeaderViewHolder = new TOCHolder(headerView, viewType);
            Log.d("CreateviewHolder", ""+CATEGORY);
            return myHeaderViewHolder;
        case TYPE_ONE_AD:
            View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_one, parent, false);
            TOCHolder adViewHolder = new TOCHolder(adView, viewType);
            Log.d("CreateviewHolder", ""+TYPE_ONE_AD);
            return adViewHolder;
        case TYPE_TWO_AD:
            View adView2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_two, parent, false);
            TOCHolder adViewHolder2 = new TOCHolder(adView2, viewType);
            Log.d("CreateviewHolder", ""+TYPE_TWO_AD);
            return adViewHolder2;
        case TYPE_THREE_AD:
            View adView3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_three, parent, false);
            TOCHolder adViewHolder3 = new TOCHolder(adView3, viewType);
            Log.d("CreateviewHolder", ""+TYPE_THREE_AD);
            return adViewHolder3;
    }
    return null;
}

@Override
public void onBindViewHolder(final TOCHolder holder,final int position) {
    if (magazineArticleList.get(position).getViewtype() == CATEGORY) {
        if(position==0)
        {
            Glide.get(mContext).clearMemory();
        }
        String category = magazineArticleList.
                get(position).getCategoryDescription();
        if (magazineArticleList.get(position).getLockStatus().equalsIgnoreCase("true")
                && ( !mAccessPreference.isLogin()
                ||  mAccessPreference.isSubscriptionExpired()
                ||  mAccessPreference.getSubscriberId().equalsIgnoreCase("") )
                ) {
            holder.mLoackImage.setImageResource(R.drawable.ic_lock);
        }
        else if(magazineArticleList.get(position).getReadStatus().equalsIgnoreCase("yes")){
            holder.mLoackImage.setImageResource(R.drawable.tick_gray);
        }
        else {
            holder.mLoackImage.setImageResource(R.drawable.ico_magazine_arrow);
        }

        if (position == 0) {
            holder.mAdViewTab.setVisibility(View.GONE);
            holder.mCategoryTitle.setVisibility(View.VISIBLE);
            holder.mTOCImage.setVisibility(View.VISIBLE);
            holder.subcat_row_title.setVisibility(View.VISIBLE);
            holder.subcat_row_title.setText(Html.fromHtml(magazineArticleList.
                    get(position).getSubCategory()));
        } else if (position > 0) {
            // loadAd(holder.mAdView);
            if (magazineArticleList.get(position).getSubCategory().equalsIgnoreCase("none")) {
                holder.subcat_row_title.setVisibility(View.GONE);
            } else if (magazineArticleList.get(position).getSubCategory().equalsIgnoreCase(magazineArticleList.get(position - 1).getSubCategory())) {
                holder.subcat_row_title.setVisibility(View.GONE);

            } else {
                holder.subcat_row_title.setVisibility(View.VISIBLE);
                holder.subcat_row_title.setText(Html.fromHtml(magazineArticleList.
                        get(position).getSubCategory()));
            }

            if (category.equalsIgnoreCase(magazineArticleList.
                    get(position - 1).getCategoryDescription())) {
                holder.mCategoryTitle.setVisibility(View.GONE);
                holder.mTOCImage.setVisibility(View.GONE);
                holder.mAdViewTab.setVisibility(View.GONE);
            } else {
                holder.mCategoryTitle.setVisibility(View.VISIBLE);
                holder.mTOCImage.setVisibility(View.VISIBLE);
                //   holder.mAdView.setVisibility(View.VISIBLE);
            }
        } else {
            holder.mCategoryTitle.setVisibility(View.VISIBLE);
            holder.mTOCImage.setVisibility(View.VISIBLE);
            //  holder.mAdView.setVisibility(View.VISIBLE);
        }
        holder.mCategoryTitle.setText(Html.fromHtml(category));
        holder.mTitleHeaderTxt.setText(Html.fromHtml(magazineArticleList.
                get(position).getArticleTitle()));

        if (magazineArticleList.
                get(position).getImagePath() != null)
            if (magazineArticleList.
                    get(position).getImagePath().length() > 0) {

                Glide.with(mContext)
                        .load(magazineArticleList.
                                get(position).getImagePath())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.placeholder)
                        .listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                Helper.getInstance().Log_error("IMAGE_@", "IMAGE ERROR" + e + " kjhg" + isFirstResource);
                                holder.mTOCImage.setVisibility(View.GONE);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                Helper.getInstance().Log_debug("IMAGE_@", "onResourceReady" + isFirstResource);
                                return false;
                            }
                        })
                        .into(holder.mTOCImage);
            } else {
                /**
                 * Video Url Empty
                 * ***/
                holder.mTOCImage.setVisibility(View.GONE);
                holder.playImg.setVisibility(View.GONE);
                holder.mTOCImage.setImageResource(R.drawable.placeholder_mag);
           // holder.playImg.setVisibility(View.VISIBLE);
            }

    } else {
            loadAd(holder.mAdViewTab, holder.adLayout);
            Log.d("CheckScroll", "onBindViewHolder: " + magazineArticleList.get(position).getViewtype()+"  po " +position);
        }

}

@Override
public int getItemViewType(int position) {
    Log.d("count", "getItemCount: "+position);
    return magazineArticleList.get(position).getViewtype();

}

@Override
public int getItemCount() {

    return magazineArticleList.size();

}

public class TOCHolder extends RecyclerView.ViewHolder {
    private TextView mTitleHeaderTxt, mTitleContenadtTxt, mCategoryTitle, subcat_row_title;
    private ImageView mTOCImage, mLoackImage, gray_arrow, playImg;
    private RelativeLayout contentBaseLayout,adLayout;
    private PublisherAdView mAdViewTab;

    public TOCHolder(View itemView, int viewType) {
        super(itemView);
        if (viewType == CATEGORY) {
            mTitleHeaderTxt = (TextView) itemView.findViewById(R.id.content_row_title);
            mCategoryTitle = (TextView) itemView.findViewById(R.id.txt_category);
            mTOCImage = (ImageView) itemView.findViewById(R.id.header_row_image);
            subcat_row_title = (TextView) itemView.findViewById(R.id.subcat_row_title);
            mLoackImage = (ImageView) itemView.findViewById(R.id.content_row_readimage);
            gray_arrow = (ImageView) itemView.findViewById(R.id.gray_arrow);
            playImg = (ImageView) itemView.findViewById(R.id.play_img);
            contentBaseLayout = (RelativeLayout) itemView.findViewById(R.id.content_root_layout);
            mAdViewTab = (PublisherAdView) itemView.findViewById(R.id.ad_view);
            gray_arrow.setVisibility(View.GONE);
            contentBaseLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    mOnTOCclickListener.onTOCitemClickListener(position, magazineArticleList.get(position).getLockStatus());
                }
            });
        } else {
            mAdViewTab = (PublisherAdView) itemView.findViewById(R.id.ad_view);
            adLayout = (RelativeLayout) itemView.findViewById(R.id.ad_rootView);
        }
    }
}

private void loadAd(final PublisherAdView mAdViewTab, final RelativeLayout adLayout) {
    try {
        if (Helper.isConnected(mContext)) {
            if (Helper.isTablet(HomePage.getInstance())) {

               // adLayout.setVisibility(View.GONE);
            }
           // mAdView.setVisibility(View.VISIBLE);
            PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
            mAdViewTab.loadAd(adRequest);

        } else {
            mAdViewTab.setVisibility(View.GONE);
            adLayout.setVisibility(View.GONE);

            notifyDataSetChanged();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
</code>```

Please help, thanks in advance.

答:
try break; keyword in your switch() condition this may work like above,</p>

```<code>  switch(viewType)
    {
        case CATEGORY:
            View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_magazine_toc_tab, parent, false);
            TOCHolder myHeaderViewHolder = new TOCHolder(headerView, viewType);
            Log.d("CreateviewHolder", ""+CATEGORY);
            return myHeaderViewHolder;
            break;
        case TYPE_ONE_AD:
            View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_one, parent, false);
            TOCHolder adViewHolder = new TOCHolder(adView, viewType);
            Log.d("CreateviewHolder", ""+TYPE_ONE_AD);
            return adViewHolder;
            break;
        case TYPE_TWO_AD:
            View adView2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_two, parent, false);
            TOCHolder adViewHolder2 = new TOCHolder(adView2, viewType);
            Log.d("CreateviewHolder", ""+TYPE_TWO_AD);
            return adViewHolder2;
            break;
        case TYPE_THREE_AD:
            View adView3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_three, parent, false);
            TOCHolder adViewHolder3 = new TOCHolder(adView3, viewType);
            Log.d("CreateviewHolder", ""+TYPE_THREE_AD);
            return adViewHolder3;
            break;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know this sounds kind of crazy, but my recyclerview adapter for tablets is behaving differently for different android versions. In my marshmallow tablet its working fine, i.e it only loads the views which are visible on the screen and loads the remaining views only when scrolling is done.

But when testing with other android versions(lollipop and below), it seems to be loading every view in my array without scrolling the recyclerview. And the whole array is loaded 4 or 5 times without doing anything.

This causes my app to freeze while scrolling in these devices.

I don't think its a problem with the code because it works perfectly in marshmallow tablets.

So can anyone please tell me what the problem might be??

I hope my question in clear enough.

Here is my adapter code, just in case.

public class MagazineTOC_Tab_Adapter extends
    RecyclerView.Adapter<MagazineTOC_Tab_Adapter.TOCHolder> {
private ArrayList<Category> magazineCategoryList;
private ArrayList<ArticlesItem> magazineArticleList;
private Context mContext;
private AccessPreference mAccessPreference;
private OnArticleclickListener mOnTOCclickListener;
private final int CATEGORY = 301,TYPE_THREE_AD = 601,TYPE_ONE_AD = 401,TYPE_TWO_AD = 501;

public MagazineTOC_Tab_Adapter(ArrayList<ArticlesItem> magazineArticleList, Context mContext) {
    this.magazineCategoryList = magazineCategoryList;
    this.magazineArticleList = magazineArticleList;
    this.mContext = mContext;
    this.mOnTOCclickListener = (OnArticleclickListener) mContext;
    this.mAccessPreference = new AccessPreference(mContext);

}

@Override
public TOCHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    switch(viewType)
    {
        case CATEGORY:
            View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_magazine_toc_tab, parent, false);
            TOCHolder myHeaderViewHolder = new TOCHolder(headerView, viewType);
            Log.d("CreateviewHolder", ""+CATEGORY);
            return myHeaderViewHolder;
        case TYPE_ONE_AD:
            View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_one, parent, false);
            TOCHolder adViewHolder = new TOCHolder(adView, viewType);
            Log.d("CreateviewHolder", ""+TYPE_ONE_AD);
            return adViewHolder;
        case TYPE_TWO_AD:
            View adView2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_two, parent, false);
            TOCHolder adViewHolder2 = new TOCHolder(adView2, viewType);
            Log.d("CreateviewHolder", ""+TYPE_TWO_AD);
            return adViewHolder2;
        case TYPE_THREE_AD:
            View adView3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_three, parent, false);
            TOCHolder adViewHolder3 = new TOCHolder(adView3, viewType);
            Log.d("CreateviewHolder", ""+TYPE_THREE_AD);
            return adViewHolder3;
    }
    return null;
}

@Override
public void onBindViewHolder(final TOCHolder holder,final int position) {
    if (magazineArticleList.get(position).getViewtype() == CATEGORY) {
        if(position==0)
        {
            Glide.get(mContext).clearMemory();
        }
        String category = magazineArticleList.
                get(position).getCategoryDescription();
        if (magazineArticleList.get(position).getLockStatus().equalsIgnoreCase("true")
                && ( !mAccessPreference.isLogin()
                ||  mAccessPreference.isSubscriptionExpired()
                ||  mAccessPreference.getSubscriberId().equalsIgnoreCase("") )
                ) {
            holder.mLoackImage.setImageResource(R.drawable.ic_lock);
        }
        else if(magazineArticleList.get(position).getReadStatus().equalsIgnoreCase("yes")){
            holder.mLoackImage.setImageResource(R.drawable.tick_gray);
        }
        else {
            holder.mLoackImage.setImageResource(R.drawable.ico_magazine_arrow);
        }

        if (position == 0) {
            holder.mAdViewTab.setVisibility(View.GONE);
            holder.mCategoryTitle.setVisibility(View.VISIBLE);
            holder.mTOCImage.setVisibility(View.VISIBLE);
            holder.subcat_row_title.setVisibility(View.VISIBLE);
            holder.subcat_row_title.setText(Html.fromHtml(magazineArticleList.
                    get(position).getSubCategory()));
        } else if (position > 0) {
            // loadAd(holder.mAdView);
            if (magazineArticleList.get(position).getSubCategory().equalsIgnoreCase("none")) {
                holder.subcat_row_title.setVisibility(View.GONE);
            } else if (magazineArticleList.get(position).getSubCategory().equalsIgnoreCase(magazineArticleList.get(position - 1).getSubCategory())) {
                holder.subcat_row_title.setVisibility(View.GONE);

            } else {
                holder.subcat_row_title.setVisibility(View.VISIBLE);
                holder.subcat_row_title.setText(Html.fromHtml(magazineArticleList.
                        get(position).getSubCategory()));
            }

            if (category.equalsIgnoreCase(magazineArticleList.
                    get(position - 1).getCategoryDescription())) {
                holder.mCategoryTitle.setVisibility(View.GONE);
                holder.mTOCImage.setVisibility(View.GONE);
                holder.mAdViewTab.setVisibility(View.GONE);
            } else {
                holder.mCategoryTitle.setVisibility(View.VISIBLE);
                holder.mTOCImage.setVisibility(View.VISIBLE);
                //   holder.mAdView.setVisibility(View.VISIBLE);
            }
        } else {
            holder.mCategoryTitle.setVisibility(View.VISIBLE);
            holder.mTOCImage.setVisibility(View.VISIBLE);
            //  holder.mAdView.setVisibility(View.VISIBLE);
        }
        holder.mCategoryTitle.setText(Html.fromHtml(category));
        holder.mTitleHeaderTxt.setText(Html.fromHtml(magazineArticleList.
                get(position).getArticleTitle()));

        if (magazineArticleList.
                get(position).getImagePath() != null)
            if (magazineArticleList.
                    get(position).getImagePath().length() > 0) {

                Glide.with(mContext)
                        .load(magazineArticleList.
                                get(position).getImagePath())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.placeholder)
                        .listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                Helper.getInstance().Log_error("IMAGE_@", "IMAGE ERROR" + e + " kjhg" + isFirstResource);
                                holder.mTOCImage.setVisibility(View.GONE);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                Helper.getInstance().Log_debug("IMAGE_@", "onResourceReady" + isFirstResource);
                                return false;
                            }
                        })
                        .into(holder.mTOCImage);
            } else {
                /**
                 * Video Url Empty
                 * ***/
                holder.mTOCImage.setVisibility(View.GONE);
                holder.playImg.setVisibility(View.GONE);
                holder.mTOCImage.setImageResource(R.drawable.placeholder_mag);
           // holder.playImg.setVisibility(View.VISIBLE);
            }

    } else {
            loadAd(holder.mAdViewTab, holder.adLayout);
            Log.d("CheckScroll", "onBindViewHolder: " + magazineArticleList.get(position).getViewtype()+"  po " +position);
        }

}

@Override
public int getItemViewType(int position) {
    Log.d("count", "getItemCount: "+position);
    return magazineArticleList.get(position).getViewtype();

}

@Override
public int getItemCount() {

    return magazineArticleList.size();

}

public class TOCHolder extends RecyclerView.ViewHolder {
    private TextView mTitleHeaderTxt, mTitleContenadtTxt, mCategoryTitle, subcat_row_title;
    private ImageView mTOCImage, mLoackImage, gray_arrow, playImg;
    private RelativeLayout contentBaseLayout,adLayout;
    private PublisherAdView mAdViewTab;

    public TOCHolder(View itemView, int viewType) {
        super(itemView);
        if (viewType == CATEGORY) {
            mTitleHeaderTxt = (TextView) itemView.findViewById(R.id.content_row_title);
            mCategoryTitle = (TextView) itemView.findViewById(R.id.txt_category);
            mTOCImage = (ImageView) itemView.findViewById(R.id.header_row_image);
            subcat_row_title = (TextView) itemView.findViewById(R.id.subcat_row_title);
            mLoackImage = (ImageView) itemView.findViewById(R.id.content_row_readimage);
            gray_arrow = (ImageView) itemView.findViewById(R.id.gray_arrow);
            playImg = (ImageView) itemView.findViewById(R.id.play_img);
            contentBaseLayout = (RelativeLayout) itemView.findViewById(R.id.content_root_layout);
            mAdViewTab = (PublisherAdView) itemView.findViewById(R.id.ad_view);
            gray_arrow.setVisibility(View.GONE);
            contentBaseLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    mOnTOCclickListener.onTOCitemClickListener(position, magazineArticleList.get(position).getLockStatus());
                }
            });
        } else {
            mAdViewTab = (PublisherAdView) itemView.findViewById(R.id.ad_view);
            adLayout = (RelativeLayout) itemView.findViewById(R.id.ad_rootView);
        }
    }
}

private void loadAd(final PublisherAdView mAdViewTab, final RelativeLayout adLayout) {
    try {
        if (Helper.isConnected(mContext)) {
            if (Helper.isTablet(HomePage.getInstance())) {

               // adLayout.setVisibility(View.GONE);
            }
           // mAdView.setVisibility(View.VISIBLE);
            PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
            mAdViewTab.loadAd(adRequest);

        } else {
            mAdViewTab.setVisibility(View.GONE);
            adLayout.setVisibility(View.GONE);

            notifyDataSetChanged();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Please help, thanks in advance.

Body:
try break; keyword in your switch() condition this may work like above,

  switch(viewType)
    {
        case CATEGORY:
            View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_magazine_toc_tab, parent, false);
            TOCHolder myHeaderViewHolder = new TOCHolder(headerView, viewType);
            Log.d("CreateviewHolder", ""+CATEGORY);
            return myHeaderViewHolder;
            break;
        case TYPE_ONE_AD:
            View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_one, parent, false);
            TOCHolder adViewHolder = new TOCHolder(adView, viewType);
            Log.d("CreateviewHolder", ""+TYPE_ONE_AD);
            return adViewHolder;
            break;
        case TYPE_TWO_AD:
            View adView2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_two, parent, false);
            TOCHolder adViewHolder2 = new TOCHolder(adView2, viewType);
            Log.d("CreateviewHolder", ""+TYPE_TWO_AD);
            return adViewHolder2;
            break;
        case TYPE_THREE_AD:
            View adView3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.rootview_toc_ad_three, parent, false);
            TOCHolder adViewHolder3 = new TOCHolder(adView3, viewType);
            Log.d("CreateviewHolder", ""+TYPE_THREE_AD);
            return adViewHolder3;
            break;
    }


问:
How can I access media files in CSS? Django
I'd like to do something like this:

```<code>div#city{
    background-image: url("{{ MEDIA_URL }}{{city.city_image}}");
}
</code>```

If I add the above as inline CSS within HTML it does produce the below path and it renders okay but I can't access it from CSS.

```<code><div class="container" style="background-image:url('media/city_pictures/paris-france.jpg');">
        <div class="city_header">
            <h1> PARIS </h1>
        </div>
</div>
</code>```

I can access Static images from CSS but not media images.

答:
User relative paths, for example:

```<code>background: url('../media/city_pictures.jpg');
</code>```

the above example is if media folder and your css folder is in the same folder.

Body:
I'd like to do something like this:

div#city{
    background-image: url("{{ MEDIA_URL }}{{city.city_image}}");
}

If I add the above as inline CSS within HTML it does produce the below path and it renders okay but I can't access it from CSS.

 PARIS

I can access Static images from CSS but not media images.

Body:
User relative paths, for example:

background: url('../media/city_pictures.jpg');

the above example is if media folder and your css folder is in the same folder.


问:
Where is my Electron App located
I have an electron app, that also operates on files in the same directory. These are not files the user selects, or files bundled inside the electron application, but I do need to reference them

for example:

/Users/test/Documents/myapp.app

/Users/test/Documents/example.zip

I need to know where that application is located, e.g.:

/Users/test/Documents

But instead when test.app is ran I get:

/Users/test/Documents/myapp.app/Contents/Resources/app/

Resulting in errors when it tries to access /Users/test/Documents/myapp.app/Contents/Resources/app/test.zip, or if I use a relative path, /test.zip.

How would I reliably access example.zip in this scenario? Note that I cannot bundle it with my app, it's being placed there by somebody else, so moving it is not an option, and it's a file I'm expecting to be there.

答:
You can use the fs.readdir function to list all the files that are in a particular directory (could be your app's or anywhere). You can make a directory from the code to put all the new files so it would be easier for you to list them out properly to process.

```<code>const testFolder = './tests/';
const fs         = require('fs');

fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
        console.log(file);
    });
});
</code>```

How do you get a list of the names of all files present in a directory in Node.js?

Title: Where is my Electron App located

Body:
You can use the fs.readdir function to list all the files that are in a particular directory (could be your app's or anywhere). You can make a directory from the code to put all the new files so it would be easier for you to list them out properly to process.

const testFolder = './tests/';
const fs         = require('fs');

fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
        console.log(file);
    });
});

How do you get a list of the names of all files present in a directory in Node.js?


问:
I'm getting a "Cannot find entry file index.android.js" error after upgrading to react-native 0.45 using react-native-git-upgrade
Before the upgrade I was using react-native 0.42 and everything worked. I even tried running a new project and still the same error. How do I fix this? Should I revert back to the older version?

React Native App Error

答:
This may happen if the 8081 port is used by any other app or service. If you are on a Linux or Mac, head to terminal and then

```<code>lsof -i :8081
</code>```

then you will get a list of ports, just select the one with name node and then

```<code>kill -9 <port-no>
</code>```

and then finally

```<code>npm start
</code>```

This should fix the problem

Body:
This may happen if the 8081 port is used by any other app or service. If you are on a Linux or Mac, head to terminal and then

lsof -i :8081

then you will get a list of ports, just select the one with name node and then

kill -9 <port-no>

and then finally

npm start

This should fix the problem


问:
Ionic 2 - How to Get data with Header Token? - Can't resolve all parameters for Headers
I'm new on Ionic2, I would really appreciate your help.
I need to get data from an login API, adding a token parameter in header.
Here is my service:

```<code>import { Injectable } from '@angular/core';
import { Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthProvider {
data:any;
  constructor(public http: Http) {
  }
  load() {
    if (this.data) {
      // already loaded data
      return Promise.resolve(this.data);
    }

    return new Promise(resolve => {
      let headers = new Headers();
     headers.append('token', '**HERE THE TOKEN**');

      this.http.get('**HERE THE API URL**', {"headers": headers})
        .map(res => res.json())
        .subscribe(data => {

          this.data = data;
          resolve(this.data);
        });
    });
  }
}
</code>```

When im run Ionic Serve, im getting a message:
Can't resolve all parameters for Headers: (?).

I have tried in Postman and the data is fetched correctly.
What can i do ?

I would really apreciate any help.

Thanks!

答:
As ,I go through the tutorials there I found that for using the header first you have to set the header value after that you may use the append for header. like

```<code> let headers = new Headers();
     headers.set('token', '**HERE THE TOKEN**');
</code>```

and you may also check Add header to API link here.

Body:
I'm new on Ionic2, I would really appreciate your help.
I need to get data from an login API, adding a token parameter in header.
Here is my service:

import { Injectable } from '@angular/core';
import { Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthProvider {
data:any;
  constructor(public http: Http) {
  }
  load() {
    if (this.data) {
      // already loaded data
      return Promise.resolve(this.data);
    }

    return new Promise(resolve => {
      let headers = new Headers();
     headers.append('token', '**HERE THE TOKEN**');

      this.http.get('**HERE THE API URL**', {"headers": headers})
        .map(res => res.json())
        .subscribe(data => {

          this.data = data;
          resolve(this.data);
        });
    });
  }
}

When im run Ionic Serve, im getting a message:
Can't resolve all parameters for Headers: (?).

I have tried in Postman and the data is fetched correctly.
What can i do ?

I would really apreciate any help.

Thanks!

Body:
As ,I go through the tutorials there I found that for using the header first you have to set the header value after that you may use the append for header. like

 let headers = new Headers();
     headers.set('token', '**HERE THE TOKEN**');

and you may also check Add header to API link here.


问:
How to modify only one element in a react .map function?
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case? </p>

```<code>changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>
        <div className="commentHolder" key={i}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}
</code>```

答:
You need to keep isReply to be an array of array and based on index of the comment clicked, update only the proper value, something like

```<code>state= {
   isReply: [[]]
}
changeIsReply(i, j) {
  var isReply = [...this.state.isReply]
  if(isReply[i] === undefined) {
    isReply.push([true]) =
  } else {
    if(isReply[i][j] === undefined) {
      isReply[i].push(true)
    } else {
       isReply[i][j] = !isReply[i][j]
    }
  }
  this.setState(
    {isReply}
  );
}

  render() {

  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data, i) =>
      data.map((secondData, j) =>
        <div className="commentHolder" key={j}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {() => this.changeIsReply(i, j)} > Reply </button>
            {this.state.isReply[i][j] ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}
</code>```

Body:
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case?

changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (

    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>

{secondData.text}

{secondData.category}

{secondData.organization}

            <button> UpButton </button>

            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}

      )
    )}

  )
}

Body:
You need to keep isReply to be an array of array and based on index of the comment clicked, update only the proper value, something like

state= {
   isReply: [[]]
}
changeIsReply(i, j) {
  var isReply = [...this.state.isReply]
  if(isReply[i] === undefined) {
    isReply.push([true]) =
  } else {
    if(isReply[i][j] === undefined) {
      isReply[i].push(true)
    } else {
       isReply[i][j] = !isReply[i][j]
    }
  }
  this.setState(
    {isReply}
  );
}

  render() {

  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data, i) =>
      data.map((secondData, j) =>
        <div className="commentHolder" key={j}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {() => this.changeIsReply(i, j)} > Reply </button>
            {this.state.isReply[i][j] ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}


问:
How to do Base64 Encoding while posting a html form?
I am stuck at one point where I need to encode the posted URL to Base64 while posting the Form in a cshtml page. We do have enctype property inside form element where we get 3 kinds of encoding, however due to some client requirement we need to encode the URL in Base64. Following is the form element:

```<code><body onload="document.getElementById('idPost').submit()">
    <form id="idPost" method="post" action= @System.Configuration.ConfigurationManager.AppSettings["postUrl"]
        style="margin: 0; padding: 0;">
        <fieldset style="border: 0">
            <h3 style="text-align: center;">We Are Signing You In, Please Wait...</h3>

            @Html.HiddenFor(model => model.agent);
             @Html.HiddenFor(model => model.User_ID);
            @Html.HiddenFor(model => model.Password);
            @Html.HiddenFor(model => model.errorUrl);
            @Html.HiddenFor(model => model.originalResourceUri);

        </fieldset>
    </form>
</body>
</code>```

Any help in getting this done would be appreciated.

答:
Convert your hidden field to base 64 string as

```<code> @Html.HiddenFor(model => Convert.ToBase64String(Encoding.UTF8.GetBytes(model.agent)));
</code>```

You can create extension method for same and do like

```<code>@Html.HiddenFor(model => model.agent.ToBase64())
</code>```

Body:
I am stuck at one point where I need to encode the posted URL to Base64 while posting the Form in a cshtml page. We do have enctype property inside form element where we get 3 kinds of encoding, however due to some client requirement we need to encode the URL in Base64. Following is the form element:

    <form id="idPost" method="post" action= @System.Configuration.ConfigurationManager.AppSettings["postUrl"]
        style="margin: 0; padding: 0;">
        <fieldset style="border: 0">

We Are Signing You In, Please Wait...

            @Html.HiddenFor(model => model.agent);
             @Html.HiddenFor(model => model.User_ID);
            @Html.HiddenFor(model => model.Password);
            @Html.HiddenFor(model => model.errorUrl);
            @Html.HiddenFor(model => model.originalResourceUri);

        </fieldset>
    </form>

Any help in getting this done would be appreciated.

Body:
Convert your hidden field to base 64 string as

 @Html.HiddenFor(model => Convert.ToBase64String(Encoding.UTF8.GetBytes(model.agent)));

You can create extension method for same and do like

@Html.HiddenFor(model => model.agent.ToBase64())


问:
Prgrammably making excel spreadsheets (97 - 2003 format)
I was wondering how difficult it would be to make an application like this. Basically, I have some old html files that use tables. I want to put these tables into excel for easier reading and manipulation. I only have text, I have no numbers of formulas or anything.

Are there any tutorials on how to do this sort of thing?

The application would produce .xls

Thanks

答: The simplest thing to do is simply create a CSV file.  If you have column headers, put them in the first row.  CSV files can be opened natively in Excel as if they were Excel spreadsheets.</p>

ContentLicense: CC BY-SA 2.5


问:
Unexpected token import with Webpack and Babel
I added react-router v4 to my project with Webpack and NodeJS. The app compiled correctly without any error messages in the log, but the browser console gave me this:

```<code>Uncaught SyntaxError: Unexpected token import
    at Object.<anonymous> (bundle.js:3391)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:11:25)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:24:27)
    at eval (eval at <anonymous> (bundle.js:1405), <anonymous>:25:30)
    at Object.<anonymous> (bundle.js:1405)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:3379), <anonymous>:12:17)
</code>```

I think that the problem is in the Webpack configuration. This is my webpack.config.js:

```<code>var path = require('path')
var webpack = require('webpack')
var NpmInstallPlugin = require('npm-install-webpack-plugin')
var autoprefixer = require('autoprefixer');
var precss = require('precss');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    'babel-polyfill',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new NpmInstallPlugin()
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loaders: ['eslint'],
        include: [
          path.resolve(__dirname, "src"),
        ],
      }
    ],
    loaders: [
      {
        loaders: ['react-hot', 'babel-loader'],
        include: [
          path.resolve(__dirname, "src"),
        ],
        test: /\.js$/,
        plugins: ['transform-runtime'],
        presets: ['es2015','react']
      },
      {
        test:   /\.css$/,
        loader: "style-loader!css-loader!postcss-loader"
      }
    ]
  },
  postcss: function () {
    return [autoprefixer, precss];
  }
}
</code>```

Here is my package.json file:

```<code>{
  "name": "redux-ru-tutorial",
  "version": "1.0.0",
  "description": "Redux RU tutorial",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "Yuriy Shipovalov",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.3.1",
    "babel-core": "^6.4.5",
    "babel-eslint": "^4.1.6",
    "babel-loader": "^6.2.1",
    "babel-plugin-transform-runtime": "^6.4.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "css-loader": "^0.23.1",
    "eslint": "^1.10.3",
    "eslint-loader": "^1.2.1",
    "eslint-plugin-react": "^3.16.1",
    "express": "^4.13.4",
    "npm-install-webpack-plugin": "^2.0.2",
    "postcss-loader": "^0.8.0",
    "precss": "^1.4.0",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.12",
    "webpack-dev-middleware": "^1.5.1",
    "webpack-hot-middleware": "^2.6.4"
  },
  "dependencies": {
    "babel-polyfill": "^6.3.14",
    "babel-runtime": "^6.3.19",
    "cors": "^2.8.3",
    "history": "^4.6.1",
    "jquery": "^3.2.1",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-redux": "^4.0.6",
    "react-redux-router": "0.0.5",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "redux": "^3.3.1",
    "redux-logger": "2.5.2",
    "redux-thunk": "1.0.3"
  }
}
</code>```

Here is my index.js file:

```<code>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import App from './containers/App'
import './styles/app.css'
import configureStore from './store/configureStore'

const store = configureStore()
console.log(store.getState())
render(
  <Provider store={store}>
      <Router>
          <Route> path="/" component={App}></Route>
      </Router>
  </Provider>,
  document.getElementById('root')
)
</code>```

答:
You're attempting to set Babel's plugins and presets directly in the Webpack configuration as part of module.loaders. This is incorrect. You have to pass it as options to the loader. The error is because you're passing the options incorrectly so Babel does not receive the options, and thus does not transpile your code based on the presets and thus the error.

Depending on your Webpack version, try:

Webpack 1.x

Since you have multiple loaders, you cannot set it in the query object. Instead, you are going to have to set your loader options inline:

```<code>{
    test: /\.js$/,
    loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=react?plugins[]=transform-runtime']
}
</code>```

This will directly pass the loader options to Babel through a query, but since you have two loaders Webpack didn't know which loader to query so you have to do it inline on one loader.

Body:
I added react-router v4 to my project with Webpack and NodeJS. The app compiled correctly without any error messages in the log, but the browser console gave me this:

Uncaught SyntaxError: Unexpected token import
    at Object.<anonymous> (bundle.js:3391)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:11:25)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:24:27)
    at eval (eval at <anonymous> (bundle.js:1405), <anonymous>:25:30)
    at Object.<anonymous> (bundle.js:1405)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:3379), <anonymous>:12:17)

I think that the problem is in the Webpack configuration. This is my webpack.config.js:

var path = require('path')
var webpack = require('webpack')
var NpmInstallPlugin = require('npm-install-webpack-plugin')
var autoprefixer = require('autoprefixer');
var precss = require('precss');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    'babel-polyfill',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new NpmInstallPlugin()
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loaders: ['eslint'],
        include: [
          path.resolve(__dirname, "src"),
        ],
      }
    ],
    loaders: [
      {
        loaders: ['react-hot', 'babel-loader'],
        include: [
          path.resolve(__dirname, "src"),
        ],
        test: /\.js$/,
        plugins: ['transform-runtime'],
        presets: ['es2015','react']
      },
      {
        test:   /\.css$/,
        loader: "style-loader!css-loader!postcss-loader"
      }
    ]
  },
  postcss: function () {
    return [autoprefixer, precss];
  }
}

Here is my package.json file:

{
  "name": "redux-ru-tutorial",
  "version": "1.0.0",
  "description": "Redux RU tutorial",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "Yuriy Shipovalov",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.3.1",
    "babel-core": "^6.4.5",
    "babel-eslint": "^4.1.6",
    "babel-loader": "^6.2.1",
    "babel-plugin-transform-runtime": "^6.4.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "css-loader": "^0.23.1",
    "eslint": "^1.10.3",
    "eslint-loader": "^1.2.1",
    "eslint-plugin-react": "^3.16.1",
    "express": "^4.13.4",
    "npm-install-webpack-plugin": "^2.0.2",
    "postcss-loader": "^0.8.0",
    "precss": "^1.4.0",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.12",
    "webpack-dev-middleware": "^1.5.1",
    "webpack-hot-middleware": "^2.6.4"
  },
  "dependencies": {
    "babel-polyfill": "^6.3.14",
    "babel-runtime": "^6.3.19",
    "cors": "^2.8.3",
    "history": "^4.6.1",
    "jquery": "^3.2.1",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-redux": "^4.0.6",
    "react-redux-router": "0.0.5",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "redux": "^3.3.1",
    "redux-logger": "2.5.2",
    "redux-thunk": "1.0.3"
  }
}

Here is my index.js file:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import App from './containers/App'
import './styles/app.css'
import configureStore from './store/configureStore'

const store = configureStore()
console.log(store.getState())
render(
  <Provider store={store}>
      <Router>
          <Route> path="/" component={App}></Route>
      </Router>
  </Provider>,
  document.getElementById('root')
)

Body:
You're attempting to set Babel's plugins and presets directly in the Webpack configuration as part of module.loaders. This is incorrect. You have to pass it as options to the loader. The error is because you're passing the options incorrectly so Babel does not receive the options, and thus does not transpile your code based on the presets and thus the error.

Depending on your Webpack version, try:

Webpack 1.x

Since you have multiple loaders, you cannot set it in the query object. Instead, you are going to have to set your loader options inline:

{
    test: /\.js$/,
    loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=react?plugins[]=transform-runtime']
}

This will directly pass the loader options to Babel through a query, but since you have two loaders Webpack didn't know which loader to query so you have to do it inline on one loader.


问:
how to print_r in codeigniter rest controller as we see output in postman
I want to print_r my array in codeigniter rest controller. As we are seeing output of rest controller in POSTMAN, not in browser. How to debug array?</p>

答:
Please use die tag.

```<code>print_r($data);
die;
</code>```

Let me know if it not works for you.

Body:
Please use die tag.

print_r($data);
die;

Let me know if it not works for you.


问:
Delete Task from ListView Using ActionBar Menu Button Android
I am working on a an application designed for students. In this application I have a list view that contains student task stored using SQLite. I have placed 2 menu buttons on the action bar one for going back and one deleting the task from list. When I click  the back button it works fine, but when I try to delete the task from list view it first asks whether the user wants to delete the task or not using AlertDialog.Builder then successfully toast the message but does not delete the task from list.

My code for the action bar menu button is given below. Please help me correct my code.I would really appreciate it.

Thank you in advance!

```<code>switch (item.getItemId()) {
            case R.id.action_back:
                Intent openMainActivity = new Intent(this, MainActivity.class);
                startActivity(openMainActivity);
                return true;

            case R.id.action_discard:
                AlertDialog.Builder builder = new AlertDialog.Builder(Second.this);
                builder
                        .setTitle(getString(R.string.delete_title))
                        .setMessage(getString(R.string.delete_message))
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                int id = getIntent().getExtras().getInt(getString(R.string.rodID));
                                db.delete(DbHelper.TABLE_NAME, DbHelper.ID + "=" + id, null);
                                Toast.makeText(Second.this,"Task deleted",Toast.LENGTH_SHORT).show();
                                db.close();
                                Intent openMainActivity = new Intent(Second.this, MainActivity.class);
                                startActivity(openMainActivity);
                            }
                        })
                        .setNegativeButton(getString(R.string.no), null)
                        .show();
                        return true;

            default:
                return super.onOptionsItemSelected(item);
        }
</code>```

答:
I think your Id doesn't match to the database Id. Print your row id and check if it is correct.

or

After deleting the data from database you need to query again and notify the adapter that data has been changed else close the app and reopen to see the effect.

Body:
I am working on a an application designed for students. In this application I have a list view that contains student task stored using SQLite. I have placed 2 menu buttons on the action bar one for going back and one deleting the task from list. When I click  the back button it works fine, but when I try to delete the task from list view it first asks whether the user wants to delete the task or not using AlertDialog.Builder then successfully toast the message but does not delete the task from list.

My code for the action bar menu button is given below. Please help me correct my code.I would really appreciate it.

Thank you in advance!

switch (item.getItemId()) {
            case R.id.action_back:
                Intent openMainActivity = new Intent(this, MainActivity.class);
                startActivity(openMainActivity);
                return true;

            case R.id.action_discard:
                AlertDialog.Builder builder = new AlertDialog.Builder(Second.this);
                builder
                        .setTitle(getString(R.string.delete_title))
                        .setMessage(getString(R.string.delete_message))
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                int id = getIntent().getExtras().getInt(getString(R.string.rodID));
                                db.delete(DbHelper.TABLE_NAME, DbHelper.ID + "=" + id, null);
                                Toast.makeText(Second.this,"Task deleted",Toast.LENGTH_SHORT).show();
                                db.close();
                                Intent openMainActivity = new Intent(Second.this, MainActivity.class);
                                startActivity(openMainActivity);
                            }
                        })
                        .setNegativeButton(getString(R.string.no), null)
                        .show();
                        return true;

            default:
                return super.onOptionsItemSelected(item);
        }


问:
Java Calendar TimeZone for US Stock Market
I am doing Android programming related to US NYSE & NASDAQ stock market. So far I know that they are using Eastern Time (ET). Stock market opens at 9.30AM ET, closes at 4pm ET.

In order to check stock market is currently open / close, I want to check whether current time is within 9.30am - 4pm.

Is the below code correct, to get user time in ET timezone?

```<code>Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
</code>```

As I read, Eastern Time (ET) observe Daylight saving. In summer it uses EDT which is UTC-4, whereas in winter it uses EST which is UTC-5. So NYSE & NASDAQ is using ET timezone?

I want to make sure my comparison of 9.30am - 4pm is using same timezone as NYSE & NASDAQ stock market.

答:
Instead of the outdated id "US/Eastern", I would choose "America/New_York" according to the tzdb maintained by IANA.

This timezone takes into account daylight saving during summer (but not winter) and can hence be applied throughout the whole year.

Wikipedia indicates that NYSE & NASDAQ stock market uses this timezone, too.

By the way, I would use new GregorianCalendar() instead of Calendar.getInstance() to make sure that you get the right calendar (relevant if you are in Thailand).

Evaluating the open-condition might look like this (half-open interval for local time "9:30/16:00"):

```<code>    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int minute = cal.get(Calendar.MINUTE);
    boolean open = (hour > 9 || (hour == 9 && minute >= 30)) && (hour < 16);
</code>```

Body:
I am doing Android programming related to US NYSE & NASDAQ stock market. So far I know that they are using Eastern Time (ET). Stock market opens at 9.30AM ET, closes at 4pm ET.

In order to check stock market is currently open / close, I want to check whether current time is within 9.30am - 4pm.

Is the below code correct, to get user time in ET timezone?

Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("US/Eastern"));

As I read, Eastern Time (ET) observe Daylight saving. In summer it uses EDT which is UTC-4, whereas in winter it uses EST which is UTC-5. So NYSE & NASDAQ is using ET timezone?

I want to make sure my comparison of 9.30am - 4pm is using same timezone as NYSE & NASDAQ stock market.

Body:
Instead of the outdated id "US/Eastern", I would choose "America/New_York" according to the tzdb maintained by IANA.

This timezone takes into account daylight saving during summer (but not winter) and can hence be applied throughout the whole year.

Wikipedia indicates that NYSE & NASDAQ stock market uses this timezone, too.

By the way, I would use new GregorianCalendar() instead of Calendar.getInstance() to make sure that you get the right calendar (relevant if you are in Thailand).

Evaluating the open-condition might look like this (half-open interval for local time "9:30/16:00"):

    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int minute = cal.get(Calendar.MINUTE);
    boolean open = (hour > 9 || (hour == 9 && minute >= 30)) && (hour < 16);


问:
How to consume Web API without server side code, using only Ajax
I Added the following two host entries to my host file:

127.0.0.1 na_api.com

127.0.0.1 na_upload.com

The 127.0.0.1 na_api.com is used to retrieve some data from a database and return JSON, while the 127.0.0.1 na_upload.com is a website that consumes the API.

Currently, I have the following Ajax call, to call the API and get some data. Here is the Ajax call:

```<code>this.ajaxRetrieve = function (url, data, onSuccessCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        crossDomain: true,
        onsuccess: function (result) {
            onSuccessCallback(result);
        }
    });
}
</code>```

The above outputs the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

How can I work around this, without the needs of a back-end server side code like .Net or something?

答:
I finally found something that worked for me, in this article.

I added the following to the Web.config file of my Web API, in the <syetm.webServer> section

```<code><httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
</code>```

Here is the Ajax call I use to make the request:

```<code>$.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });
</code>```

Body:
I Added the following two host entries to my host file:

127.0.0.1 na_api.com

127.0.0.1 na_upload.com

The 127.0.0.1 na_api.com is used to retrieve some data from a database and return JSON, while the 127.0.0.1 na_upload.com is a website that consumes the API.

Currently, I have the following Ajax call, to call the API and get some data. Here is the Ajax call:

this.ajaxRetrieve = function (url, data, onSuccessCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        crossDomain: true,
        onsuccess: function (result) {
            onSuccessCallback(result);
        }
    });
}

The above outputs the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

How can I work around this, without the needs of a back-end server side code like .Net or something?

Body:
I finally found something that worked for me, in this article.

I added the following to the Web.config file of my Web API, in the <syetm.webServer> section

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

Here is the Ajax call I use to make the request:

$.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答:
Some databases allow multiple values to be stored in a single column of a single row, but it is generally more convenient to use a separate table.

Create a table with two columns, one that contains pointers to the primary key of the objects table, and one that contains pointers to the primary key of the fruit table.  Then, if an object has three fruit, there are three rows in the object_fruit table that all all point to the same object, but to three different fruit.

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

OwnerDisplayName: Glomek


问:
What are some good example open source Ruby projects that use Cucumber and RSpec well?
What are some good example open source Ruby projects that use Cucumber and RSpec well?

Update: While the suggestions below where quite impressive, I wanted to see how others are using RSpec and Cucumber to drive product development.

答:
From Quora:

Teng Siong Ong, Ruby, Python, etc.

https://github.com/teambox/teambox


问:
Don't update all textfields to firebase
I have three textFields and when the user enters information into them, the information is sent to Firebase.

```<code>     func buttonMethod() {
if let uid = FIRAuth.auth()?.currentUser?.uid{
            if let City = City.text{
                if let Major = Major.text{
                    if let College = College.text{

                        let saveObject: Dictionary<String, Any> = [
                            "uid": uid,
                            "City" : City,
                            "Major" : Major,
                            "College" : College
                        ]
                   }
               }
          }
      }

FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid).setValue(saveObject)
</code>```

Using those same textFields, the user can edit their information. And the information will be displayed in labels in another view controller.

```<code>  func loadInfo(){
        if (FIRAuth.auth()?.currentUser) != nil{

            FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid).observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

                if let postsDictionary = snapshot .value as? [String: AnyObject] {
                    for post in postsDictionary {
                        //self.posts.add(post.value)

                        let city = postsDictionary["City"] as! String
                        let major = postsDictionary["Major"] as! String
                        let college = postsDictionary["College"] as! String
                        self.City.text = city
                        self.Major.text = major
                        self.College.text = college
                    }

                }})}
    }
</code>```

My problem is that when the user edits the information, if a textField was not edited it replaces the value of the non-edited textField in Firebase with an empty string. I want it to be that if the user does not edit a textField then the value in Firebase should stay the same.I started out with this:

```<code> if City.tex t== "" {

 }
 if Major.text=="" {

 }
 if College.text==""{

 }
</code>```

But I'm not sure where to go from there.

答:
If the textfield text is empty then don't send that field to firebase. Say if user haven't edited city field then don't add city textField in the method to send value to firebase.

Please try update your buttonMethod() like this,

```<code>func buttonMethod() {
    if let uid = FIRAuth.auth()?.currentUser?.uid{

        var tempObject = [String:Any]()
        tempObject["uid"] = uid
        if !City.text.isEmpty {
            tempObject["City"] = City.text
        }

        if !Major.text.isEmpty{
            tempObject["Major"] = Major.text
        }

        if !College.text.isEmpty{
            tempObject["College"] = College.text
        }

        let saveObject:Dictionary<String,Any> = tempObject

}
</code>```

Instead of saving the object to firebase update the data at firebase using updateChildValues() function

Title: Don't update all textfields to firebase

Body:
I have three textFields and when the user enters information into them, the information is sent to Firebase.

     func buttonMethod() {
if let uid = FIRAuth.auth()?.currentUser?.uid{
            if let City = City.text{
                if let Major = Major.text{
                    if let College = College.text{

                        let saveObject: Dictionary<String, Any> = [
                            "uid": uid,
                            "City" : City,
                            "Major" : Major,
                            "College" : College
                        ]
                   }
               }
          }
      }

FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid).setValue(saveObject)

Using those same textFields, the user can edit their information. And the information will be displayed in labels in another view controller.

  func loadInfo(){
        if (FIRAuth.auth()?.currentUser) != nil{

            FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid).observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

                if let postsDictionary = snapshot .value as? [String: AnyObject] {
                    for post in postsDictionary {
                        //self.posts.add(post.value)

                        let city = postsDictionary["City"] as! String
                        let major = postsDictionary["Major"] as! String
                        let college = postsDictionary["College"] as! String
                        self.City.text = city
                        self.Major.text = major
                        self.College.text = college
                    }

                }})}
    }

My problem is that when the user edits the information, if a textField was not edited it replaces the value of the non-edited textField in Firebase with an empty string. I want it to be that if the user does not edit a textField then the value in Firebase should stay the same.I started out with this:

 if City.tex t== "" {

 }
 if Major.text=="" {

 }
 if College.text==""{

 }

But I'm not sure where to go from there.

Body:
If the textfield text is empty then don't send that field to firebase. Say if user haven't edited city field then don't add city textField in the method to send value to firebase.

Please try update your buttonMethod() like this,

func buttonMethod() {
    if let uid = FIRAuth.auth()?.currentUser?.uid{

        var tempObject = [String:Any]()
        tempObject["uid"] = uid
        if !City.text.isEmpty {
            tempObject["City"] = City.text
        }

        if !Major.text.isEmpty{
            tempObject["Major"] = Major.text
        }

        if !College.text.isEmpty{
            tempObject["College"] = College.text
        }

        let saveObject:Dictionary<String,Any> = tempObject

}

Instead of saving the object to firebase update the data at firebase using updateChildValues() function


问:
why onclick is not working with innerHtml
Here I am trying to add html to an element using innerHtml

```<code>  <body>
 <h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
    <button id="addChapter">Add Chapter</button>
    <div id="courseStructure">

    </div>
 </div>
 </div>
<script src="index.js"></script>
</body>
</code>```

JS:

```<code>var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
 }
</code>```

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

答:
You have not written innerHTML in proper format. its innerHTML instead of innerHtml
your code should be..

```<code><body>
<h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
<button id="addChapter">Add Chapter</button>
<div id="courseStructure">

</div>
</div>
</div>
<script src="index.js"></script>
</body>
</code>```

Your .JS file will be.

```<code>var addChapter = document.getElementById("addChapter");

addChapter.onclick = function()
{
document.getElementById("courseStructure").innerHTML += '<div><input type="text" name="chaptername" placeholder="chapter name"/>
<button id="addSubChapter">Add SubChapter</button>
<button id="addContent">Add Content</button>
<br><br></div>';
}
</code>```

Body:
Here I am trying to add html to an element using innerHtml

Dynamically Retrieve the chapter name

    <button id="addChapter">Add Chapter</button>

JS:

var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '
<input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button>

';
 }

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

Body:
You have not written innerHTML in proper format. its innerHTML instead of innerHtml
your code should be..

<body>
<h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
<button id="addChapter">Add Chapter</button>
<div id="courseStructure">

</div>
</div>
</div>
<script src="index.js"></script>
</body>

Your .JS file will be.

var addChapter = document.getElementById("addChapter");

addChapter.onclick = function()
{
document.getElementById("courseStructure").innerHTML += '<div><input type="text" name="chaptername" placeholder="chapter name"/>
<button id="addSubChapter">Add SubChapter</button>
<button id="addContent">Add Content</button>
<br><br></div>';
}


问:
Convert an Integer to a String and Trim in 1 Step
I'm wondering if it's possible to convert an integer to a string and trim it within one step.

I have the following object:

currentForm

```<code>{
id:1,
name:"Abusicus",
value:12203,
period:"Morning",
favoriteSnack:"      "
....
}
</code>```

I need to find a way to check if the values are empty ("") or have something in it.

Eg. favoriteSnack would be considered empty since it's just white space. Currently I use this to check for white space:

```<code>var validInput = currentForm.every( v => currentForm[v] && currentForm[v].trim().length);
</code>```

But this does not work on fields with values that are integers. I want to do something like this: (Convert the integers to strings and then do a check on all the values)

```<code>var validInput = currentForm.every( v => currentForm[v] && currentForm[v].toString().trim().length);
</code>```

Is something like this possible?

答:
For int, value will be 0, and even you convert, it will be "0", not " "
Regardless, there is a dirty way to do this by adding "" in front of an int.
You can do sonething like this:
"" + value;</p>

Body:
I'm wondering if it's possible to convert an integer to a string and trim it within one step.

I have the following object:

currentForm

{
id:1,
name:"Abusicus",
value:12203,
period:"Morning",
favoriteSnack:"      "
....
}

I need to find a way to check if the values are empty ("") or have something in it.

Eg. favoriteSnack would be considered empty since it's just white space. Currently I use this to check for white space:

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].trim().length);

But this does not work on fields with values that are integers. I want to do something like this: (Convert the integers to strings and then do a check on all the values)

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].toString().trim().length);

Is something like this possible?


问:
Adding metadata (x-amz-meta-SOMEINFO) while uploading to S3
I am looking for a way to programmatically insert custom metadata (x-amz-meta-SOMEINFO) while uploading a file into AWS S3.

Currently I am inserting the file using a Python lambda function into S3 bucket using the below command.

open('/tmp/newFile.docx',
  'wb').write(attachment.get_payload(decode=True))
  s3r.meta.client.upload_file('/tmp/newFile.docx', outputBucket,
  attachment.get_filename())

答:
I was able to solve the above issue using 'ExtraArgs'

```<code>s3r.meta.client.upload_file('/tmp/newFile.docx', outputBucket, str(time.time())+'-'+attachment.get_filename(),
    ExtraArgs={"Metadata": {"SOMEINFO": value}})
</code>```

The metadata 'SOMEINFO' gets saved as x-amz-meta-SOMEINFO'.

Body:
I was able to solve the above issue using 'ExtraArgs'

s3r.meta.client.upload_file('/tmp/newFile.docx', outputBucket, str(time.time())+'-'+attachment.get_filename(),
    ExtraArgs={"Metadata": {"SOMEINFO": value}})

The metadata 'SOMEINFO' gets saved as x-amz-meta-SOMEINFO'.


问:
How to get at the database schema of a hidden DB?
My customer is a dental practice that has bought a piece of practice management software.  This software was installed on their local server, including a patient database, a schedule and all manner of medical records.  Now they want me to write some utilities for them that aren't provided with their package, and for this I need the ability to query this database.

I tried calling tech support of the software manufacturers (Patterson/EagleSoft), and it's difficult finding anyone who understands the technology enough to answer my questions.  As far as I can tell, there's no API for their software, and understandably they're reluctant to tell me how to query the DB directly, programmatically.  They do have an interactive query window, but obviously that's no good for writing automated queries.  All that they would let on is that somewhere there's a SQL Server DB, but the ODBC drivers to connect to it are SQL Anywhere drivers (huh?).

So I searched around on the server and couldn't find any database files.  Then I discovered that the installation creates some kind of proprietary virtual machine, which is only visible to the EagleSoft software.  But while they've been very good at insulating their DB in layers of obfuscation, they have left open an ODBC driver, which is indeed an SQL Anywhere connection.

Now after that fascinating and lengthy preamble, here is my question: What queries can I run over this ODBC connection to interrogate the DB as to its structure?  If it's a SQL Server DB underneath I could use the sysobjects table, but I don't fully grasp how you can use a SQL Anywhere ODBC connection to connect to a MSSQL DB.  And If they were misinforming me and it really is a SQL Anywhere DB underneath, what are the queries to run to get at the DB structure?

And if there's anyone else out there who's ever succeeded in actually querying EagleSoft (or any similar proprietary package) - please tell me how you did it!

答: Turns out the simplest way to do it was to write a little app using OdbcDbConnection, and connect using the DSN installed with the software.  It took one probing 'select * from sysobjects' to reveal that it is, indeed a MS-SQL database underneath all that, and I'm good to go from there!


问:
Open a PopupWindow and let the outsides still touchable
How to open a PopupWindow on Android and let all the others components touchable without dismiss the PopupWindow?

This is how it's created:

```<code>public class DynamicPopup {
    private final PopupWindow window;
    private final RectF rect;
    private final View parent;
    private final RichPageView view;

    public DynamicPopup(Context context, RichPage page, RectF rectF, View parent) {
        this.parent = parent;
        rect = rectF;

        window = new PopupWindow(context);

        window.setBackgroundDrawable(new BitmapDrawable());
        window.setWidth((int) rect.width());
        window.setHeight((int) rect.height());
        window.setTouchable(true);
        window.setFocusable(true);
        window.setOutsideTouchable(true);

        view = new RichPageView(context, page, false);
        window.setContentView(view);

        view.setOnCloseListener(new Listener(){
            @Override
            public void onAction() {
                window.dismiss();
            }
        });

    }

    public void show() {
        window.showAtLocation(parent, Gravity.NO_GRAVITY, (int) rect.left, (int) rect.top);
    }
}
</code>```

答:
Try adding this to your code:

```<code>window.setOutsideTouchable(true);
</code>```

From the Android documentation:

```<code>void setOutsideTouchable (boolean touchable)
</code>```

Controls whether the pop-up will be informed of touch events outside of its window. This only makes sense for pop-ups that are touchable but not focusable, which means touches outside of the window will be delivered to the window behind. The default is false.

If the popup is showing, calling this method will take effect only the next time the popup is shown or through a manual call to one of the update() methods.

Body:
How to open a PopupWindow on Android and let all the others components touchable without dismiss the PopupWindow?

This is how it's created:

public class DynamicPopup {
    private final PopupWindow window;
    private final RectF rect;
    private final View parent;
    private final RichPageView view;

    public DynamicPopup(Context context, RichPage page, RectF rectF, View parent) {
        this.parent = parent;
        rect = rectF;

        window = new PopupWindow(context);

        window.setBackgroundDrawable(new BitmapDrawable());
        window.setWidth((int) rect.width());
        window.setHeight((int) rect.height());
        window.setTouchable(true);
        window.setFocusable(true);
        window.setOutsideTouchable(true);

        view = new RichPageView(context, page, false);
        window.setContentView(view);

        view.setOnCloseListener(new Listener(){
            @Override
            public void onAction() {
                window.dismiss();
            }
        });

    }

    public void show() {
        window.showAtLocation(parent, Gravity.NO_GRAVITY, (int) rect.left, (int) rect.top);
    }
}

Body:
Try adding this to your code:

window.setOutsideTouchable(true);

From the Android documentation:

void setOutsideTouchable (boolean touchable)

Controls whether the pop-up will be informed of touch events outside of its window. This only makes sense for pop-ups that are touchable but not focusable, which means touches outside of the window will be delivered to the window behind. The default is false.

If the popup is showing, calling this method will take effect only the next time the popup is shown or through a manual call to one of the update() methods.


问:
How to stop intentservice in android?
Could anyone tell me how to stop intentservice in Android?

If I use stopservice to stop an intentservice, it doesn't work.

I have browsed the website, but nobody has given a clear answer to this question.

答: An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.As per docs,IntentService class "Stops the service after all of the start requests are handled, so you never have to call stopSelf()"

Title: How to stop intentservice in android?