如何将API中的JSON数据提取到ListView中?

时间:2017-05-30 23:01:26

标签: android json api listview

因为我还有点开始进行更高级的android开发,所以我想了解更多有关API以及如何将JSON数据提取到ListView中的信息。

让我们说我希望能够搜索一个演员并作为回报获得他参与列表视图中显示的所有电影。我一直在看改造,但不确定它是否能完成我正在寻找的工作。

我会就此事采取任何相关信息。链接,片段,你的名字。

1 个答案:

答案 0 :(得分:1)

第1步:创建activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    >
    <ListView
        android:id="@+id/actorslist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:color="#ffffff"
        android:divider="@null"
        android:scrollbars="none"
      />
</RelativeLayout>

第2步:创建RequestSenderFiles

-first创建一个接口AsyncResponse.java

public interface AsyncResponse
        {
            void processFinish(Object output) throws JSONException;
        }

- 创建另一个文件RequestResponse.java

public class RequestResponse extends AsyncTask<String ,String,String>
    {

        Activity c;
        public AsyncResponse delegate = null;
        String req="";
        HashMap<String,String> params;
        boolean connect=true;
        int responseCode;
        String url;
        ProgressDialog Loader;
        public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod)
        {
            delegate = AsyncResponse;
            c=context;
            req=RequestMethod;
        }
        public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod, HashMap<String, String> postparam)
        {
            delegate = AsyncResponse;
            c=context;
            req=RequestMethod;
            params=postparam;
        }
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
          // your progressdialog your here
              Loader=new ProgressDialog(c);
                Loader.setMessage("Loading...");
                Loader.show();

        }
        @Override
        protected String doInBackground(String... params)
        {
            String json="";
            Log.i("REposnse",""+params[0]);
            url=params[0];
            if(req.equals("GET"))
            {
                json=Client(params[0]);
            }
            else
            {
                json=ClientPost(params[0]);
            }
            Log.i("REposnse", "" + json);

            return json;



        }
        @Override
        protected void onPostExecute(String av)
        {
            super.onPostExecute(av);
            if(connect)
            {
                try
                {
                    delegate.processFinish(av);
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    if ((this.Loader != null) && this.Loader.isShowing())
                    {
                        this.Loader.dismiss();
                    }
                }
                catch (final IllegalArgumentException e)
                {
                    // Handle or log or ignore
                }
                catch (final Exception e)
                {
                    // Handle or log or ignore
                }
                finally
                {
                    this.Loader = null;
                }
            }
            else
            {
                try
                {
                    if ((this.Loader != null) && this.Loader.isShowing())
                    {
                        this.Loader.dismiss();
                    }
                }
                catch (final IllegalArgumentException e)
                {
                    // Handle or log or ignore
                }
                catch (final Exception e)
                {
                    // Handle or log or ignore
                }
                finally
                {
                    this.Loader = null;
                }
                c.runOnUiThread(new Runnable()
                {
                    public void run()
                    {

                        if(req.equals("GET"))
                        {
                            RequestResponse requestget= RequestResponse(delegate, c);
                            requestget.execute(url);
                        }
                        else
                        {

                            RequestResponse requestpost = new RequestResponse(delegate, c, req, params);
                            requestpost.execute(url);
                        }
                    }
                });

            }
        }
        public String ClientPost(String url)
        {
            URL url1;
            String response = "";
            try
            {
                url1 = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                conn.setReadTimeout(1500000);
                conn.setConnectTimeout(1500000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(params));
                writer.flush();
                writer.close();
                os.close();
                responseCode=conn.getResponseCode();
                Log.i("REposnse",""+responseCode);
                if(responseCode == HttpsURLConnection.HTTP_OK)
                {
                    String line;
                    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line=br.readLine()) != null)
                    {
                        response+=line;
                    }
                }
                else
                {
                    connect=false;
                    response="";
                }
            }
            catch (Exception e)
            {
                connect=false;

            }

            return response;
        }
        public String Client(String url)
        {
            String result = "";
            try
            {
                URL apiurl =null;
                HttpURLConnection conn;
                String line;
                BufferedReader rd;
                apiurl = new URL(url);
                conn = (HttpURLConnection) apiurl.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(1500000);
                conn.setConnectTimeout(1500000);

                responseCode=conn.getResponseCode();
                Log.i("REposnse",""+responseCode);
                if(responseCode==HttpsURLConnection.HTTP_OK)
                {
                    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = rd.readLine()) != null)
                    {
                        result += line;
                    }
                    rd.close();

                }
                else
                {

                    connect=false;
                }

            }
            catch (Exception e)
            {
                connect=false;

            }
            return result;
        }
        private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
        {
            StringBuilder result = new StringBuilder();
            boolean first = true;
            for(Map.Entry<String, String> entry : params.entrySet())
            {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            Log.i("REposnse",""+params);
            return result.toString();
        }
    }

