将json数组数据填充到android动态微调器中

时间:2016-08-25 10:21:17

标签: java android arrays json android-spinner

我对Android很新,我只用了两个月左右,所以请好好=)因为String []项目需要,我在字符串结果中收到错误填充数组适配器适配器。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select_class);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    /**dropdown start**/
    populatedata();
    spinnercall(result);
    /**dropdown end**/
}

private void spinnercall(result) {

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    //String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };
    String items = result;

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

    dynamicSpinner.setAdapter(adapter);

    dynamicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    });

}

private String populatedata() {
    try{
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        String userid =pref.getString("userid", "null");

        String link="selectclass.php";
        String data  = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(userid, "UTF-8");

        URL url = new URL(link);
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

        wr.write( data );
        wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
            break;
        }

        result = sb.toString();
        return result;
    }
    catch(Exception e){
        String errorno;
        errorno = ("Exception: " + e.getMessage());
        Toast.makeText(getApplicationContext(), errorno, Toast.LENGTH_SHORT).show();
    }

}

这是我的selectclass.php代码

$sql = "SELECT subejct_id, subject_name FROM class_schedule where subject_lec = '$id'";
$res = $conn->query($sql);
$result = array();

if ($res->num_rows > 0) {
    // output data of each row
    while($row = $res->fetch_array()){

      array_push($result, array('subject_id'=>$row[0], 'subject_name'=>$row[1]));

      echo json_encode(array("result"=>$result));
    }  
} else {
    echo "fail";
}

更清楚问题解释,我遇到的问题是

// Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
            break;
        }
    result = sb.toString();
    return result;
}

//String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };
    String items = result;

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

虽然//完美运行但我不想要硬编码阵列。

2 个答案:

答案 0 :(得分:1)

假设你的json看起来像这样:

[{"subject_id":"123","subject_name":"123Name"},{"subject_id":"123","subject_name":"123Name"}]

您可以使用以下代码将其解析为数组:

Gson gson = new Gson();
Subject[] items = gson.fromJson(jsonString, Subject[].class);

借助此对象类的帮助:

class Subject {
    public String subject_id = "";
    public String subject_name = "";
}

这不会直接与ArrayAdapter一起使用,您将需要一个自定义适配器来仅提取您想要的值,或者创建一个只包含subject_name值的新数组。

正如其他评论中所提到的,使用库来进行REST调用将简化代码并使其更具弹性。以下是使用Volley的示例:

String url = "http://address/path";
RequestQueue queue = Volley.newRequestQueue(appContext);

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
              new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {

                      Log.d("TAG", "success, parse your json here: " + response);
                      // Populate your ArrayList
                      // notify adapter of the dataset change
                  }
              }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

 queue.add(stringRequest);

更新(添加异步http库列表):

Volley来自Google

Retrofit是Square提供的社区广告

Android Aysnc - 来自James Smith的开源产品

答案 1 :(得分:0)

我解决了使用json对象解码器

try{
            JSONObject person = new JSONObject(result);
            JSONArray jsonMainNode = person.getJSONArray("result");
            final int n = jsonMainNode.length();

            //List<Map<String,String>> classList = new ArrayList<Map<String,String>>();
            final ArrayList<HashMap> classList = new ArrayList<>();
            String[] spinnerArray = new String[n];
            HashMap<String,String> spinnerMap = new HashMap<>();

            for(int i = 0; i< n; i++){
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                String schedule_id = jsonChildNode.getString("schedule_id");
                String subject_name = jsonChildNode.getString("subject_name");

                spinnerMap.put(schedule_id, subject_name);
                classList.add(spinnerMap);

                String total = "Class Section : "+schedule_id+" "+subject_name;
                spinnerArray[i] = total;
            }

            Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, spinnerArray);
            dynamicSpinner.setAdapter(adapter);

            dynamicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String classid = classList.get(position);
                    Log.v("item", (String) parent.getItemAtPosition(position));
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub
                }
            });
        }
        catch(JSONException e){
            Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
        }