将API数据保存在一个数组中

时间:2018-06-25 13:11:54

标签: java android rest api

我正在开发一个基本的测验应用程序,但卡在API部分中。在API中,我们有一个“问题”,“选择”,“选择”和“正确”关键字。我想将“ question”和“ choice”关键字的值保留在一个数组或其他数组中,添加与问题编号一样长的片段,还将这些问题和选择添加至片段活动中。我分享了一个样例屏幕截图,该样机应为什么样。 Layour并不重要,我只需要Java代码。如果您能帮助我,我将不胜感激。谢谢。

Click for screenshot

这是我的MainActivity.java

package myusarisoy.quizmasters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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.JsonArrayRequest;
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 {
Frag frag = new Frag();
ViewPager vp;
RequestQueue requestQueue;
String[] abc, cba;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    vp = findViewById(R.id.vp);
    requestQueue = Volley.newRequestQueue(this);

    FragmentPagerAdapter fpa = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(final int position) {
            String url = "https://private-anon-a98702efdd-quizmasters.apiary-mock.com/questions";
            final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            try {
                                for(int i = 0; i < response.length(); i++) {
                                    JSONObject jrResponse = response.getJSONObject(i);
                                    String question = jrResponse.getString("question");
                                    abc = new String[question.length()];
                                    JSONArray choiceArray = jrResponse.getJSONArray("choices");

                                    for(int j = 0; j < choiceArray.length(); j++) {
                                        JSONObject currentChoice = choiceArray.getJSONObject(j);
                                        String choice = currentChoice.getString("choice");
                                        cba = new String[choice.length()];

                                        String q = abc[i];
                                        String c = cba[j];

                                        Bundle b = new Bundle() ;
                                        b.putString("tvQ", q);
                                        b.putString("tvC", c);

                                        frag.setArguments(b);

                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("myusarisoy", "Error...");
                }
            });
            requestQueue.add(request);

            return frag;
        }

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

    // Set PagerAdapter to ViewPager
    vp.setAdapter(fpa);
}

 public void importantTask() {
    Log.e("myusarisoy", "Important Task...");
 }
}

这是我的activity_main.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">

<android.support.v4.view.ViewPager
    android:id="@+id/vp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

</LinearLayout>

这是我的Frag.java

package myusarisoy.quizmasters;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Frag extends Fragment {
View root;
TextView tvQuestion, tvChoices;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable         ViewGroup container, @Nullable Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.activity_frag, container, false);
    tvQuestion = root.findViewById(R.id.tvq);
    tvChoices = root.findViewById(R.id.tvc);

    String tvQ = getArguments().getString("tvQ");
    String tvC = getArguments().getString("tvC");

    tvQuestion.setText(tvQ);
    tvChoices.setText(tvC);

    MainActivity ma = (MainActivity) getActivity();
    ma.importantTask();

    return root;
}
}

这是我的activity_frag.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=".Frag">

<TextView
    android:layout_marginTop="200sp"
    android:id="@+id/tvq"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="20sp"
    android:textColor="#000000"
    android:textStyle="bold"
    android:text="Question"
    android:gravity="center"/>

<TextView
    android:layout_marginTop="50sp"
    android:id="@+id/tvc"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="17sp"
    android:textColor="#000000"
    android:textStyle="bold"
    android:text="Answers"
    android:gravity="center"/>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

我想你有点倒退了。

您需要获取问题,然后构建片段列表,然后构建适配器。

看起来像这样

// directly in onCreate 
final List<Frag> frags = new ArrayList<>();
String url = "https://private-anon-a98702efdd-quizmasters.apiary-mock.com/questions";
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        frags.clear();
        try {
            for(int i = 0; i < response.length(); i++) {
                JSONObject jrResponse = response.getJSONObject(i);
                String question = jrResponse.getString("question");
                abc = new String[question.length()];
                JSONArray choiceArray = jrResponse.getJSONArray("choices");
                // TODO: parse the JSON to get arguments 

                Frag f = new Frag();
                f.setArguments(...);  // set the arguments
                frags.add(f); // store for the adapter 
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        // Create a PagerAdapter here using list of Fragments 

        // set adapter to viewpager here 

    } // end of onResponse 

然后,例如getItem,您将返回frags.get(position)