-1

J'ai créé l'application de fond d'écran en ligne et j'ai l'habitude d'activité pour mon application et j'utilise volley et glide pour mon application mais quand j'utilise le tiroir de navigation du bas, l'activité n'est pas utile. après que je l'utilise fragment mais maintenant quand je lance l'application mon recyclerview ne montre rienpourquoi mon recyclerview ne montre pas les données dans le fragment?

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

+0

Quelles mesures de débogage avez-vous prises? Le code de vue est-il atteint? – jdv

Répondre

0

Il y a des considérations de Context que vous devez faire throught votre code. Vous pouvez utiliser le mauvais exemple Context s très grand Context s. Par exemple de ce que je peux voir rapidement l'une est dans cette ligne MainFragment.java:

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

Vous avez passé le contexte d'application alors que vous avez juste besoin Context d'activité. Donc, changez cela en:

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

Essayez de le faire si cela fonctionnera ou essayez d'essayer de trouver plus de code pouvant causer un problème.