为什么我的recyclerview没有显示片段中的数据?

时间:2017-10-21 13:55:40

标签: java android android-fragments android-recyclerview android-volley

我创建了在线壁纸应用程序,我曾经为我的应用程序活动,我使用排球和滑行为我的应用程序,但当我使用底部导航抽屉,活动是没有用的。 之后我使用片段,但现在当我运行应用程序时,我的recyclerview没有显示任何内容

MainFragment.java:

package ir.zooding.wallpaper.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
 import android.widget.TextView;
 import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.util.ArrayList;

import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.adapter.GalleryAdapter;
import ir.zooding.wallpaper.app.AppController;
import ir.zooding.wallpaper.model.Image;
import ir.zooding.wallpaper.receiver.ConnectivityReceiver;

public class MainFragment extends Fragment implements     ConnectivityReceiver.ConnectivityReceiverListener {

  RecyclerView recycler_view;
  static final String url="";
  ArrayList<Image> images;
  GalleryAdapter mAdapter;
  ProgressDialog pd;
  View v;

  public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  }

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

v = inflater.inflate(R.layout.fragment_main, container, false);


Toolbar toolbar=(Toolbar)v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

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


pd=new ProgressDialog(getActivity());
pd.setCancelable(false);

images=new ArrayList<>();
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);



RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getActivity().getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);


recycler_view.setAdapter(mAdapter);
Log.i("LOG:","stop 1");





ActivityCompat.requestPermissions(getActivity(),
  new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
  1);

recycler_view.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity().getApplicationContext(),recycler_view, new GalleryAdapter.ClickListener() {
  @Override
  public void onClick(View view, int position) {

    Bundle bundle=new Bundle();
    bundle.putSerializable("images",images);
    bundle.putInt("position",position);
    //Log.i("LOG:",""+position);



    // FragmentTransaction ft=getFragmentManager().beginTransaction();
    android.app.FragmentTransaction ft=getActivity().getFragmentManager().beginTransaction();

    SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
    newFragment.setArguments(bundle);
    newFragment.show(ft,"slideshow");


  }

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

  }
}));


checkConnection();

fetchImages();



return inflater.inflate(R.layout.fragment_main, container, false);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode,
                                     String permissions[], int[] grantResults) {
switch (requestCode) {
  case 1: {

    // If request is cancelled, the result arrays are empty.
    if (grantResults.length > 0
      && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

      // permission was granted, yay! Do the
      // contacts-related task you need to do.
    } else {

      // permission denied, boo! Disable the
      // functionality that depends on this permission.
      Toast.makeText(getActivity(), "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
    }
    return;
  }

  // other 'case' lines to check for other
  // permissions this app might request
    }
  }



  public void fetchImages()
  {

pd.setMessage("در حال بارگزاری ...");
pd.show();


StringRequest req = new StringRequest(url,
  new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
      Log.d("", response.toString());
      pd.dismiss();

      images.clear();
      try {
        JSONObject object = new JSONObject(response);
        JSONArray dataArray = object.getJSONArray("data");

        for (int i = 0; i < dataArray.length(); i++) {
          JSONObject dataObject = dataArray.getJSONObject(i);

          Image image = new Image();
          image.setName_client(dataObject.getString("name_client"));
          image.setName(dataObject.getString("name"));

          // JSONObject url = object.getJSONObject("url");
          image.setSmall(dataObject.getString("small"));
          image.setOriginal(dataObject.getString("orginal"));
          image.setTimestamp(dataObject.getString("timestamp"));

          images.add(image);

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


      Log.i("LOG:","stop 2");

      mAdapter.notifyDataSetChanged();
      Log.i("LOG:","stop 3");

    }
  }, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
    Log.e("", "Error: " + error.getMessage());
    pd.dismiss();
  }
});


AppController.getmInstance().addToRequsetQueue(req);



  }

  // Method to manually check connection status
  private void checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected();
    showSnack(isConnected);
  }

  // Showing the status in Snackbar
  private void showSnack(boolean isConnected) {
String message ="";
//View parentLayout = v.findViewById(android.R.id.content);
RelativeLayout parentLayout = (RelativeLayout)v.findViewById(R.id.mroot);

if (!isConnected) {
  message = "اتصال شما به اینترنت برقرار نیست!";
  Snackbar snackbar = Snackbar
    .make(parentLayout, message, Snackbar.LENGTH_LONG)
    .setAction("بررسی مجدد", new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        fetchImages();
        checkConnection();
      }
    });
  snackbar.setActionTextColor(Color.RED);
  snackbar.setActionTextColor(Color.parseColor("#e62d3f"));
  View sbView = snackbar.getView();
  TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
  textView.setTextColor(Color.parseColor("#FFC107"));
  snackbar.setDuration(8000);

  snackbar.show();
    }


  }

  @Override
  public void onResume() {
    super.onResume();

// register connection status listener
AppController.getmInstance().setConnectivityListener(this);
  }

  /**
   * Callback will be triggered when there is change in
   * network connection
   */
  @Override
  public void onNetworkConnectionChanged(boolean isConnected) {
    showSnack(isConnected);
  }
}

