问:
Button click load data from url fragment
This is a project am trying to modify. The project is made in fragment. its an online market for buying and selling. the code below helps data to be fetched from server automatically when the App is lunched / opened. but i dont want it to load data Automatically but onlu load when a user press a button it will fetch the content from the server.  the METHOD_STREAM_GET below is for

public static final String METHOD_STREAM_GET = API_DOMAIN + "api/" + API_VERSION + "/method/stream.get" + API_FILE_EXTENSION;.

package ml.shopnet.market;

public class StreamFragment extends Fragment implements Constants, SwipeRefreshLayout.OnRefreshListener
{

```<code>private static final String STATE_LIST = "State Adapter Data";
private static final String STATE_LIST_2 = "State Adapter Data";

private static final int PROFILE_NEW_POST = 4;

RecyclerView mRecyclerView;
TextView mMessage;

SwipeRefreshLayout mItemsContainer;

FloatingActionButton mFabButton;

Button login;
GridView gridView;

private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;

private Parcelable mListState;

private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;

int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;

public StreamFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {

        itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST_2);
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = savedInstanceState.getBoolean("restore");
        itemId = savedInstanceState.getInt("itemId");

        viewMore = savedInstanceState.getBoolean("viewMore");

    } else {

        itemsList = new ArrayList<>();
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = false;
        itemId = 0;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
    mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

    mMessage = (TextView) rootView.findViewById(R.id.message);

    mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
    mFabButton.setImageResource(R.drawable.ic_action_new);

    if (App.getInstance().getId() == 0) {

        mFabButton.setVisibility(View.GONE);
    }

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);

    final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mRecyclerView.setAdapter(itemsAdapter);

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(dy > 0) //check for scroll down
            {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                if (!loadingMore)
                {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
                    {
                        loadingMore = true;
                        Log.e("...", "Last Item Wow !");

                        getItems();
                    }
                }
            }
        }
    });

    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Item i = (Item) itemsList.get(position);

            Intent intent = new Intent(getActivity(), ViewItemActivity.class);
            intent.putExtra("itemId", i.getId());
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(View view, int position) {
            // ...
        }
    }));

    mFabButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getActivity(), NewItemActivity.class);
            startActivityForResult(intent, STREAM_NEW_POST);
        }
    });

    if (itemsAdapter.getItemCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (!restore) {

        showMessage(getText(R.string.msg_loading_2).toString());

        getItems();
    }

    return rootView;
}

static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    public interface OnItemClickListener {

        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;

    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {

        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {

                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childView != null && mListener != null) {

                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {

        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {

            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {

        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {

            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge

                outRect.top = spacing;
            }

            outRect.bottom = spacing; // item bottom

        } else {

            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)

            if (position >= spanCount) {

                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {

    Resources r = getResources();

    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putBoolean("viewMore", viewMore);

    outState.putBoolean("restore", true);
    outState.putInt("itemId", itemId);

    mListState = mRecyclerView.getLayoutManager().onSaveInstanceState();
    outState.putParcelable(STATE_LIST, mListState);

    outState.putParcelableArrayList(STATE_LIST_2, itemsList);
}

@Override
public void onRefresh() {

    if (App.getInstance().isConnected()) {

        itemId = 0;
        getItems();

    } else {

        mItemsContainer.setRefreshing(false);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == STREAM_NEW_POST && resultCode == getActivity().RESULT_OK && null != data) {

        itemId = 0;
        getItems();

    } else if (requestCode == ITEM_EDIT && resultCode == getActivity().RESULT_OK) {

        int position = data.getIntExtra("position", 0);

        Item item = itemsList.get(position);

        item.setContent(data.getStringExtra("post"));
        item.setImgUrl(data.getStringExtra("imgUrl"));

        itemsAdapter.notifyDataSetChanged();
    }
}

public void showToast(String msg) {
    Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View row=inflater.inflate(R.layout.cell_categories, parent, false);

        ImageView myimage= (ImageView) row.findViewById(R.id.img);

        TextView mytitle= (TextView) row.findViewById(R.id.category);

        myimage.setImageResource(image[position]);

        mytitle.setText(title[position]);

        return row;
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);
}

public void getItems() {

    mItemsContainer.setRefreshing(true);

    CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_STREAM_GET, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    if (!isAdded() || getActivity() == null) {

                        Log.e("ERROR", "StreamFragment Not Added to Activity");

                        return;
                    }

                    if (!loadingMore) {

                        itemsList.clear();
                    }

                    try {

                        arrayLength = 0;

                        if (!response.getBoolean("error")) {

                            itemId = response.getInt("itemId");

                            if (response.has("items")) {

                                JSONArray itemsArray = response.getJSONArray("items");

                                arrayLength = itemsArray.length();

                                if (arrayLength > 0) {

                                    for (int i = 0; i < itemsArray.length(); i++) {

                                        JSONObject itemObj = (JSONObject) itemsArray.get(i);

                                        Item item = new Item(itemObj);

                                        itemsList.add(item);
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {

                        e.printStackTrace();

                    } finally {

                        loadingComplete();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            if (!isAdded() || getActivity() == null) {

                Log.e("ERROR", "StreamFragment Not Added to Activity");

                return;
            }

            loadingComplete();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountId", Long.toString(App.getInstance().getId()));
            params.put("accessToken", App.getInstance().getAccessToken());
            params.put("itemId", Integer.toString(itemId));
            params.put("language", "en");

            return params;
        }
    };

    App.getInstance().addToRequestQueue(jsonReq);
}

public void loadingComplete() {

    if (arrayLength == LIST_ITEMS) {

        viewMore = true;

    } else {

        viewMore = false;
    }

    itemsAdapter.notifyDataSetChanged();

    if (itemsAdapter.getItemCount() == 0) {

        if (StreamFragment.this.isVisible()) {

            showMessage(getText(R.string.label_empty_list).toString());
        }

    } else {
        hideMessage();
    }
    loadingMore = false;
    mItemsContainer.setRefreshing(false);
}
public void showMessage(String message) {

    mMessage.setText(message);
    mMessage.setVisibility(View.VISIBLE);
}

public void hideMessage() {

    mMessage.setVisibility(View.GONE);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}
</code>```

}

Hi I also have another problem. Thanks for solving the first one the below code receives data from categories.java but i want to modify it to only open one category with one category ID like id 5 than receiving category id from categories i want to make it retrieve information from id "5"

package ml.shopnet.market;

