简体   繁体   English

为什么我的recyclerview适配器不起作用? /为什么班级没有上课?

[英]Why does my recyclerview adapter not work? / Why is the class not running?

I have been trying to get the adapter for my RecyclerView to work, but I cannot get anything to display upon the cards, and also, the CycleTrails class does not run as the Logcat does not show any of the logs setup through the class... Before I setup the Adapter, everything worked fine, I could get all of the values from my CycleTrails class. 我一直在尝试使我的RecyclerView适配器正常工作,但无法在卡上显示任何内容,而且,CycleTrails类无法运行,因为Logcat不会显示通过该类设置的任何日志。在设置适配器之前,一切工作正常,我可以从CycleTrails类中获取所有值。 But now, things are messed up and I cannot figure out why. 但是现在,事情变得混乱了,我不知道为什么。

MainActivity.java (the onCreate part/only thing that I added with the adapter) MainActivity.java(与适配器一起添加的onCreate部分/唯一内容)

@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rvItem = (RecyclerView) findViewById(R.id.rvItem);
    rvItem.setHasFixedSize(true);
    LinearLayoutManager manager = new LinearLayoutManager(this);
    rvItem.setLayoutManager(manager);
    ArrayList<Trails> finalData = getTrails();
    Adapter adapter = new Adapter(this, finalData);
    rvItem.setAdapter(adapter);

CycleTrails.java CycleTrails.java

public class CycleTrails extends MainActivity {

public static double LAT_MAX = myLatitude + (0.01 * 200);
public static double LAT_MIN = myLatitude - (0.01 * 200);
public static double LON_MAX = myLongitude + (0.01 * 200);
public static double LON_MIN = myLongitude - (0.01 * 200);

public static ArrayList<Trails> getTrails() {
    Log.d("trails", "Cycle trails running");
    ArrayList<Trails> trailList = new ArrayList<>();
    Trails t1 = new Trails(51.71, -3.36, "Bike Park Wales", "", "", "");
    Trails t2 = new Trails(51.66, -3.35, "Mountain Ash", "", "", "");
    Trails t3 = new Trails(50.50, -4.17, "FlyUp Downhill", "", "", "");
    trailList.add(t1);
    trailList.add(t2);
    trailList.add(t3);


    final ArrayList<Trails> localTrails = new ArrayList<>();
    for (final Trails trail : trailList) {
        Log.d("List running", "Local trail list");
        if (trail.lat > LAT_MIN && trail.lat < LAT_MAX && trail.lon > LON_MIN && trail.lon < LON_MAX) {
            localTrails.add(trail);
            Log.d("Calc", "Run code");


            final RequestBuilder weather = new RequestBuilder();

            final Request request = new Request();
            request.setLat(String.valueOf(trail.lat));
            Log.d("Lat used", String.valueOf(trail.lat));
            Log.d("Actual Lat", request.getLat());
            request.setLng(String.valueOf(trail.lon));
            Log.d("Lon used", String.valueOf(trail.lon));
            request.setUnits(Request.Units.UK);
            request.setLanguage(Request.Language.ENGLISH);
            request.addExcludeBlock(Request.Block.CURRENTLY);
            request.removeExcludeBlock(Request.Block.CURRENTLY);


            weather.getWeather(request, new Callback<WeatherResponse>() {
                @Override
                public void success(WeatherResponse weatherResponse, Response response) {
                    Log.d("Weather", "We have weather!");
                    Log.d("Location", weatherResponse.getTimezone());
                    trail.temp = String.valueOf(weatherResponse.getCurrently().getTemperature());
                    Log.d("Temperature", trail.temp);
                    trail.weather = weatherResponse.getCurrently().getIcon();
                }

                @Override
                public void failure(RetrofitError retrofitError) {
                    Log.d("Error while calling: ", "Weather");
                }


            });
        } else {
            Log.d("Too far", "Trails too far" + trail.name);
        }
    }
    return localTrails;
}

}

Adapter 适配器

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private Context context;
public ArrayList <Trails> finalData;

