我正在尝试将解析后的JSON插入ListAdapter中。我想了解一下我是否使用拧紧方法遇到错误和/或存在执行此操作的严格方法。
这里是解析GSon的代码:
URL url = new URL("http://10.203.134.146/cloud/api/sensor/" + reqUrl);
httpConn = (HttpURLConnection) url.openConnection(); // Open http connection to web server.
httpConn.setDoOutput(true);// Set http request method to put.
httpConn.setDoInput(true);
String responses = null;
httpConn.setDoOutput(false);
httpConn.setRequestMethod(REQUEST_METHOD_GET);
// httpConn.setRequestProperty("charset", "utf-8");
// httpConn.setConnectTimeout(1000);
// httpConn.setReadTimeout(1000);
// read the response
InputStream in = new BufferedInputStream(httpConn.getInputStream());
responses = convertStreamToString(in);
// JSONObject jsonOBJ = new JSONObject(responses);
Type listSensorType = new TypeToken<ArrayList<Sensor>>(){}.getType();
ArrayList<Sensor> sensors = new Gson().fromJson(responses, listSensorType);
Log.d("TAG", "ServerKey " +sensors);
Intent intent = new Intent(getApplicationContext(),
StoryResult.class);
intent.putExtra("key_to_display",sensors);
startActivity(intent);
finish();
这里Result.java类:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class StoryResult extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SensorList
ListView lv = findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
assert extras != null;
String sens_response =extras.getString("key_to_display");
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
StoryResult.this, sens_response,
R.layout.list_item, new String[]{"shipmentDate", "uid",
"lotId"}, new int[]{R.id.shipmentDate,
R.id.uid, R.id.lotId});
lv.setAdapter(adapter);
}
}
参数sens_resp,它是ListAdapter上的错误参数。我想我错了如何解析的Gson在两个Activity之间传递。 谁能帮助我发现错误并解决问题?预先感谢!
答案 0 :(得分:1)
我看到几个问题。首先,当您将多余的内容添加到意图中时,将添加一个ArrayList。这样做意味着将列表序列化为意图。要使列表返回到Result.java中,必须使用extras.getSerializableExtra()而不是extras.getString()。其次,当数据传递到SimpleAdapter时,它是一个Map列表(而不是现在的String),其中该Map包含列表中每一行的数据。因此,您可能需要将通过意图传递的(传感器)列表转换为地图列表。