0 votes

How to implement Swiperefreshlayout in this code?

I am trying to use SwipeRefresh to update a list of images that are obtained from a .json but I don't know exactly how, here is the code, how should I modify it?

MainActivity.java
package info.androidhive.glide.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;  
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import info.androidhive.glide.R;
import info.androidhive.glide.adapter.GalleryAdapter;
 import info.androidhive.glide.app.AppController;
import info.androidhive.glide.model.Image;

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "http://api.androidhive.info/json/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    pDialog = new ProgressDialog(this);
    images = new ArrayList<>();
    mAdapter = new GalleryAdapter(getApplicationContext(), images);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    /* recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("images", images);
            bundle.putInt("position", position);

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
            newFragment.setArguments(bundle);
            newFragment.show(ft, "slideshow");
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));*/

    fetchImages();
}

private void fetchImages() {

    pDialog.setMessage("Downloading json...");
    pDialog.show();

    JsonArrayRequest req = new JsonArrayRequest(endpoint,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();

                    images.clear();
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject object = response.getJSONObject(i);
                            Image image = new Image();
                            image.setName(object.getString("name"));

                            JSONObject url = object.getJSONObject("url");
                            image.setSmall(url.getString("small"));
                            image.setMedium(url.getString("medium"));
                            image.setLarge(url.getString("large"));
                            image.setTimestamp(object.getString("timestamp"));

                            images.add(image);

                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            pDialog.hide();
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);
}
}

Activity_main.xml

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

0voto

Armando Barreda Points 366

Good morning, in your layout you have to surround everything with the SwipeRefreshLayout tag.

  <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/activity_main_swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

 Tus cosas

    </android.support.v4.widget.SwipeRefreshLayout>

then in your MainActivity you initialize swipetorefresh

private SwipeRefreshLayout mSwipeRefreshLayout;

in the oncreate

mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);

Below you create an OnRefreshListener to set what you want to update.

mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh() {
          //Aqui debe ir lo que quieras actualizar, en tu caso pedir que el json vuelva a hacer el request.
            fetchimages();
    } 
    });

Don't forget to put the following compile in your dependencies

apply plugin: 'com.android.application'

//...

dependencies {
    // ...
    compile 'com.android.support:support-v4:24.2.1'
}

I hope you find it useful, best regards

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X