0

Estoy tratando de usar SwipeRefresh para actualizar una lista de imágenes que se obtienen de un .json pero no se exactamente como, aquí esta el código, como debo modificarlo?

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>

1 respuesta 1

0

Buenos dias, en tu layout tenes que rodear todo con el tag SwipeRefreshLayout

  <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>

luego en tu MainActivity inicializas el swipetorefresh

private SwipeRefreshLayout mSwipeRefreshLayout;

en el oncreate

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

Debajo creas un OnRefreshListener para setear que es lo que quieres actualizar

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

No te olvides de poner en tus dependencias el siguiente compile

apply plugin: 'com.android.application'

//...

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

Espero te sirva, saludos

2
  • Gracias compañero
    – SpaceSpace
    Commented el 4 nov. 2016 a las 18:43
  • @SpaceSpace podrias calificar la respuesta como positiva o darle el checkout de completada :) Commented el 4 nov. 2016 a las 22:20

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.