Spinner无法填充片段

时间:2018-02-16 07:52:20

标签: java android android-fragments

希望有人可以帮助我。由于某种原因让我失望,UI中的微调器没有填充任何数据。在8小时阅读Stack Overflow问题和答案之后,我已经搜索了高低,并尝试了无数的修复,但没有运气。来自服务器的烘焙返回数据返回正常,但该数据未被转发到微调器中。

我没有得到任何编译时间或运行时错误,所以要么我没有正确处理JSON,要么我重写在某处分配给微调器的内容,不确定。

查询的代码是

<?php

include 'Dbconf.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 // Get list of current events
 //$qry = "SELECT EventID,EventName,EventDate FROM skid_event WHERE IsOpen ='1'";
 $qry = "SELECT EventID,EventName,EventDate FROM skid_event";
 $result=mysqli_query($con,$qry);

 if ($result=mysqli_query($con,$qry))
    {
      $rowcount=mysqli_num_rows($result);
      if ($rowcount > 0)
      {
            $rows = array();
            while($r = mysqli_fetch_assoc($result)) {
            $rows[] = $r;
      }
      print json_encode($rows);


          //$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
          //echo json_encode($row);
          mysqli_free_result($result);
          mysqli_close($con);
          exit();
      }
      else
      {
          echo "Fail";
      }
    }       
    else
    {    
        echo 'Failed'; 
    }
    mysqli_close($con);

?>

它产生以下格式化的JSON结果,这是我期望的

[{“EventID”:“1”,“EventName”:“Burnout King”,“EventDate”:“2017-04-14”},{“EventID”:“2”,“EventName”:“Gazzanats WA”, “EVENTDATE”: “2018年2月23日”}]

以上是我在应用程序中响应服务器响应时的情况。

片段代码如下所示

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
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;

public class FindEventFragment extends Fragment{

    public static final String TAG = "FindEventFragment";
    private VolleyHelper mInstance;
    private ArrayList<String> eventList;
    private JSONArray result;
    private Spinner eventNameSpinner;
    private TextView eventDate;         
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;    
    private OnFragmentInteractionListener mListener;    
    public FindEventFragment() {
        // Required empty public constructor
    }


    public static FindEventFragment newInstance(String param1, String param2) {
        FindEventFragment fragment = new FindEventFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    public void onStart() {
        super.onStart();
        // Instantiate the RequestQueue from VolleyHelper
        mInstance = VolleyHelper.getInstance(getActivity().getApplicationContext());
        // API
        connectApi();
    }

    @Override
    public void onStop () {
        super.onStop();
        if (mInstance.getRequestQueue() != null) {
            mInstance.getRequestQueue().cancelAll(TAG);
        }
    }

    private void connectApi() {
        String url = "http://gblakes.ddns.net/get_events.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {                               
                        Toast.makeText(getActivity().getApplicationContext(), ServerResponse, Toast.LENGTH_LONG).show();
                        JSONObject j = null;
                        try {
                            j = new JSONObject(ServerResponse);
                            result = j.getJSONArray("EventName");
                            eventDetails(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        Toast.makeText(getActivity().getApplicationContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                });

        if (mInstance != null) {
            // Add a request to your RequestQueue.
            mInstance.addToRequestQueue(stringRequest);
            // Start the queue
            mInstance.getRequestQueue().start();
        }
    }

    private void eventDetails(JSONArray j) {
        for (int i = 0; i < j.length(); i++) {
            try {
                JSONObject json = j.getJSONObject(i);
                eventList.add(json.getString("EventName"));
            } catch (JSONException e) {
                //e.printStackTrace();
                Log.d(TAG, e.toString());
            }
        }
        /**check this it could be wrong since Im trying to set an adapter that contains no data yet*/
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, eventList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        eventNameSpinner.setAdapter(dataAdapter);

        eventNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                //Setting the value to textview for a selected item
                eventDate.setText(getEventDate(position));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                eventDate.setText("test me");
            }
        });
        // arrayList.add(0,"Select Event");
        //eventNameSpinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, eventList));
    }

    private String getEventID(int position) {
        String eventID = "";
        try {
            //Getting object of given index
            JSONObject json = result.getJSONObject(position);
            //Fetching name from that object
            eventID = json.getString("EventID");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Returning the name
        return eventID;
    }

    private String getEventDate(int position){
        String eventDate="";
        try {
            JSONObject json = result.getJSONObject(position);
            eventDate = json.getString("EventDate");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return eventDate;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_find_event,container,false);
        eventNameSpinner = (Spinner) v.findViewById(R.id.spinEventPicker);
        eventNameSpinner = new Spinner(getActivity().getApplicationContext());

        eventDate = (TextView) v.findViewById(R.id.textEventDate);
        eventDate.setText("test me");
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

片段xml看起来像这样

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:id="@+id/textEventName">
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinEventPicker"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textEventDate"
        android:layout_marginTop="49dp"
        android:layout_below="@+id/spinEventPicker"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

如果有人能够指出我做错了什么,并且可能提出的解决办法很棒。

TIA

1 个答案:

答案 0 :(得分:0)

你好像是在实例化你的Spinner两次,首先(正确的方式)引用布局,第二次创建一个全新的Spinner对象。

eventNameSpinner = (Spinner) v.findViewById(R.id.spinEventPicker);
eventNameSpinner = new Spinner(getActivity().getApplicationContext());

我相信如果您删除了这两行代码的第二行(在onCreateView中找到),它应该可以工作。

修改

似乎还需要对JSON的处理进行一些更改。首先,您需要更改ServerResponse String的使用。

try {
    result = new JSONArray(ServerResponse);
    eventDetails(result);
} catch (JSONException e) {
    e.printStackTrace();
}

然后你需要改变你访问数组的方式。

for (int i = 0; i < j.length(); i++) {
    try {
        JSONObject json = j.getJSONObject(i);
        eventList.add(json.getString("EventName") + json.getString("EventDate");
    } catch (JSONException e) {
        //e.printStackTrace();
        Log.d(TAG, e.toString());
    }
}

这应该可行。