gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:34:14 26 4
gpt4 key购买 nike

我对 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);

虽然//工作得很好,但我不想要硬编码数组。

最佳答案

假设你的 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 提供的开源产品

关于java - 将 json 数组数据填充到 android 动态微调器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com