public Adapter (Context context, ArrayList<Trails> finalData) {
    Log.d("Hello", "Adapter");
    this.context = context;
    this.finalData = finalData;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    Log.d("Hello", "2");
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.trail_card, parent, false);
    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Trails trails = finalData.get(position);
    Log.d("Hello", "3");
    Picasso.with(context)
            .load("http://www.wigglestatic.com/product-media/5360108808/Wiggle-Road-Bike-Road-Bikes-Black-1WGMY16R7048UK0001-6.jpg?w=2000&h=2000&a=7")
            .placeholder(R.drawable.cycle)
            .error(android.R.drawable.stat_notify_error)
            .into(holder.locationImage);
    holder.locationText.setText(trails.name);
    Log.d("Location", trails.name);
    holder.temperatureText.setText(trails.temp);
    Log.d("Temperature", trails.temp);
    holder.weatherText.setText(trails.weather);
    holder.conditionsText.setText(trails.conditions);
}

@Override
public int getItemCount() {
    Log.d("Hello", "4");
    if(finalData != null) {
        Log.d("Hello", "5");
        return finalData.size();
    }
    return 0;
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    public CardView cardView;
    public ImageView locationImage;
    public TextView locationText;
    public TextView temperatureText;
    public TextView weatherText;
    public TextView conditionsText;

    public ViewHolder(View itemView) {
        super(itemView);
        cardView = (CardView)itemView.findViewById(R.id.cardView);
        locationImage = (ImageView)itemView.findViewById(R.id.locationImage);
        locationText = (TextView)itemView.findViewById(R.id.locationText);
        temperatureText = (TextView)itemView.findViewById(R.id.temperatureText);
        weatherText = (TextView)itemView.findViewById(R.id.weatherText);
        conditionsText = (TextView)itemView.findViewById(R.id.conditionsText);
    }
}
}

Trails.java Trails.java

public class Trails {
public String name;
public double lat;   // Object fields
public double lon;
public String temp;
public String weather;
public static String conditions;


Trails(double lat, double lon, String name, String temp, String weather, String conditions){ // construcor
    this.lat = lat;
    this.lon = lon;
    this.name = name;
    this.temp = temp;
    this.weather = weather;
    this.conditions = conditions;
}
}

This is the logcat for the whole app running 这是整个应用程序运行的日志

03-16 10:32:48.877 20535-20535/com.example.android.cycleuk D/Lat: 52.1981981981982
03-16 10:32:48.877 20535-20535/com.example.android.cycleuk D/Lon: -2.2341297062250933
03-16 10:33:19.859 20535-20542/com.example.android.cycleuk W/art: Suspending all threads took: 10.141ms
03-16 10:33:19.956 20535-20535/com.example.android.cycleuk D/Hello: Adapter
03-16 10:33:20.023 20535-20535/com.example.android.cycleuk D/Hello: 4
03-16 10:33:20.023 20535-20535/com.example.android.cycleuk D/Hello: 4
03-16 10:33:20.069 20535-20535/com.example.android.cycleuk D/Lat: 52.1981981981982
03-16 10:33:20.069 20535-20535/com.example.android.cycleuk D/Lon: -2.2341297062250933

Bind your adapter with recycleview.. 将适配器与recycleview绑定。

ArrayList<Trails> finalData = getTrails();
Adapter adapter = new Adapter(this, finalData);
rvItem.setAdapter(adapter)

I think you have to change your Adapter class slightly.First you have to add Adapter to your recyclerView.Please be sure that recyclerView initialised with layout manger and not null. 我认为您必须稍微更改Adapter类。首先必须将Adapter添加到您的recyclerView中。请确保recyclerView使用布局管理器初始化且不为null。

Adapter adapter = new Adapter(this);
rvItem.setAdapter(adapter);

Here our Adapter class implementation.You have to create your List inside Adapter class. 这是我们的Adapter类的实现。您必须在Adapter类中创建List。

public class Adapter {

ArrayList<Trails> finalData;
Context context;

public Adapter(Context context){
     this.context = context;
     finalData = new ArrayList<>();
}

.....

....

public void addItem(Trails data){
    finalData.add(data);
    notifyDataSetChanged(); // Note this method is important because it will let adapter know size of list changed and render the list
}

}

In your fragment or Activity class add that method 在您的片段或活动类中添加该方法