第3步:创建Activity MainActivity.java

public class MainActivity extends Activity
{
     ListView   list;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        try
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main.xml);
            list = (ListView) findViewById(R.id.actorslist);
            request();       
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    public void request()
    {
     // for POST Request
       //suppose you need to send some data to server to fetch the response from server
      HashMap<String,String> data=new HashMap<String,String>();
      data.put("id","12");
        try
        {
            RequestResponse crr = new RequestResponse(new AsyncResponse()
            {
                @Override
                public void processFinish(Object output) throws JSONException
                {
                    output.toString();//your response
                    // for example you got the response like this
                    String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
                    fetchandapplydata(actors);

                }
            }, this,"POST",data);
            crr.execute(yourserversideurltofetchdata);
        }
        catch (Exception e)
        {
            e.printStacktrace();
        }

     // for GET Request
        try
                {
            RequestResponse crr = new RequestResponse(new AsyncResponse()
            {
                @Override
                public void processFinish(Object output) throws JSONException
                {
                     output.toString();//your response
                     // for example you got the response like this
                    String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
                    fetchandapplydata(actors);

                }
            }, this,"GET");
            crr.execute(yourserversideurltofetchdata);
        }
        catch (Exception e)
        {
            e.printStacktrace();
        }

     //Depend upon the request method use the code and comment the rest code. 

    }
    public void fetchandapplydata(String data)
    {
        JSONObject object=new JSONObject(data);
        JSONArray actors=object.getJSONArray("data");
        ArrayList<HashMap<String,String>> actorsdata=new ArrayList<HashMap<String, String>>();
        for(int i=0;i<actors.length();i++)
        {
            JSONObject actor=actors.getJSONObject(i);
            HashMap<String,String> actorsnames=new HashMap<String,String>();
            actorsnames.put("name",actor.getString("actorname"));
            actorsdata.add(actorsnames);
        }
        ActorAdapter actoradapter = new ActorAdapter(this, actorsdata);
        list.setAdapter(actoradapter);
    }
}

第4步:创建ActorAdapter.java

public class ActorAdapter extends BaseAdapter
{

    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    private Activity activity;
    public ActorAdapter(Activity a, ArrayList<HashMap<String, String>> d) 
    {
        activity = a;
        data=d;
        inflater = (LayoutInflater)Ced_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }
    public int getCount()
    {
        return data.size();
    }
    public Object getItem(int position)
    {
        return position;
    }
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        try
        {
            View vi;
            vi = inflater.inflate(R.layout.actor_item, null);
            TextView name= (TextView) vi.findViewById(R.id.name);
            HashMap<String, String> actor = new HashMap<String, String>();
            actor = data.get(position);
            name.setText(actor.get("name"));
            return vi;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

第5步:创建actor_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main">

    <TextView
        android:layout_width="wrap_parent"
        android:layout_height="wrap_parent"
        android:id="@+id/name" />

</RelativeLayout>

对于您的问题,这是一步一步的过程,如果您有任何疑问,请随时向我们提出。