public class CategoryFragment extends Fragment implements Constants, SwipeRefreshLayout.OnRefreshListener {

```<code>private static final String STATE_LIST = "State Adapter Data";

RecyclerView mRecyclerView;
TextView mMessage;

SwipeRefreshLayout mItemsContainer;

private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;

private int categoryId = 0;

private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;

private String title = "";

int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;

public CategoryFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {

        itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST);
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = savedInstanceState.getBoolean("restore");
        itemId = savedInstanceState.getInt("itemId");
        categoryId = savedInstanceState.getInt("categoryId");
        title = savedInstanceState.getString("title");

        viewMore = savedInstanceState.getBoolean("viewMore");

    } else {

        itemsList = new ArrayList<Item>();
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = false;
        itemId = 0;
        categoryId = 0;

        Intent i = getActivity().getIntent();

        title = i.getStringExtra("title");
        categoryId = i.getIntExtra("categoryId", 0);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_category, container, false);

    mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

    mMessage = (TextView) rootView.findViewById(R.id.message);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);

    final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mRecyclerView.setAdapter(itemsAdapter);

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(dy > 0) //check for scroll down
            {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                if (!loadingMore)
                {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
                    {
                        loadingMore = true;
                        Log.e("...", "Last Item Wow !");

                        getItems();
                    }
                }
            }
        }
    });

    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Item i = (Item) itemsList.get(position);

            Intent intent = new Intent(getActivity(), ViewItemActivity.class);
            intent.putExtra("itemId", i.getId());
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(View view, int position) {
            // ...
        }
    }));

    if (itemsAdapter.getItemCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (title != null) {

        getActivity().setTitle(title);
    }

    if (!restore) {

        showMessage(getText(R.string.msg_loading_2).toString());

        getItems();
    }

    return rootView;
}

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putBoolean("viewMore", viewMore);
    outState.putBoolean("restore", true);
    outState.putInt("itemId", itemId);
    outState.putInt("categoryId", categoryId);
    outState.putString("title", title);
    outState.putParcelableArrayList(STATE_LIST, itemsList);
}

@Override
public void onRefresh() {

    if (App.getInstance().isConnected()) {

        itemId = 0;
        getItems();

    } else {

        mItemsContainer.setRefreshing(false);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
}

public void getItems() {

    mItemsContainer.setRefreshing(true);

    CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_CATEGORY_GET, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    if (!isAdded() || getActivity() == null) {

                        Log.e("ERROR", "CategoryFragment Not Added to Activity");

                        return;
                    }

                    if (!loadingMore) {

                        itemsList.clear();
                    }

                    try {

                        arrayLength = 0;

                        if (!response.getBoolean("error")) {

                            itemId = response.getInt("itemId");
                            categoryId = response.getInt("categoryId");

                            if (response.has("items")) {

                                JSONArray itemsArray = response.getJSONArray("items");

                                arrayLength = itemsArray.length();

                                if (arrayLength > 0) {

                                    for (int i = 0; i < itemsArray.length(); i++) {

                                        JSONObject itemObj = (JSONObject) itemsArray.get(i);

                                        Item item = new Item(itemObj);

                                        itemsList.add(item);
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {

                        e.printStackTrace();

                    } finally {

                        loadingComplete();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            if (!isAdded() || getActivity() == null) {

                Log.e("ERROR", "CategoryFragment Not Added to Activity");

                return;
            }

            loadingComplete();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountId", Long.toString(App.getInstance().getId()));
            params.put("accessToken", App.getInstance().getAccessToken());
            params.put("itemId", Long.toString(itemId));
            params.put("categoryId", Integer.toString(categoryId));
            params.put("language", "en");

            return params;
        }
    };

    App.getInstance().addToRequestQueue(jsonReq);
}

public void loadingComplete() {

    if (arrayLength == LIST_ITEMS) {

        viewMore = true;

    } else {

        viewMore = false;
    }

    itemsAdapter.notifyDataSetChanged();

    if (mRecyclerView.getAdapter().getItemCount() == 0) {

        if (isAdded()) {

            showMessage(getText(R.string.label_empty_list).toString());
        }

    } else {

        hideMessage();
    }

    loadingMore = false;
    mItemsContainer.setRefreshing(false);
}

static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    public interface OnItemClickListener {

        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;

    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {

        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {

                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childView != null && mListener != null) {

                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {

        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {

            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {

        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {

            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge

                outRect.top = spacing;
            }

            outRect.bottom = spacing; // item bottom

        } else {

            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)

            if (position >= spanCount) {

                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {

    Resources r = getResources();

    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

public void showMessage(String message) {

    mMessage.setText(message);
    mMessage.setVisibility(View.VISIBLE);
}

public void hideMessage() {

    mMessage.setVisibility(View.GONE);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}
</code>```

}

答:
remove getItems() from

```<code>if (!restore) {

    showMessage(getText(R.string.msg_loading_2).toString());

    getItems();
}
</code>```

set click listener to your button then call getItems() method

```<code>    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMessage(getText(R.string.msg_loading_2).toString());
            getItems();
        }
    });
</code>```

Body:
This is a project am trying to modify. The project is made in fragment. its an online market for buying and selling. the code below helps data to be fetched from server automatically when the App is lunched / opened. but i dont want it to load data Automatically but onlu load when a user press a button it will fetch the content from the server.  the METHOD_STREAM_GET below is for

public static final String METHOD_STREAM_GET = API_DOMAIN + "api/" + API_VERSION + "/method/stream.get" + API_FILE_EXTENSION;.

package ml.shopnet.market;

public class StreamFragment extends Fragment implements Constants, SwipeRefreshLayout.OnRefreshListener
{

private static final String STATE_LIST = "State Adapter Data";
private static final String STATE_LIST_2 = "State Adapter Data";

private static final int PROFILE_NEW_POST = 4;

RecyclerView mRecyclerView;
TextView mMessage;

SwipeRefreshLayout mItemsContainer;

FloatingActionButton mFabButton;

Button login;
GridView gridView;

private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;

private Parcelable mListState;

private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;

int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;

public StreamFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {

        itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST_2);
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = savedInstanceState.getBoolean("restore");
        itemId = savedInstanceState.getInt("itemId");

        viewMore = savedInstanceState.getBoolean("viewMore");

    } else {

        itemsList = new ArrayList<>();
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = false;
        itemId = 0;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
    mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

    mMessage = (TextView) rootView.findViewById(R.id.message);

    mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
    mFabButton.setImageResource(R.drawable.ic_action_new);

    if (App.getInstance().getId() == 0) {

        mFabButton.setVisibility(View.GONE);
    }

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);

    final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mRecyclerView.setAdapter(itemsAdapter);

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(dy > 0) //check for scroll down
            {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                if (!loadingMore)
                {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
                    {
                        loadingMore = true;
                        Log.e("...", "Last Item Wow !");

                        getItems();
                    }
                }
            }
        }
    });

    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Item i = (Item) itemsList.get(position);

            Intent intent = new Intent(getActivity(), ViewItemActivity.class);
            intent.putExtra("itemId", i.getId());
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(View view, int position) {
            // ...
        }
    }));

    mFabButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getActivity(), NewItemActivity.class);
            startActivityForResult(intent, STREAM_NEW_POST);
        }
    });

    if (itemsAdapter.getItemCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (!restore) {

        showMessage(getText(R.string.msg_loading_2).toString());

        getItems();
    }

    return rootView;
}