Adapter adapter = new Adapter(this);
rvItem.setAdapter(adapter);

/// here your methods what ever you want

dataList = getTrails();
for(Trails trails: dataList){
    adapter.addItem(trails);
}

I hope this will help you. 我希望这能帮到您。

I think your getTrails method always return size 0 list that why you never get anything in recyclerview. All code is working fine . just check your code that you get any data in your list before setting it into recyclerview.



public static ArrayList<Trails> getTrails() {
    Log.d("trails", "Cycle trails running");
    ArrayList<Trails> trailList = new ArrayList<>();
    Trails t1 = new Trails(51.71, -3.36, "Bike Park Wales", "", "", "");
    Trails t2 = new Trails(51.66, -3.35, "Mountain Ash", "", "", "");
    Trails t3 = new Trails(50.50, -4.17, "FlyUp Downhill", "", "", "");
    trailList.add(t1);
    trailList.add(t2);
    trailList.add(t3);


    final ArrayList<Trails> localTrails = new ArrayList<>();
    for (final Trails trail : trailList) {
        Log.d("List running", "Local trail list");
        if (trail.lat > LAT_MIN && trail.lat < LAT_MAX && trail.lon > LON_MIN && trail.lon < LON_MAX) {
            localTrails.add(trail);
            Log.d("Calc", "Run code");


            final RequestBuilder weather = new RequestBuilder();

            final Request request = new Request();
            request.setLat(String.valueOf(trail.lat));
            Log.d("Lat used", String.valueOf(trail.lat));
            Log.d("Actual Lat", request.getLat());
            request.setLng(String.valueOf(trail.lon));
            Log.d("Lon used", String.valueOf(trail.lon));
            request.setUnits(Request.Units.UK);
            request.setLanguage(Request.Language.ENGLISH);
            request.addExcludeBlock(Request.Block.CURRENTLY);
            request.removeExcludeBlock(Request.Block.CURRENTLY);


            weather.getWeather(request, new Callback<WeatherResponse>() {
                @Override
                public void success(WeatherResponse weatherResponse, Response response) {
                    Log.d("Weather", "We have weather!");
                    Log.d("Location", weatherResponse.getTimezone());
                    trail.temp = String.valueOf(weatherResponse.getCurrently().getTemperature());
                    Log.d("Temperature", trail.temp);
                    trail.weather = weatherResponse.getCurrently().getIcon();
                }

                @Override
                public void failure(RetrofitError retrofitError) {
                    Log.d("Error while calling: ", "Weather");
                }


            });
        } else {
            Log.d("Too far", "Trails too far" + trail.name);
        }
    }
    return localTrails;
}

Your weather.getWeather() is not synchronous right?, this may cause your localTrails is always empty. 您的weather.getWeather()不同步吗?,这可能导致您的localTrails始终为空。 And maybe you can try to put this code localTrails.add(trail) inside success method of your synchronous call. 也许您可以尝试将这段代码localTrails.add(trail)放入同步调用的success方法内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的 RecyclerView Adapter 上的 onCreateView 没有被调用? - Why onCreateView on my RecyclerView Adapter is not called? 为什么我的 RecyclerView 不显示我的适配器项目? - Why isn't my RecyclerView displaying my adapter items? 为什么在不通知适配器的情况下更新了RecyclerView? - Why my RecyclerView updated while I don't notify the adapter? 为什么 ViewPager2 的 RecyclerView 适配器? - Why RecyclerView adapter for ViewPager2? 为什么实时数据库无法在我的recyclerview中工作 - why realtime database can not work in my recyclerview 为什么我的方法在我的 API 中有效,但在测试 class 中无效? - Why does my method work in my API, but not in a test class? 不同片段中的不同 recyclerview 可以使用相同的 Recyclerview 适配器类吗? 这是好方法吗? 为什么? - Different recyclerview in different fragment can use same Recyclerview adapter class ? It is good approach? Why? 为什么我的班在Java HashSet中不能正常工作? - Why does my class not work properly in a Java HashSet? 为什么我的setOnKeyListener()不起作用? - Why my setOnKeyListener() does not work? RecyclerView Adapter 附加跳过布局,为什么? - RecyclerView Adapter Attached Skipping Layout, why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM