下载没有数组中任何对象的JSON数组,并添加到autocompletetextview

时间:2016-07-02 17:23:46

标签: java android json

我正在开发一个从api下载一系列字符串的应用程序,然后将它们放在一个数组中,以便可以从自动完成的textview字段调用它们。我无法下载阵列。该数组只是["String", "String" ... etc]我使用ASyncTask来调用api并下载json,但我无法弄清楚如何正确下载它...感谢您的时间......

MapFragment.java

package com.horizonservers.horizon;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
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.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.jar.Attributes;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MapFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MapFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MapFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView test2;
    AutoCompleteTextView textView;
    ArrayList<String> Maps = new ArrayList<String>();

    private OnFragmentInteractionListener mListener;

    public MapFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MapFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MapFragment newInstance(String param1, String param2) {
        MapFragment fragment = new MapFragment();
        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);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_map, container, false);

        new PostDataTask().execute("https://www.horizonservers.net/api/mentions/maps?q=surf_&c=map");


        textView = (AutoCompleteTextView) v.findViewById(R.id.map_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, Maps);
        textView.setThreshold(3);
        textView.setAdapter(adapter);
        test2 = (TextView) v.findViewById(R.id.testMap);

        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);
    }

    class PostDataTask extends AsyncTask<String, Void, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params) {

            try {
                return postData(params[0]);
            } catch (IOException ex) {
                return "Network error !";
            } catch (JSONException ex) {
                return "Data Invalid !";
            }
        }

        @Override
        protected void onPostExecute(String result) {

            try {


              JSONArray jsonArray = new JSONArray(result);
                for(int i = 0; i < jsonArray.length(); i++){
                    final JSONArray e = jsonArray.getJSONArray(i);
                    String name = e.toString();
                    Maps.add(name);
                }

                test2.setText(Maps.toString());





                Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();


            } catch (JSONException e) {
                Log.e("Horizon", "unexpected JSON exception", e);
               // Toast.makeText(getActivity(), "Failed to load maps.", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(result);


            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }


        private String postData(String urlPath) throws IOException, JSONException {

            StringBuilder result = new StringBuilder();
            BufferedWriter bufferedWriter = null;
            BufferedReader bufferedReader = null;

            try {
                //Create data to send to server
                JSONObject dataToSend = new JSONObject();
                //Initialize and config request, then connect to server.
                URL url = new URL(urlPath);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(10000 /* milliseconds */);
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);  //enable output (body data)
                urlConnection.setRequestProperty("Content-Type", "application/json");// set header
                urlConnection.connect();

                //Write data into server
                OutputStream outputStream = urlConnection.getOutputStream();
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                bufferedWriter.write(dataToSend.toString());
                bufferedWriter.flush();

                //Read data response from server
                InputStream inputStream = urlConnection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line).append("&");
                }
            } finally {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            }

            return result.toString();

        }

    }



}

实际上调用JSON的部分是OnPostExecute,它是

 @Override
        protected void onPostExecute(String result) {

            try {


              JSONArray jsonArray = new JSONArray(result);
                for(int i = 0; i < jsonArray.length(); i++){
                    final JSONArray e = jsonArray.getJSONArray(i);
                    String name = e.toString();
                    Maps.add(name);
                }

                test2.setText(Maps.toString());





                Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();


            } catch (JSONException e) {
                Log.e("Horizon", "unexpected JSON exception", e);
               // Toast.makeText(getActivity(), "Failed to load maps.", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(result);


            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }

另外应该注意的是,这个数组没有对象,只有字符串,我想我遇到的问题是设置为textview 现在只是为了让我看到它有下载。我尝试将其转换为字符串,但我得到org.json.JSONException: Value Network of type java.lang.String cannot be converted to JSONArray。再次感谢您的时间。

1 个答案:

答案 0 :(得分:0)

使用此功能连接到网络服务器

private HttpURLConnection connection;
private URL url = null; 
public void connect()
{
    try {
        url = new URL(SERVER_ADDRESS);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");
        connection.connect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

然后使用此函数从那里获取字符串

public String getStringFromServer()  {
    InputStream input;
    StringBuilder result;
    String line,JSONRESPOND="";
    BufferedReader reader;

    try {
        input = this.connection.getInputStream();
        reader= new BufferedReader(new InputStreamReader(input));
        result= new StringBuilder();
        while ((line=reader.readLine())!=null)
        {
            result.append(line);
        }
        JSONRESPOND = ""+result.toString();
    } catch (IOException e) {
       return null;
    }

    return JSONRESPOND;
}

终于搞定了

connect();
String yourJSON = getStringFromServer();
JSONArray yourArray = new JSONArray(yourJSON);

您可以使用此代码段解析此数组

ArrayList<String> yourParsedStrings = new ArrayList<>();
for(int i =0; i<yourArray.length();i++){
 yourParsedStrings.add(yourArray.getString(i));
}