如何从json获取数据到微调器?

时间:2017-01-04 11:55:55

标签: java android android-volley

在SearchFormFragment类中有spinner,我想从json.So获取数据,如何在spinner中获取数据? 并给出建议在旋转器中从json设置数据的不同方法。

FormType.java

//POJO class
public Class FormType {

private String fid;
private String formType;

public String getFid() {
    return fid;
}

public void setFid(String fid) {
    this.fid = fid;
}

public String getFormType() {
    return formType;
}

public void setFormType(String formType) {
    this.formType = formType;
}
}

SearchFormFragment.java

import android.app.DownloadManager;
import android.app.LoaderManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.ApplicationController;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.error.AuthFailureError;
import com.android.volley.error.VolleyError;
import com.android.volley.request.StringRequest;
import com.example.pc.formfillingapp.R;
import com.google.gson.JsonObject;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import MainPages.Utils.Constants;
import MainPages.Utils.TinyDB;

/**
 * Created by PC on 29-12-2016.
 */

public class SearchFormFragment extends Fragment implements View.OnClickListener {

    ArrayList<FormType> formTypes = new ArrayList<FormType>();
    ArrayList<String> formName = new ArrayList<String>();

    Spinner spinner1;
    Toolbar toolbar;
    View view;
    FragmentActivity fragmentActivity;
    AppCompatActivity appCompatActivity;
    TinyDB tinyDB;

    public SearchFormFragment() {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.spinner, container, false);
        fragmentActivity = getActivity();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.v("onActivtyCreated", "inside it");
        super.onActivityCreated(savedInstanceState);
        tinyDB = new TinyDB(getActivity());

        //ToolBar for {NavigationView}
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        appCompatActivity = (AppCompatActivity) getActivity();
        appCompatActivity.setSupportActionBar(toolbar);
        appCompatActivity.getSupportActionBar().setTitle(R.string.app_name);

        spinner1 = (Spinner) view.findViewById(R.id.spinner_category_view1);

        getDataFromApi();
        Log.v("onAcitvityCreated", "endof it");
    }

    public void getDataFromApi() {
        MainActivity.showLoader(getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
               "JSON URL", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("Response", "response from type " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    String message = jsonObject.getString("message");
                    JSONObject list = jsonObject.getJSONObject("list");
                    boolean status = jsonObject.getBoolean("status");
                    JSONArray data = list.getJSONArray("data");

                    if (status == true){
                        if (data != null) {
                            for (int i = 0; i < data.length(); i++) {

                                FormType form = new FormType();

                                JSONObject currentData = data.getJSONObject(i);
                                String fid = currentData.getString("fid");
                                String formType = currentData.getString("form_type");

                                form.setFid(fid);
                                form.setFormType(formType);
                                Log.e("FormType","type....");
                                formTypes.add(form);
                                formName.add(formType);
                                Log.e("Response","adding data...");
                            }
                            MainActivity.hideLoader();
                        }
                    }
                    spinner1.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, formName));
                    Log.e("Response","adding dataadapter");
                    MainActivity.hideLoader();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("Response","exception");
                    MainActivity.hideLoader();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    String errorJson = String.valueOf(error.networkResponse);
                    JSONObject jsonObject = new JSONObject(errorJson);
                    String errorMessage = jsonObject.getString("error");

                    Toast.makeText(getContext(),errorMessage , Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), getResources().getString(R.string.exception) , Toast.LENGTH_LONG).show();
                }
                MainActivity.hideLoader();
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };
        ApplicationController.getInstance().addToRequestQueue(stringRequest);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        Log.v("onClick", "inside");

        Log.v("onClick", "endof it");
    }
}

spinner.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:id="@+id/spinner_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="@dimen/activity_horizontal_margin">

        <TextView
            android:id="@+id/text_view1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/simple_value"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:text="@string/spinner_category_type" />

        <Spinner
            android:id="@+id/spinner_category_view1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/simple_value" />

    </LinearLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

当您从JSON获取数据时,您需要将此数据放在任何Arraylist中。然后将此arraylist分配给您的适配器。并在您的微调器中分配此适配器,如下所示..

{{1}}