static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    public interface OnItemClickListener {

        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;

    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {

        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {

                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childView != null && mListener != null) {

                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {

        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {

            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {

        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {

            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge

                outRect.top = spacing;
            }

            outRect.bottom = spacing; // item bottom

        } else {

            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)

            if (position >= spanCount) {

                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {

    Resources r = getResources();

    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putBoolean("viewMore", viewMore);

    outState.putBoolean("restore", true);
    outState.putInt("itemId", itemId);

    mListState = mRecyclerView.getLayoutManager().onSaveInstanceState();
    outState.putParcelable(STATE_LIST, mListState);

    outState.putParcelableArrayList(STATE_LIST_2, itemsList);
}

@Override
public void onRefresh() {

    if (App.getInstance().isConnected()) {

        itemId = 0;
        getItems();

    } else {

        mItemsContainer.setRefreshing(false);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == STREAM_NEW_POST && resultCode == getActivity().RESULT_OK && null != data) {

        itemId = 0;
        getItems();

    } else if (requestCode == ITEM_EDIT && resultCode == getActivity().RESULT_OK) {

        int position = data.getIntExtra("position", 0);

        Item item = itemsList.get(position);

        item.setContent(data.getStringExtra("post"));
        item.setImgUrl(data.getStringExtra("imgUrl"));

        itemsAdapter.notifyDataSetChanged();
    }
}

public void showToast(String msg) {
    Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View row=inflater.inflate(R.layout.cell_categories, parent, false);

        ImageView myimage= (ImageView) row.findViewById(R.id.img);

        TextView mytitle= (TextView) row.findViewById(R.id.category);

        myimage.setImageResource(image[position]);

        mytitle.setText(title[position]);

        return row;
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);
}

public void getItems() {

    mItemsContainer.setRefreshing(true);

    CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_STREAM_GET, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    if (!isAdded() || getActivity() == null) {

                        Log.e("ERROR", "StreamFragment Not Added to Activity");

                        return;
                    }

                    if (!loadingMore) {

                        itemsList.clear();
                    }

                    try {

                        arrayLength = 0;

                        if (!response.getBoolean("error")) {

                            itemId = response.getInt("itemId");

                            if (response.has("items")) {

                                JSONArray itemsArray = response.getJSONArray("items");

                                arrayLength = itemsArray.length();

                                if (arrayLength > 0) {

                                    for (int i = 0; i < itemsArray.length(); i++) {

                                        JSONObject itemObj = (JSONObject) itemsArray.get(i);

                                        Item item = new Item(itemObj);

                                        itemsList.add(item);
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {

                        e.printStackTrace();

                    } finally {

                        loadingComplete();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            if (!isAdded() || getActivity() == null) {

                Log.e("ERROR", "StreamFragment Not Added to Activity");

                return;
            }

            loadingComplete();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountId", Long.toString(App.getInstance().getId()));
            params.put("accessToken", App.getInstance().getAccessToken());
            params.put("itemId", Integer.toString(itemId));
            params.put("language", "en");

            return params;
        }
    };

    App.getInstance().addToRequestQueue(jsonReq);
}

public void loadingComplete() {

    if (arrayLength == LIST_ITEMS) {

        viewMore = true;

    } else {

        viewMore = false;
    }

    itemsAdapter.notifyDataSetChanged();

    if (itemsAdapter.getItemCount() == 0) {

        if (StreamFragment.this.isVisible()) {

            showMessage(getText(R.string.label_empty_list).toString());
        }

    } else {
        hideMessage();
    }
    loadingMore = false;
    mItemsContainer.setRefreshing(false);
}
public void showMessage(String message) {

    mMessage.setText(message);
    mMessage.setVisibility(View.VISIBLE);
}

public void hideMessage() {

    mMessage.setVisibility(View.GONE);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}

}

Hi I also have another problem. Thanks for solving the first one the below code receives data from categories.java but i want to modify it to only open one category with one category ID like id 5 than receiving category id from categories i want to make it retrieve information from id "5"

package ml.shopnet.market;

public class CategoryFragment extends Fragment implements Constants, SwipeRefreshLayout.OnRefreshListener {

private static final String STATE_LIST = "State Adapter Data";

RecyclerView mRecyclerView;
TextView mMessage;

SwipeRefreshLayout mItemsContainer;

private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;

private int categoryId = 0;

private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;

private String title = "";

int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;

public CategoryFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {

        itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST);
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = savedInstanceState.getBoolean("restore");
        itemId = savedInstanceState.getInt("itemId");
        categoryId = savedInstanceState.getInt("categoryId");
        title = savedInstanceState.getString("title");

        viewMore = savedInstanceState.getBoolean("viewMore");

    } else {

        itemsList = new ArrayList<Item>();
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList);

        restore = false;
        itemId = 0;
        categoryId = 0;

        Intent i = getActivity().getIntent();

        title = i.getStringExtra("title");
        categoryId = i.getIntExtra("categoryId", 0);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_category, container, false);

    mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

    mMessage = (TextView) rootView.findViewById(R.id.message);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);

    final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mRecyclerView.setAdapter(itemsAdapter);

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(dy > 0) //check for scroll down
            {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                if (!loadingMore)
                {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
                    {
                        loadingMore = true;
                        Log.e("...", "Last Item Wow !");

                        getItems();
                    }
                }
            }
        }
    });

    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Item i = (Item) itemsList.get(position);

            Intent intent = new Intent(getActivity(), ViewItemActivity.class);
            intent.putExtra("itemId", i.getId());
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(View view, int position) {
            // ...
        }
    }));

    if (itemsAdapter.getItemCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (title != null) {

        getActivity().setTitle(title);
    }

    if (!restore) {

        showMessage(getText(R.string.msg_loading_2).toString());

        getItems();
    }

    return rootView;
}

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putBoolean("viewMore", viewMore);
    outState.putBoolean("restore", true);
    outState.putInt("itemId", itemId);
    outState.putInt("categoryId", categoryId);
    outState.putString("title", title);
    outState.putParcelableArrayList(STATE_LIST, itemsList);
}

