Reputation: 1116
I'm trying to insert into ListAdapter my parsed JSON. I would like to understand if i'm getting into errors using a wring way and/or exist a rigth way to do it.
Here code to parse 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();
Here Result.java class:
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);
}
}
the parameter sens_resp it's a wrong parameter on ListAdapter. I thing I'm wronging how to pass between two Activity my parsed Gson. Could anyone help me to find errors and solve it? thanks in advance!
Upvotes: 0
Views: 43
Reputation: 4296
I see a couple of problems. Firstly, when you add the extra to the intent you add an ArrayList. Doing this means that the list is serialized into the intent. To get the list back in Result.java, you must use extras.getSerializableExtra() not extras.getString(). Secondly, when data is passed into SimpleAdapter it is a List of Map (not a String as you have it now), where the map contains the data for each row in the list. As a result you may need to convert the list (of Sensor) you passed via the intent into a list of maps.
Upvotes: 1