创建JSON适配器和JSON请求Android

时间:2017-10-23 11:27:45

标签: json

我有以下2个类用于在Android Studio中创建JSON请求(请求本身和主类)。我想知道如何使用与我已有的格式类似的格式创建JSON适配器。

请求类如下:

import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

多线程解决方案,您仍然可以使用线程。 Asynctask是一个依赖于main的工作线程 处理同步

3种通用类型

  • 1 - 输入类型
  • 2 - 更新类型
  • 3 - 结果

异步 ​​- 异步,它不会阻止执行

public class JSONRequest extends AsyncTask<String, Void, JSONObject> {

    private JSONListener listener;

    public JSONRequest(JSONListener listener) {
        this.listener = listener;
    }

逻辑之肉

    protected JSONObject doInBackground(String... strings) {

        // receive url
        JSONObject result = null;
        try{
            URL url = new URL(strings[0]);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

HTTP CODE 404 - 未找到 400 - 糟糕的要求 500 - 服务器错误 200 - 好的

int code = connection.getResponseCode();
    if(code == HttpURLConnection.HTTP_OK){

        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String currentLine = "";

        while((currentLine = br.readLine()) != null){
            Log.d("JSON REQUEST", currentLine);
            sb.append(currentLine);
        }

        result = new JSONObject(sb.toString());

    }

}catch (Exception e){
    e.printStackTrace();
}
// do request
// return parsed result
return result;

}

从生命周期中重写 当另一方结束时,这将会发生

    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);
        listener.requestDone(jsonObject);
    }

    public interface JSONListener {

        void requestDone(JSONObject jsonObject);
    }
}

主要类看起来像这样:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements JSONRequest.JSONListener {

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

        JSONRequest request = new JSONRequest(this);
        request.execute("https://api.github.com");
    }

    public void requestDone(JSONObject jsonObject) {
        try{

            Toast.makeText(this, "VALUE: " + jsonObject.getString("current_user_url"), Toast.LENGTH_SHORT).show();
        } catch(JSONException je){
            je.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这样做的方法如下,还有两个类,一个用于适配器本身,另一个用于main方法:

适用于适配器:

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONAdapter extends BaseAdapter {

    private JSONArray data;
    private Activity activity;

    public JSONAdapter(JSONArray data, Activity activity){
        this.data = data;
        this.activity = activity;
    }

    public int getCount() {
        return data.length();
    }

    public Object getItem(int i) {

        try{
            return data.getJSONObject(i);
        }catch(JSONException jse){
            jse.printStackTrace();
        }

        return null;
    }

    public long getItemId(int i) {

        try{
            JSONObject object = data.getJSONObject(i);
            return object.getLong("id");
        }catch(JSONException jse){
            jse.printStackTrace();
        }
        return -1;
    }

    // returns the view of a single row

    public View getView(int i, View view, ViewGroup viewGroup) {

        if(view == null){
            view = activity.getLayoutInflater().inflate(R.layout.custom_row, null);
        }

        TextView studentName = (TextView)view.findViewById(R.id.textView);
        TextView studentGrade = (TextView)view.findViewById(R.id.textView2);

        try{

            JSONObject object = data.getJSONObject(i);
            studentName.setText(object.getString("name"));
            studentGrade.setText(object.getDouble("grade") + "");

        }catch(JSONException jse){
            jse.printStackTrace();
        }

        return view;
    }
}

主要方法:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;

public class MainActivity extends AppCompatActivity implements
        AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {

    private ListView listView;
    private Spinner spinner;
    private JSONArray data;

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

        Toast.makeText(this, getString(R.string.sample_toast), Toast.LENGTH_SHORT).show();

        listView = (ListView)findViewById(R.id.mylist);
        spinner = (Spinner)findViewById(R.id.spinner);

        // to load data to a collection view you need something called an Adapter
        // data -> adapter -> UI

        String[] source = {"Christian", "Fernanda", "Francisco"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                source);

        //listView.setAdapter(adapter);

        String source2 = "[" +
                "{'name': 'Gil', 'grade':32, 'id':141414}," +
                "{'name': 'Migue', 'grade':15, 'id':121212}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}," +
                "{'name': 'Chris', 'grade':15.2, 'id':131313}" +
                "]";

        try{

            data = new JSONArray(source2);
            JSONAdapter adapter2 = new JSONAdapter(data, this);
            listView.setAdapter(adapter2);
            spinner.setAdapter(adapter2);
            listView.setOnItemClickListener(this);
            spinner.setOnItemSelectedListener(this);
        }catch(JSONException jse){

            jse.printStackTrace();
        }
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        try {
            Toast.makeText(this, data.getJSONObject(i).getString("name"), Toast.LENGTH_SHORT).show();
        } catch(JSONException jse){
            jse.printStackTrace();

        }
    }

    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        //Toast.makeText(this, i + " : " + l, Toast.LENGTH_SHORT).show();
    }

    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}