@Override
public void onRefresh() {

    if (App.getInstance().isConnected()) {

        itemId = 0;
        getItems();

    } else {

        mItemsContainer.setRefreshing(false);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
}

public void getItems() {

    mItemsContainer.setRefreshing(true);

    CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_CATEGORY_GET, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    if (!isAdded() || getActivity() == null) {

                        Log.e("ERROR", "CategoryFragment Not Added to Activity");

                        return;
                    }

                    if (!loadingMore) {

                        itemsList.clear();
                    }

                    try {

                        arrayLength = 0;

                        if (!response.getBoolean("error")) {

                            itemId = response.getInt("itemId");
                            categoryId = response.getInt("categoryId");

                            if (response.has("items")) {

                                JSONArray itemsArray = response.getJSONArray("items");

                                arrayLength = itemsArray.length();

                                if (arrayLength > 0) {

                                    for (int i = 0; i < itemsArray.length(); i++) {

                                        JSONObject itemObj = (JSONObject) itemsArray.get(i);

                                        Item item = new Item(itemObj);

                                        itemsList.add(item);
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {

                        e.printStackTrace();

                    } finally {

                        loadingComplete();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            if (!isAdded() || getActivity() == null) {

                Log.e("ERROR", "CategoryFragment Not Added to Activity");

                return;
            }

            loadingComplete();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountId", Long.toString(App.getInstance().getId()));
            params.put("accessToken", App.getInstance().getAccessToken());
            params.put("itemId", Long.toString(itemId));
            params.put("categoryId", Integer.toString(categoryId));
            params.put("language", "en");

            return params;
        }
    };

    App.getInstance().addToRequestQueue(jsonReq);
}

public void loadingComplete() {

    if (arrayLength == LIST_ITEMS) {

        viewMore = true;

    } else {

        viewMore = false;
    }

    itemsAdapter.notifyDataSetChanged();

    if (mRecyclerView.getAdapter().getItemCount() == 0) {

        if (isAdded()) {

            showMessage(getText(R.string.label_empty_list).toString());
        }

    } else {

        hideMessage();
    }

    loadingMore = false;
    mItemsContainer.setRefreshing(false);
}

static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    public interface OnItemClickListener {

        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;

    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {

        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {

                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childView != null && mListener != null) {

                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {

        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {

            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {

        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {

            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge

                outRect.top = spacing;
            }

            outRect.bottom = spacing; // item bottom

        } else {

            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)

            if (position >= spanCount) {

                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {

    Resources r = getResources();

    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

public void showMessage(String message) {

    mMessage.setText(message);
    mMessage.setVisibility(View.VISIBLE);
}

public void hideMessage() {

    mMessage.setVisibility(View.GONE);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}

}

Body:
remove getItems() from

if (!restore) {

    showMessage(getText(R.string.msg_loading_2).toString());

    getItems();
}

set click listener to your button then call getItems() method

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMessage(getText(R.string.msg_loading_2).toString());
            getItems();
        }
    });


来源: stackexchange

问:
document.querySelector doesn't work in .js file
If var raster = document.querySelector ("canvas") is in the HTML file, raster is defined and declared.  However, I'd like to have everything in my js file, only function calls in my HTML.  When I try putting var raster... in the .js file, it keeps coming up null.

Is there any way to have document.querySelector point to the associated HTML file?

```<code>// this doesn't work
//var raster = document.querySelector ("canvas").getContext ("2d");

function drawSquare (w,h) {

raster.fillStyle = "blue";
raster.fillRect (0,0,w,h);
}
</code>```

```<code><!DOCTYPE html>

<html>

    <head>
        <meta charset="utf-8">
        <title>IFS</title>
        <script src="IFS.js"></script>
    </head>

    <body>
        <canvas width="500" height="500"></canvas>
        <script>var raster = document.querySelector ("canvas").getContext ("2d");
        drawSquare (500,500);</script>
    </body>

</html>
</code>```

答:
Try moving  to the end of the HTML code, before the closing  tag, instead of having it at the .

The issue is caused because the script is loaded before the <canvas> is rendered, so document.querySelector ("canvas") returns null.

ContentLicense: CC BY-SA 3.0

Body:
If var raster = document.querySelector ("canvas") is in the HTML file, raster is defined and declared.  However, I'd like to have everything in my js file, only function calls in my HTML.  When I try putting var raster... in the .js file, it keeps coming up null.

Is there any way to have document.querySelector point to the associated HTML file?

// this doesn't work
//var raster = document.querySelector ("canvas").getContext ("2d");

function drawSquare (w,h) {

raster.fillStyle = "blue";
raster.fillRect (0,0,w,h);
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>IFS</title>

        <canvas width="500" height="500"></canvas>

Body:
Try moving <script src="IFS.js"></script> to the end of the HTML code, before the closing <body> tag, instead of having it at the <head>.

The issue is caused because the script is loaded before the <canvas> is rendered, so document.querySelector ("canvas") returns null.


问:
Azure website hiding .html extensions
Im hosting a couple of html files using an Azure website. I want to hide the .html file name extensions. I have been looking trough the site however i didnt find an options that works specifically with Azure websites. </p>

答:
You could use a URL Rewrite in the web.config file for an ASP.NET application to send a 404 or some other response for .html file requests.

Also, you could probably set up a custom HTTP handler mapping for .html extensions. That way a language processor could intercept those requests instead of just serving the file.

Title: Azure website hiding .html extensions


问:
jquery ajax file upload, success doesn't get called
I'm using jquery to upload images to a joomla site, but have problems with the file ajaxfileupload.js. The images upload just fine, but the function in "success" doesn't get called. And I need it to work to show a confirmation that the upload is finished. I have tried using "complete" instead of "success" and then the code works, but it refreshes the page over and over agian. How can I make it work like it should? Here's the code..</p>

```<code>upload: function (a) {
    if (jQuery("#Filedata-" + a).val() == "") {
        jQuery("#photoupload-" + a).remove();
        joms.uploader.upload();
        if (jQuery("#photoupload").next().length == 0) {
            joms.uploader.addNewUpload()
        }
        jQuery("#upload-photos-button").show();
        return
    }
    var c = (jQuery("#photoupload-" + a + " :input:checked").val() == "1") ? "&defaultphoto=1" : "";
    var b = jQuery("#photoupload-" + a).next().find(".elementIndex").val();
    b = (b != "") ? "&nextupload=" + b : "";
    jQuery("#photoupload-" + a).children().each(function () {
        jQuery(this).css("display", "none")
    });
    jQuery("#photoupload-" + a).append('<div id="photoupload-loading-' + a + '"><span class="loading" style="display:block;float: none;margin: 0px;"></span><span>' + joms.uploader.uploadText + "</span></div>");
    jQuery.ajaxFileUpload({
        url: this.postUrl + c + b,
        secureuri: false,
        fileElementId: "Filedata-" + a,
        dataType: "json",
        success: function (e, d) {
            jQuery("#photoupload-loading-" + a).remove();
            if (typeof (e.error) != "undefined" && e.error == "true") {
                jQuery("#photoupload-" + a).css("background", "#ffeded");
                jQuery("#photoupload-" + a).append('<span class="error">' + e.msg + "</span>")
            } else {
                jQuery("#photoupload-" + a).css("background", "#edfff3");
                jQuery("#photoupload-" + a).append('<span class="success">' + e.msg + "</span>")
            }
            jQuery("#photoupload-" + a).fadeOut(4500, function () {
                jQuery("#photoupload-" + a).remove();
                if (jQuery("#photoupload").next().length == 0) {
                    joms.uploader.addNewUpload()
                }
            });
            jQuery("#photoupload-" + a + " .remove").css("display", "block");
            if (e.nextupload != "undefined") {
                joms.uploader.upload(e.nextupload);
                return
            } else {
                jQuery("#upload-photos-button").show()
            }
        },
        error: function (f, d, g) {}
    });
    return false
}
</code>```

答:
This might be late though but for people seeing this for the first time just change
 dataType: "json",
to
 dataType: "JSON",</p>

Body:
I'm using jquery to upload images to a joomla site, but have problems with the file ajaxfileupload.js. The images upload just fine, but the function in "success" doesn't get called. And I need it to work to show a confirmation that the upload is finished. I have tried using "complete" instead of "success" and then the code works, but it refreshes the page over and over agian. How can I make it work like it should? Here's the code..

upload: function (a) {
    if (jQuery("#Filedata-" + a).val() == "") {
        jQuery("#photoupload-" + a).remove();
        joms.uploader.upload();
        if (jQuery("#photoupload").next().length == 0) {
            joms.uploader.addNewUpload()
        }
        jQuery("#upload-photos-button").show();
        return
    }
    var c = (jQuery("#photoupload-" + a + " :input:checked").val() == "1") ? "&defaultphoto=1" : "";
    var b = jQuery("#photoupload-" + a).next().find(".elementIndex").val();
    b = (b != "") ? "&nextupload=" + b : "";
    jQuery("#photoupload-" + a).children().each(function () {
        jQuery(this).css("display", "none")
    });
    jQuery("#photoupload-" + a).append('
' + joms.uploader.uploadText + "
");
    jQuery.ajaxFileUpload({
        url: this.postUrl + c + b,
        secureuri: false,
        fileElementId: "Filedata-" + a,
        dataType: "json",
        success: function (e, d) {
            jQuery("#photoupload-loading-" + a).remove();
            if (typeof (e.error) != "undefined" && e.error == "true") {
                jQuery("#photoupload-" + a).css("background", "#ffeded");
                jQuery("#photoupload-" + a).append('' + e.msg + "")
            } else {
                jQuery("#photoupload-" + a).css("background", "#edfff3");
                jQuery("#photoupload-" + a).append('' + e.msg + "")
            }
            jQuery("#photoupload-" + a).fadeOut(4500, function () {
                jQuery("#photoupload-" + a).remove();
                if (jQuery("#photoupload").next().length == 0) {
                    joms.uploader.addNewUpload()
                }
            });
            jQuery("#photoupload-" + a + " .remove").css("display", "block");
            if (e.nextupload != "undefined") {
                joms.uploader.upload(e.nextupload);
                return
            } else {
                jQuery("#upload-photos-button").show()
            }
        },
        error: function (f, d, g) {}
    });
    return false
}


问:
Bootstrap 4 - put small element between two long in a row without gaps
I want to make it look similar to this.

```<code>hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

  <div class="row code-line">
    <div class="col-5">
      <div class="line-left">
        <hr>
      </div>
    </div>
    <div class="col-1">
      <i class="fa fa-code fa-2x" aria-hidden="true"></i>
    </div>
    <div class="col-5">
     <div class="line-right">
        <hr>
      </div>
    </div>
  </div>
</code>```

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

答:
I made a quick fork of your codepen here and implemented some simple flex to make what you wanted happen. The trick was to remove the
 and use
s.

.row {
  background-color: yellow;
  display: flex;
}

.row > div.hr {
  flex: 1 1 auto;
}

.row > div.hr-icon {
  flex: 0 1 auto;
  padding: 12px;
}

.row > div {
  align-self: center;
}

.hr {
  border: none; /* Убираем границу для браузера Firefox */
  color: red; /* Цвет линии для остальных браузеров */
  background-color: red; /* Цвет линии для браузера Firefox и Opera */
  height: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="hr"></div>
    <div class="hr-icon">
      <i class="fa fa-code fa-2x" aria-hidden="true"></i>
    </div>
    <div class="hr"></div>
  </div>
</div></code>```

Body:
I want to make it look similar to this.

hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

Body:
I made a quick fork of your codepen here and implemented some simple flex to make what you wanted happen. The trick was to remove the <hr /> and use <div>s.

.row {
  background-color: yellow;
  display: flex;
}

.row > div.hr {
  flex: 1 1 auto;
}

.row > div.hr-icon {
  flex: 0 1 auto;
  padding: 12px;
}

.row > div {
  align-self: center;
}

.hr {
  border: none; /* Убираем границу для браузера Firefox */
  color: red; /* Цвет линии для остальных браузеров */
  background-color: red; /* Цвет линии для браузера Firefox и Opera */
  height: 5px;
}

<div class="container">
  <div class="row">
    <div class="hr"></div>
    <div class="hr-icon">
      <i class="fa fa-code fa-2x" aria-hidden="true"></i>
    </div>
    <div class="hr"></div>
  </div>
</div>


问:
bootstrap modal does not come up
I am trying http://bootstrap-confirmation.js.org

my html has

```<code><html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <!-- Bootstrap Core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <!-- DataTables CSS -->
    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <!-- DataTables Responsive CSS -->
    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <style>
    td.details-control {
        background: url('images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    tr.details td.details-control {
            background: url('images/details_close.png') no-repeat center center;
    }

    td.flag-control {
        background: url('images/ban_circle.png') no-repeat center center;
        cursor: pointer;
    }

      table {
            table-layout:fixed;
        }

            .word-break-all{
                word-break:break-all;
            }
        </style>

</head>

<body>

    <div id="wrapper">

        <!-- Navigation -->

        <div id="page-wrapper">
            <div class="row">
                <div class="col-lg-12">
                       <h4></h4>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>
</code>```

and toward bottom:

```<code><script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="js/bootstrap-confirmation.js"></script>
</code>```

my javascript has:

$(document).ready(function() {

```<code>     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});
</code>```

clicking the button nothing happens

答:
Not sure if the missing closing brackets was a copy and paste issue but it does seem to work when you put it all together: http://plnkr.co/edit/tmgKh22PftNMua0Pdmjo</p>

```<code>$(document).ready(function() {
    $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
    });
});
</code>```

Title: bootstrap modal does not come up

Body:
I am trying http://bootstrap-confirmation.js.org

my html has

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>

and toward bottom:

my javascript has:

$(document).ready(function() {

     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});

clicking the button nothing happens

Body:
Not sure if the missing closing brackets was a copy and paste issue but it does seem to work when you put it all together: http://plnkr.co/edit/tmgKh22PftNMua0Pdmjo

$(document).ready(function() {
    $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
    });
});


问:
How to use Enum in Camel Route?
I have the following route:

```<code>.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)
</code>```

I want to use this enum to compare.

```<code>  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}
</code>```

I tried to do something like this, but it doesn't works..

```<code>.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")
</code>```

Any idea to solve this problem?

答:
According to http://camel.apache.org/simple.html you can use just

```<code>.simple("${body.messageType} == ${type:myPackage.Code.CODE_A}")
</code>```

In example you have tried you are using

```<code>myPackage.Code.value()
</code>```

not

```<code>myPackage.Code.CODE_A
</code>```

Title: How to use Enum in Camel Route?

Body:
I have the following route:

.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)

I want to use this enum to compare.

  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

I tried to do something like this, but it doesn't works..

.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")

Any idea to solve this problem?

Body:
According to http://camel.apache.org/simple.html you can use just

.simple("${body.messageType} == ${type:myPackage.Code.CODE_A}")

In example you have tried you are using

myPackage.Code.value()

not

myPackage.Code.CODE_A


问:
Flex Builder Tween Library
There are missing tween libraries in my Flex Builder how to add them?

Sultan

答: You can use mx.effects.Tween for tweening. But i recommend using other tweening library like TweenLite, Tweener..etc.</p>

ContentLicense: CC BY-SA 2.5

Title: Flex Builder Tween Library


问:
Inserting DATETIME to SQL from PHP
I can't seem to store the datetime to the database.

```<code>public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}
</code>```

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table

答:
Help this code for you,</p>

```<code>public function add_post($username, $content) {
   date_default_timezone_set("Asia/Manila");
   $date = date("m/d/Y h:i A");
   $final = strtotime($date);
   $time_posted = date("Y-m-d H:i:s", $final);

   $sql =" INSERT INTO POSTS (username, post_content, time_posted)
        VALUES ('$username','$content','$time_posted')";

    return $this->db->query($sql);
}
</code>```

Title: Inserting DATETIME to SQL from PHP

Body:
I can't seem to store the datetime to the database.

public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table

Body:
Help this code for you,

public function add_post($username, $content) {
   date_default_timezone_set("Asia/Manila");
   $date = date("m/d/Y h:i A");
   $final = strtotime($date);
   $time_posted = date("Y-m-d H:i:s", $final);

   $sql =" INSERT INTO POSTS (username, post_content, time_posted)
        VALUES ('$username','$content','$time_posted')";

    return $this->db->query($sql);
}


问:
Deploy a .NET Core Console app to PCF
I'm trying to deploy a dotnet core Console app to PCF, it seems to deploy fine, but the health check fails trying to reach the app at http://0.0.0.0:${PORT}. Since it's a console app, it doesn't have an HTTP endpoint. On the app info I can see this:

```<code>Start Command: dotnet dotnet-app.dll --server.urls http://0.0.0.0:${PORT}
</code>```

It's expecting the app to be a web app by default. Is there a way to deploy it using a console app setup for pcf?

The buildpack is:

```<code>Buildpack: ASP.NET Core (buildpack-1.0.4)
</code>```

I'm wondering if there is a pure .NET Core buildpack.

答:
Have you tried adding the 'no-route' to your manifest file?

This will prevent pcf from trying to bind a port.

```<code>no-route: true
</code>```

You may also need to disable health checking:

```<code>cf set-health-check APP_NAME none
</code>```

Title: Deploy a .NET Core Console app to PCF

Body:
I'm trying to deploy a dotnet core Console app to PCF, it seems to deploy fine, but the health check fails trying to reach the app at http://0.0.0.0:${PORT}. Since it's a console app, it doesn't have an HTTP endpoint. On the app info I can see this:

Start Command: dotnet dotnet-app.dll --server.urls http://0.0.0.0:${PORT}

It's expecting the app to be a web app by default. Is there a way to deploy it using a console app setup for pcf?

The buildpack is:

Buildpack: ASP.NET Core (buildpack-1.0.4)

I'm wondering if there is a pure .NET Core buildpack.

Body:
Have you tried adding the 'no-route' to your manifest file?

This will prevent pcf from trying to bind a port.

no-route: true

You may also need to disable health checking:

cf set-health-check APP_NAME none


问:
SQL: Only Group to only display 1 Membership Level
```<code>select
u.Resnet_Agent_ID,
u.First_Name + ' ' + u.Last_Name AS [Agent Name],
u.Email,
[Current Membership Level] = CASE
 WHEN u.UserMembershiptType_CodeID = 1 THEN 'Standard'
 WHEN u.UserMembershiptType_CodeID = 2 THEN 'Premium Membership'
 WHEN u.UserMembershiptType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN u.UserMembershiptType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN u.UserMembershiptType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN u.UserMembershiptType_CodeID = 6 THEN 'Pro'
 WHEN u.UserMembershiptType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END,
[Prior Paid Membership Level] = CASE
 WHEN mh.MembershipType_CodeID = 2 THEN 'Premium Membership'
 WHEN mh.MembershipType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN mh.MembershipType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN mh.MembershipType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN mh.MembershipType_CodeID = 6 THEN 'Pro'
 WHEN mh.MembershipType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END, mh.Description
  from amp.dbo.tbl_User u (nolock)
join amp.dbo.tbl_MembershipHistoryNew mh (nolock)
    on u.UniversalUserId = mh.AgentUniversalUserId
where u.IsAgent = 1 and mh.MembershipType_CodeID <> 1
</code>```

How can  I group the Current Membership Level to only display  "one current membership level, only one Resnet_Agent_ID, only one Agent Name, only one Email" ?

答:
Its unclear if you want to include or exclude members that have a code as null.
if you want nulls then use:
and (mh.MembershipType_Codeid <> 1 or mh.MembershipType_Codeid is null)
otherwise use:
and (mh.MembershipType_Codeid <> 1 or mh.MembershipType_Codeid not null)</p>

Body:
select
u.Resnet_Agent_ID,
u.First_Name + ' ' + u.Last_Name AS [Agent Name],
u.Email,
[Current Membership Level] = CASE
 WHEN u.UserMembershiptType_CodeID = 1 THEN 'Standard'
 WHEN u.UserMembershiptType_CodeID = 2 THEN 'Premium Membership'
 WHEN u.UserMembershiptType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN u.UserMembershiptType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN u.UserMembershiptType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN u.UserMembershiptType_CodeID = 6 THEN 'Pro'
 WHEN u.UserMembershiptType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END,
[Prior Paid Membership Level] = CASE
 WHEN mh.MembershipType_CodeID = 2 THEN 'Premium Membership'
 WHEN mh.MembershipType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN mh.MembershipType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN mh.MembershipType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN mh.MembershipType_CodeID = 6 THEN 'Pro'
 WHEN mh.MembershipType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END, mh.Description
  from amp.dbo.tbl_User u (nolock)
join amp.dbo.tbl_MembershipHistoryNew mh (nolock)
    on u.UniversalUserId = mh.AgentUniversalUserId
where u.IsAgent = 1 and mh.MembershipType_CodeID <> 1

How can  I group the Current Membership Level to only display  "one current membership level, only one Resnet_Agent_ID, only one Agent Name, only one Email" ?


问:
Node-Red - JSON over MQTT - Remove String
Question about JSON via MQTT
Raspberry pi w/gps sending location data to server via MQTT. all the information is received by the server fine, however, the payload is a string when received.

How to remove the "" from my json.

Raw from GPS Module:

3/31/2017, 2:13:29 PMec04f460.a91eb8
msg.payload : Object

{ "class": "TPV", "tag": "RMC", "device": "/dev/ttyUSB0", "mode": 3, "time": "2017-03-31T18:14:48.000Z", "ept": 0.005, "lat": 29.844941667, "lon": -81.277976667, "alt": 2.2, "epx": 45.649, "epy": 10.829, "epv": 4.945, "track": 171.72, "speed": 0.046, "climb": 0, "eps": 91.3, "epc": 9.89 }

directly to MQTT server via Node-Red

Server Receives:

3/31/2017, 2:16:26 PMnode: d369167f.b8ea58
trolley281/gps : msg.payload : string[251]

"{"class":"TPV","tag":"RMC","device":"/dev/ttyUSB0","mode":3,"time":"2017-03-31T18:17:46.000Z","ept":0.005,"lat":29.844945,"lon":-81.277986667,"alt":2.9,"epx":45.649,"epy":10.829,"epv":4.945,"track":166.53,"speed":0.005,"climb":0,"eps":91.3,"epc":9.89}"

As a string...

Anyone have an idea how to clean this up?

答: Look in the palette for the JSON node, it will convert a JSON string to a JSON object (or vis versa).


问:
Button tag isn't being recognized as being clicked, with on('click') function?
Ok so this is a little weird explanation but I till try to get through it. First off, i am unable to share a lot of code but i will make code that is similar to what is written. Ok so my problem is that I am using an iframe to make a tour on a web page, in said iframe the user should be able to click a button. Once clicked on the left side of the page should be a table of all the elements that can be clicked, in this table it would scroll to the element that is connected to said button in the iframe. Now my problem comes into play here, there are three buttons that aren't doing what i described. Two of them are cancel buttons and the other is a reset to default button(the code for them will be shown). The especially weird thing is that there are other cancel buttons and reset buttons that do work. There is code inside a js file that is a click function, where contentDocument is the body of the iframe, but the ones that dont work never enter this call.

```<code>$(this.contentDocument).on('click', function(e){ does stuff and things});
</code>```

These are code from the ones that don't work!!!

```<code><button type="button" name="btn-basic-form-cancel" id="btn-basic-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
<button type="button" name="btn-basic-form-reset" id="btn-basic-form-reset" class="button-small icon-reset" onclick="">Reset to Default</button>
<button type="button" name="btn-advanced-form-cancel" id="btn-advanced-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
</code>```

These are code from ones that are working!!!

```<code><button type="button" name="btn-advanced-form-reset" id="btn-advanced-form-reset" class="button-small icon-reset" onclick="">Reset</button>
<button type="button" name="btn-ziplookup-form-cancel" id="btn-ziplookup-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
<button type="button" name="btn-columns-cancel" id="btn-columns-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
</code>```

Ok so if you any further questions please ask, i tried my best to explain everything but there is a chance that i did miss something. ::UPDATE I have narrowed it down to the fact that those three buttons aren't being recognized to be inside contentDocument, why would they not be if everything else around it is?

答:
Give your iframe an ID, then reference it as such:

```<code>$('#myiframe').load(function(){
  var iframe = $('#myiframe').contents();
  iframe.find("button").on('click',function(e){
      alert("test");
      alert($(e.target).text());// or some such
  });
});
</code>```

OR

```<code>$("#myiframeid").load( function() {
    $("#myiframeid").contents().on("click", "button", function() {
        //do something
    });
});
</code>```

These SHOULD ensure it is loaded prior to attaching the event handler.

Body:
Ok so this is a little weird explanation but I till try to get through it. First off, i am unable to share a lot of code but i will make code that is similar to what is written. Ok so my problem is that I am using an iframe to make a tour on a web page, in said iframe the user should be able to click a button. Once clicked on the left side of the page should be a table of all the elements that can be clicked, in this table it would scroll to the element that is connected to said button in the iframe. Now my problem comes into play here, there are three buttons that aren't doing what i described. Two of them are cancel buttons and the other is a reset to default button(the code for them will be shown). The especially weird thing is that there are other cancel buttons and reset buttons that do work. There is code inside a js file that is a click function, where contentDocument is the body of the iframe, but the ones that dont work never enter this call.

$(this.contentDocument).on('click', function(e){ does stuff and things});

These are code from the ones that don't work!!!

<button type="button" name="btn-basic-form-cancel" id="btn-basic-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
<button type="button" name="btn-basic-form-reset" id="btn-basic-form-reset" class="button-small icon-reset" onclick="">Reset to Default</button>
<button type="button" name="btn-advanced-form-cancel" id="btn-advanced-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>

These are code from ones that are working!!!

<button type="button" name="btn-advanced-form-reset" id="btn-advanced-form-reset" class="button-small icon-reset" onclick="">Reset</button>
<button type="button" name="btn-ziplookup-form-cancel" id="btn-ziplookup-form-cancel" class="button-small icon-cancel" onclick="">Cancel</button>
<button type="button" name="btn-columns-cancel" id="btn-columns-cancel" class="button-small icon-cancel" onclick="">Cancel</button>

Ok so if you any further questions please ask, i tried my best to explain everything but there is a chance that i did miss something. ::UPDATE I have narrowed it down to the fact that those three buttons aren't being recognized to be inside contentDocument, why would they not be if everything else around it is?

Body:
Give your iframe an ID, then reference it as such:

$('#myiframe').load(function(){
  var iframe = $('#myiframe').contents();
  iframe.find("button").on('click',function(e){
      alert("test");
      alert($(e.target).text());// or some such
  });
});

OR

$("#myiframeid").load( function() {
    $("#myiframeid").contents().on("click", "button", function() {
        //do something
    });
});

These SHOULD ensure it is loaded prior to attaching the event handler.


问:
How do I write a custom event string to Aws cloudwatch logs
I have spent hours digging through Aws documentation, and I cannot find a c# 'hello world' type sample showing how to programmatically write something simple (like a string or something similar) to Aws cloud watch logs. Perhaps I am not looking in the right place, but Amazon's sdk documentation and code samples seems to be lacking. Anyone have a link to the (probably) 10 lines of code I need?</p>

答: After some time I have come to the conclusion that there is no simple way to write individual events to AWS in an atomic fashion. You can write a single event to a logfile, and send that to AWS. However, AWS really isn't the tool for streaming logs to a repository in real time. There are much better providers available for performing actions like that.</p>


问:
Attach JSON data to be used by view in MVC application
I have a very simple application that I am using to learn move about MVC. In that application I search some data and return a JSON string that I want to use as the model for the view. I just can't seem to figure out how to get the view to consume the JSON as a set of data for it to show on screen.

The code I have so far:

```<code>Function Find(term As String) As ActionResult

    Dim model As String = SearchData(term)

    Return View(model)
End Function
</code>```

SearchData returns a JSON string that can have one or many objects in it.

How do I now take the JSON returned from SearchData and use it in a view? In fact, when I attempt to add a view it wants to know what model to use. How do i also specific that?

答:
Create a strongly typed object to store you data when parsed

```<code>Public Class Data
    Public Property ID As Integer
    Public Property Term As String
    Public Property SomeProperty As String
    Public Property SomeOtherProperty As String
End Class
</code>```

Using a library like JSON.Net, parse the JSON returned from the search.

This assumes a collection of Data is returned from the search.

```<code>Imports Newtonsoft.Json;

Function Find(term As String) As ActionResult
    Dim json As String = SearchData(term)
    Dim model As List(Of Data) = JsonConvert.DeserializeObject(Of List(Of Data))(json)
    Return View(model)
End Function
</code>```

Let the view know to expect the strongly typed model.

```<code>@ModelType List(Of Data)
@Code
    ViewData("Title") = "Find"
End Code

<h2>MyView</h2>
<!-- rest of view where model can be accessed -->
</code>```

Body:
I have a very simple application that I am using to learn move about MVC. In that application I search some data and return a JSON string that I want to use as the model for the view. I just can't seem to figure out how to get the view to consume the JSON as a set of data for it to show on screen.

The code I have so far:

Function Find(term As String) As ActionResult

    Dim model As String = SearchData(term)

    Return View(model)
End Function

SearchData returns a JSON string that can have one or many objects in it.

How do I now take the JSON returned from SearchData and use it in a view? In fact, when I attempt to add a view it wants to know what model to use. How do i also specific that?

Body:
Create a strongly typed object to store you data when parsed

Public Class Data
    Public Property ID As Integer
    Public Property Term As String
    Public Property SomeProperty As String
    Public Property SomeOtherProperty As String
End Class

Using a library like JSON.Net, parse the JSON returned from the search.

This assumes a collection of Data is returned from the search.

Imports Newtonsoft.Json;

Function Find(term As String) As ActionResult
    Dim json As String = SearchData(term)
    Dim model As List(Of Data) = JsonConvert.DeserializeObject(Of List(Of Data))(json)
    Return View(model)
End Function

Let the view know to expect the strongly typed model.

@ModelType List(Of Data)
@Code
    ViewData("Title") = "Find"
End Code

<h2>MyView</h2>
<!-- rest of view where model can be accessed -->


问:
Recycler view adding item at position creating empty views and not updating data on added position
adding a item dynamically which is not giving me desired output, with static data its working fine but not with dynamic data. view are repeating sometimes and some times its creating empty views.

Fragment service call:

```<code>public void getDataFromServer() {
        try {
            RequestParams params = new RequestParams();
            String url = ApplicationConstants.GET_ITEMS;

            if (networkClient!= null)
                networkClient.getData(url, params, new ItemsDataListener());

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

    class ItemsDataListener extends ResponseHandler{

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] byteResponse) {
            try {
                String response = new String(byteResponse);
                if (response != null && !response.isEmpty()) {
                    Model model=new Gson().fromJson(response,Model.class);
                    mAdapter.addItem(model, 2);

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

        @Override
        public void onFailure(int statusCode, byte[] byteResponse) {

        }
    }
</code>```

this is the method in my adapter:

```<code>public class ItemCardAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context = null;
    private ArrayList<Model> itemList;

    public ItemCardAdapter(Context context) {
        super();
        this.context = context;
        this.activity = (Activity) context;
        itemList= new ArrayList<>();

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int viewType) {

            View v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.single_item_view, viewGroup, false);
            ItemCardHolder itemCardHolder = new ItemCardHolder(v);

            return itemCardHolder ;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {

         (holder instanceof ItemCardHolder) {
            Model model=itemList.get(i)
            ((ItemCardHolder) holder).populateData(model);
        }
    }

    @Override
    public int getItemCount() {

            return itemList.size();
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
            ((ItemCardHolder) holder).cardview.clearAnimation();
    }

     public void addItem(Model newItem, int position) {
            itemlist.add(position, newItem);
            this.notifyItemInserted(position);
            this.notifyItemChanged(position);

        }

    public void clearData() {
        itemList.clear();
        this.notifyDataSetChanged();
    }

}
</code>```

答:
You are doing wrong here

```<code>mAdapter.addItem(model, 2);
</code>```

It will try to add item at 2 position always even if no data. try to get item count from adapter and then try to add item.

Body:
adding a item dynamically which is not giving me desired output, with static data its working fine but not with dynamic data. view are repeating sometimes and some times its creating empty views.

Fragment service call:

public void getDataFromServer() {
        try {
            RequestParams params = new RequestParams();
            String url = ApplicationConstants.GET_ITEMS;

            if (networkClient!= null)
                networkClient.getData(url, params, new ItemsDataListener());

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

    class ItemsDataListener extends ResponseHandler{

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] byteResponse) {
            try {
                String response = new String(byteResponse);
                if (response != null && !response.isEmpty()) {
                    Model model=new Gson().fromJson(response,Model.class);
                    mAdapter.addItem(model, 2);

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

        @Override
        public void onFailure(int statusCode, byte[] byteResponse) {

        }
    }

this is the method in my adapter:

public class ItemCardAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context = null;
    private ArrayList<Model> itemList;

    public ItemCardAdapter(Context context) {
        super();
        this.context = context;
        this.activity = (Activity) context;
        itemList= new ArrayList<>();

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int viewType) {

            View v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.single_item_view, viewGroup, false);
            ItemCardHolder itemCardHolder = new ItemCardHolder(v);

            return itemCardHolder ;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {

         (holder instanceof ItemCardHolder) {
            Model model=itemList.get(i)
            ((ItemCardHolder) holder).populateData(model);
        }
    }

    @Override
    public int getItemCount() {

            return itemList.size();
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
            ((ItemCardHolder) holder).cardview.clearAnimation();
    }

     public void addItem(Model newItem, int position) {
            itemlist.add(position, newItem);
            this.notifyItemInserted(position);
            this.notifyItemChanged(position);

        }

    public void clearData() {
        itemList.clear();
        this.notifyDataSetChanged();
    }

}

Body:
You are doing wrong here

mAdapter.addItem(model, 2);

It will try to add item at 2 position always even if no data. try to get item count from adapter and then try to add item.