为什么json数据不能访问viewpager?

fnatzsnv  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(331)

我想在pageradapter for slider中使用volley json获取图像,但问题是使用json获取的数据在构造函数之前是到达的,而不是重新处理到instanceItem方法。
这是我的xml文件。

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

    <androidx.viewpager.widget.ViewPager
        android:layout_width="match_parent"
        android:layout_height="@dimen/_200sdp"
        android:id="@+id/view_pager">

    </androidx.viewpager.widget.ViewPager>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="@dimen/_50sdp"
        android:text="@string/app_name"
        android:textSize="@dimen/_30sdp"
        android:textColor="@color/colorPrimaryDark"
        android:id="@+id/txt"/>
</LinearLayout>

主活动.java

package com.example.sliderwithvolleyjson;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;
    String slider_url="Here is my API";
    ArrayList<String> image=new ArrayList<>();
    RequestQueue queue;
    Slider_Adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        queue= Volley.newRequestQueue(getApplicationContext());
        viewPager=findViewById(R.id.view_pager);
        getImageByJson();
        viewPager.setAdapter(adapter);

    }

    public void getImageByJson(){

        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray array=response.getJSONArray("slider");

                    for (int i=0;i<array.length();i++){

                        JSONArray jsonData=array.getJSONArray(i);

                        image.add(jsonData.getString(1));

                    }

                    String[] imageUrls=new String[image.size()];
                    imageUrls=image.toArray(imageUrls);

                    for (String s : imageUrls){
                       Log.d("String",s);
                    }
                    adapter=new Slider_Adapter(getApplicationContext(),imageUrls);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
                    Log.d("ath",String.valueOf(e));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
                Log.d("Error",String.valueOf(error));
            }
        });

        queue.add(request);
    }
}

我使用mainactivity类中的api从服务器获取图像。我使用volley json来实现它。然后我使用viewpager将这些图像传递给pageradapter类。
pageradapter类

package com.example.sliderwithvolleyjson;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.squareup.picasso.Picasso;

public class Slider_Adapter extends PagerAdapter {

    LayoutInflater inflater;
    private Context context;
    private String[] imageurls;

    public Slider_Adapter(Context context, String[] imageurls) {
        this.context = context;
        this.imageurls = imageurls;
        Toast.makeText(context, String.valueOf(imageurls[1]), Toast.LENGTH_SHORT).show();
    }

    @Override
    public int getCount() {
        return imageurls.length;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view=inflater.inflate(R.layout.activity_main,container);

        ImageView imageView=new ImageView(container);
        TextView textView=view.findViewById(R.id.txt);
        textView.setText(String.valueOf(imageurls.length));
        Picasso.with(context).load(imageurls[position]).fit().into(imageView);
        ViewPager pager=(ViewPager)container;
        pager.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View)object);
    }
}

直到构造函数(我尝试使用toast消息)才到达图像,但是在instanceItem方法和其他函数中找不到图像/数据。
提前谢谢。

ar7v8xwq

ar7v8xwq1#

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;
    String slider_url="Here is my API";
    ArrayList<String> image=new ArrayList<>();
    RequestQueue queue;
    Slider_Adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        queue= Volley.newRequestQueue(getApplicationContext());
        viewPager=findViewById(R.id.view_pager);
        getImageByJson();

    }

    public void getImageByJson(){

        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray array=response.getJSONArray("slider");

                    for (int i=0;i<array.length();i++){

                        JSONArray jsonData=array.getJSONArray(i);

                        image.add(jsonData.getString(1));

                    }

                    String[] imageUrls=new String[image.size()];
                    imageUrls=image.toArray(imageUrls);

                    for (String s : imageUrls){
                       Log.d("String",s);
                    }
                    adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
                    viewPager.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
                    Log.d("ath",String.valueOf(e));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
                Log.d("Error",String.valueOf(error));
            }
        });

        queue.add(request);
    }
}
xxe27gdn

xxe27gdn2#

for (String s : imageUrls){
   Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);

在你的 onResponse 方法,添加此代码。

viewPager.setAdapter(adapter);

并将其从oncreate中删除,因为它不是必需的。

相关问题