GalleryAdapter.java:

package ir.zooding.wallpaper.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.List;

import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.model.Image;

import static android.R.animator.fade_in;


public class GalleryAdapter extends             RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

List<Image> images;
Context mContext;

public GalleryAdapter (Context context,List<Image> images){

this.images = images;
mContext = context;

}

@Override
public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int     viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_thumbnail,parent,false);
return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(GalleryAdapter.MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getSmall())
  .thumbnail(0.5f)
  .diskCacheStrategy(DiskCacheStrategy.ALL)
  .placeholder(R.drawable.loading)
  .fitCenter()
  .into(holder.thumbnail);






}

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

public interface ClickListener{

void onClick (View view,int position);
void onLongClick (View view,int position);


}

public static class RecyclerTouchListener implements     RecyclerView.OnItemTouchListener{
GalleryAdapter.ClickListener clickListener;
GestureDetector gestureDetector;

public RecyclerTouchListener(Context context,final RecyclerView recyclerView,final GalleryAdapter.ClickListener clickListener){

  this.clickListener = clickListener;

  gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){

    @Override
    public boolean onSingleTapUp(MotionEvent e){

      return  true;
    }


    @Override
    public void onLongPress(MotionEvent e){

      View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
      if(child != null && clickListener != null){

        clickListener.onLongClick(child,recyclerView.getChildPosition(child));
      }


    }


  });

}

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



  View child = rv.findChildViewUnder(e.getX(),e.getY());
  if(child != null && clickListener != null&& gestureDetector.onTouchEvent(e)){

    clickListener.onClick(child,rv.getChildPosition(child));
  }

  return false;
}

@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {

}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}
}

public class MyViewHolder extends RecyclerView.ViewHolder{

ImageView thumbnail;
public MyViewHolder(View view) {
  super(view);

  thumbnail =(ImageView) view.findViewById(R.id.thumbnail);
}
}
}

MainActivity.java:

package ir.zooding.wallpaper.activity;

import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import ir.adad.client.Adad;
import ir.zooding.wallpaper.R;

public class MainActivity extends AppCompatActivity {



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

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

BottomNavigationView bottomNavigationView = (BottomNavigationView)
  findViewById(R.id.navigation);

bottomNavigationView.setOnNavigationItemSelectedListener
  (new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
      Fragment selectedFragment = null;
      switch (item.getItemId()) {
        case R.id.action_item1:
          selectedFragment = MainFragment.newInstance();
          break;
        case R.id.action_item2:
          selectedFragment = CategoryFragment.newInstance();
          break;
        case R.id.action_item3:
          selectedFragment = InfoFragment.newInstance();
          break;
      }
      FragmentTransaction transaction =     getSupportFragmentManager().beginTransaction();
      transaction.replace(R.id.frame_layout, selectedFragment);
      transaction.commit();
      return true;
    }
});

//Manually displaying the first fragment - one time only
 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, MainFragment.newInstance());
transaction.commit();

//Used to select an item programmatically
//bottomNavigationView.getMenu().getItem(2).setChecked(true);

}
}

fragment_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<RelativeLayout
    android:id="@+id/mroot"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"

        />

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

<include
    android:id="@+id/include"
    layout="@layout/content_main"/>

content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

android:paddingTop="?attr/actionBarSize">


<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:scrollbars="vertical"/>

1 个答案:

答案 0 :(得分:0)

您需要考虑Context个问题。您可能使用错误的Context示例非常大Context s。例如,根据我所看到的,快速的一个是MainFragment.java中的这一行:

mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);

您在活动中只需要Context时已经传递了应用程序上下文。所以改为:

mAdapter=new GalleryAdapter(getActivity(),images); // remove the method getApplicationContext

尝试这样做,如果它可以工作,或者让我们尝试找到可能带来问题的更多代码。