i have create an android application on where the user can select the start and end point of the location.
This application will use the Google-Direction web service and make the HTTPRequest.
I will make this as short, I want to call the asynctask method in the JSONParser class from the main_activity.
The issue is, I don't know how to display the result in the main_activtiy method
here is the asynctask method
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONParser() {
}
public void getJSONFromUrl(final String url, final responseListener target) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection = null;
StringBuilder stringBuilder = new StringBuilder();
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = inputStreamReader.read(buff)) != -1) {
stringBuilder.append(buff, 0, read);
}
return stringBuilder.toString();
} catch (MalformedURLException localMalformedURLException) {
return "";
} catch (IOException localIOException) {
return "";
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
target.onResponseComplete(result);
}
}.execute();
}
here is how the main method is calling the method
new JSONParser().getJSONFromUrl(url, new responseListener() {
#Override
public void onResponseComplete(String response) {
try {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps");
for (int i = 0; i < step.length(); i++) {
HashMap<String,Object> row = new HashMap<String,Object>();
row.put("Distance", step.getJSONObject(i).getJSONObject("distance").getString("text"));
list.add(row);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
the issue right know is how i want to display the Arraylist List value and put it into the TextView call jarak
You can change your List to be
ArrayList<HashMap<String, String>>
as you are getting a string from
step.getJSONObject(i).getJSONObject("distance").getString("text")
To get it out you can use (assuming your textview is called jarak)
for(HashMap<String,String> map : list) {
for(Entry<String, String> entry : map.entrySet()) {
jarak.setText(entry.getKey() + ", " + entry.getValue());
}
}
Hope that helps
Related
I had wrote a code which use a parse to catch some data from a JSON file but i don't know what kind of structure is better between the sparse array or the array map for memorise these data ?
I had used a array map but I don't know if it's too wasted on so little data data.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, ValoriDiSueg> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The parse of these data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("weather"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new ValoriDiSueg( jsonPart.getString("main"), jsonPart.getString("description")));
//ArrayDati.put(i,new ValoriDiSueg("description : "+ jsonPart.getString("description")));
textViewProg.setText(textViewProg.getText()+"main : "+ ArrayDati.get(i).Main +"\n"+textViewProg.getText()+"description : "+ ArrayDati.get(i).Description );
}
} catch (Exception e ){
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
}
And I created a class:
public class ValoriDiSueg {
String Main;
String Description;
public ValoriDiSueg(String main, String description) {
this.Main = main;
this.Description = description;
}
}
any suggestions??
In simple:
If your key is int or long, you should use SparseArray, SparseLongArray as it will not boxing/un-boxing the key value when operates. Also, it provides similar classes for int/long values as long as the key is int/long.
If you key is not int nor long, such as an object or String, you should use ArrayMap instead as it will handle the conflicts of key hashes.
There are no much performance and memory usage difference between these two class as they are all requires O(log n) to search and O(n) to insert/delete (in most cases).
I have a problem with this Json file. I am trying to do a Parser that shows in a textview the results after a button is pressed. I wonna parse the "firstName" tag but to do this, I need to pass through the others tags like "league" and "standard". I don't know how to parse them in this Json file.
The Json file is structured like this:
{
"_internal":{
"pubDateTime":"2017-06-23 03:21:52.076",
"xslt":"xsl/league/roster/marty_active_players.xsl",
"eventName":"league_roster"
},
"league":{
"standard":[
{
"firstName":"Alex",
"lastName":"Abrines",
"personId":"203518",
"teamId":"1610612760 1610612760",
"jersey":"8",
"pos":"G-F",
"heightFeet":"6",
"heightInches":"6",
"heightMeters":"1.98",
"weightPounds":"190",
"weightKilograms":"86.2",
"dateOfBirthUTC":"1993-08-01",
"teams":[
{
"teamId":"1610612760",
"seasonStart":"2016",
"seasonEnd":"2016"
}
],
"draft":{
"teamId":"1610612760",
"pickNum":"32",
"roundNum":"2",
"seasonYear":"2013"
},
"nbaDebutYear":"2016",
"yearsPro":"0",
"collegeName":"",
"lastAffiliation":"Spain/Spain",
"country":"Spain"
},
This is my Java code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
String Players[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btn);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
JSONArray jsonArray = new JSONArray(DataPlayers);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Wrong:
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
Correct:
JSONObject jsonObject = new JSONObject(result);
JsonObject objStandard = jsonObject.getJSONObject("league");
Now from objStandard object, you can retrieve the json array and iterate through the sub json objects.
JSONArray jsonArray = objStandard.getJSONArray("standard");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
2 cents suggestion :)
It seems you have just started exploring android development, saying based on you are using a legacy method of json parsing, I would suggest you to check out GSON library, which is a Java serialization/deserialization library to convert Java Objects into JSON and back. In short, you will not be needed to parse JSON response manually but rather you will be having normal java class objects and members/methods to deal with.
Your code should be like this
try {
String result = "your_json_string";
JSONObject jsonObject = new JSONObject(result);
JSONObject leagueObject = jsonObject.getJSONObject("league");
JSONArray standardArray = leagueObject.getJSONArray("standard");
for (int i = 0; i < standardArray.length(); i++) {
JSONObject standardObject = standardArray.getJSONObject(i);
String name = standardObject.getString("firstName");
}
} catch (Exception e) {
System.out.println(e);
}
I'm using recyclerView in my app in which I'm calculating the route distance between the cities in other thread than UI thread. Now I want to refresh the recyclerView's distance field only whenever the distance is calculated.
TIA
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.ListItemViewHolder> {
private List<DashBoardData> dashBoardData;
private Context context;
public DashboardAdapter(List<DashBoardData> dashBoardData, Context context) {
if (dashBoardData == null) {
throw new IllegalArgumentException("Data must not be null");
}
this.dashBoardData = dashBoardData;
this.context = context;
}
#NonNull
#Override
public ListItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout, viewGroup, false);
return new ListItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ListItemViewHolder holder, int position) {
holder.tvSource.setText(dashBoardData.get(position).getSource());
holder.tvDestination.setText(dashBoardData.get(position).getDestination());
getDistance(context,
dashBoardData.get(position).getStartLocation(),
dashBoardData.get(position).getEndLocation());
holder.tvDistance.setText("");
}
#Override
public int getItemCount() {
return dashBoardData.size();
}
public final static class ListItemViewHolder extends RecyclerView.ViewHolder {
TextView tvSource, tvDestination, tvDistance;
public ListItemViewHolder(View itemView) {
super(itemView);
tvSource = (TextView) itemView.findViewById(R.id.tv_from_source);
tvDestination = (TextView) itemView.findViewById(R.id.tv_to_destination);
tvDistance = itemView.findViewById(R.id.tv_distance);
}
}
public static void getDistance(Context context, String srcLocation, String destLocation) {
String url = getDirectionsUrl(context, srcLocation, destLocation);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
public static class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
String urlEncoded = (url[0]).replaceAll(" ", "");
data = downloadUrl(urlEncoded);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
private static String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception downloading url", e.toString());
} finally {
if (iStream != null) {
iStream.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return data;
}
private static class ParserTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... jsonData) {
JSONObject jObject;
String distance = "0 Mt";
try {
jObject = new JSONObject(jsonData[0]);
JSONArray jRoutes = null;
JSONArray jLegs = null;
jRoutes = jObject.getJSONArray("routes");
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
for (int j = 0; j < jLegs.length(); j++) {
distance = (String) ((JSONObject)((JSONObject) jLegs.get(j)).get("distance")).get("text");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return distance;
}
#Override
protected void onPostExecute(String result) {
//update ui
}
}
}
this is my adapter and I'm passing a dashboard list to this. After parsing the json data for distance I want to notify the distance field in onPostExecute() method.
The easiest way of doing that is once you are done updating all your data you call notify dataset changed on your adapter something like this:
//Some Code
mAdapter.notifyDataSetChanged();
Where mAdapter is the reference for your RecyclerView Adapter.
I have spent days on this, but I can't find a solution to my problem:
I'm developing an app that retrieves a list of theaters showing some movie selected by the user, parsing an HTML page in an AsyncTask.
I want to visualize those theaters on a Map with markers, so I need coordinates: once the "GetCinemaList" AsyncTask is completed, I try to populate my markerList in onPostExecute.
I have an SQLite db in which I store [theater|city|lat|lng]. So I first look up in the db, if it is not found I want call another AsyncTask to retrieve coordinates from HTTP google geocoding ('cause device geocoder returns null, causing the app to crash)
The problem is I am not able to return the LatLng point to the first AsyncTask...
I have tried to use listeners and to override processFinish(LatLng p), but I can't assign the value to my variable cause, accessing it from inner class it should be final.
Any help/idea? Thanks!
Here my code (containing error) for the AsyncTasks , in my Activity.
private class GetCinemaList extends AsyncTask<URL, Void, List<String>> {
private Context mContext;
public GetCinemaList(Context c){
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
List<String> cinemas = new ArrayList<>();
Document docHTML = null;
try {
docHTML = QueryUtils.makeRequest(urls[0]);
cinemas = QueryUtils.extractCinemasFromHTML(mTitile, docHTML);
} catch (IOException e) {
Log.e("JSwa", "Problem making request for parsing HTML "+e);
}
return cinemas;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
cinemaList = result;
LatLng point;
pointList = new ArrayList<>();
for (String elem : cinemaList) {
String name = elem.split("\t")[0];
String orari = elem.split("\t")[1];
Cursor cursor = queryDB(mCinemaDbR, city, name);
if (!cursor.moveToFirst()) {
// call geocoding service
new LatLongFromService(name.concat(" " + city), new AsyncResponse() {
#Override
public void processFinish(LatLng output) {
point = output;
}
}).execute();
Log.d("JSwa", "Inserting point "+point.toString());
// insert new value in the database
long id = addCimena(mCinemaDbW, name, city, String.valueOf(point.latitude), String.valueOf(point.longitude));
// insert new value in the list
MarkerOptions marker = new MarkerOptions().position(point).title(name).snippet(orari);
pointList.add(marker);
}
else{
double lat = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LAT)));
double lng = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LNG)));
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat,lng)).title(name)
.snippet(orari);
pointList.add(marker);
}
cursor.close();
}
for (MarkerOptions marker : pointList){
m_map.addMarker(marker);
}
}
}
// Sometimes happens that device gives location = null
public class LatLongFromService extends AsyncTask<Void, Void, StringBuilder> {
String place;
public AsyncResponse delegate = null;
public LatLongFromService(String place, AsyncResponse resp) {
this.place = place;
delegate = resp;
}
#Override
protected StringBuilder doInBackground(Void... params) {
try {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + this.place + "&sensor=false";
URL url = new URL(googleMapUrl);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(
conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
return jsonResults;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
try {
JSONObject jsonObj = new JSONObject(result.toString());
JSONArray resultJsonArray = jsonObj.getJSONArray("results");
JSONObject location = resultJsonArray
.getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
String lat_helper = location.getString("lat");
double lat = Double.valueOf(lat_helper);
String lng_helper = location.getString("lng");
double lng = Double.valueOf(lng_helper);
delegate.processFinish(new LatLng(lat, lng));
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
i have classes in my projects that only does the server operations such as getting and putting data. i have class which populating list and then method to get this list. the problem is that i'm calling the "getList" method and the background operation hasent finished then i get null from the "getList" method
this is my AsyncTask class, as you can see the "getList" suppose to give me the list completed
public class GetRoomatesListActivity extends AsyncTask<String, String, String> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}
and this is the class which im trying to get the list to in order to use it but its retrieving null
public class roomatesScreen extends Activity {
ListView items;
ArrayList<RoomateModel> list; //list to compare with the list rerived from GetRoomatesListActivity
RoomatesAdapter adapter;
DBHelper db;
ApartmentModel apartment;
SharedPreferences preferences;
GetRoomatesListActivity r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roomates_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView) findViewById(R.id.roomatesList);
db = DBHelper.getInstance(this);
Bundle bundle = getIntent().getExtras();
int number = bundle.getInt("number");
apartment = new ApartmentModel(number);// creates apartment model with the user's apartment number
final String num = Integer.toString(number);
r = new GetRoomatesListActivity(this);
r.execute("this is the link to my query" + num);
list = r.getList(); //here list is null
adapter = new RoomatesAdapter(roomatesScreen.this, list);
items.setAdapter(adapter);//here application crushes because of nullPointerExpeption
The best way is to perform the update on UI is in PostExecute method of AsyncTask..
At the time you are accessing it, the control is in the doInBackground method. So your list is null at that time.
put this
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter = new RoomatesAdapter(roomatesScreen.this, tmpList);
items.setAdapter(adapter);/
}
into the onPostExecute().
2nd solution
Initialize the list when you are setting it to adapter. like:
list = new ArrayList();
and rest work (update the list and call notifyDataSetChanged() on adapter object) in onPostExecute().
Change doInBackground() method return type
public class GetRoomatesListActivity extends AsyncTask<String, String, ArrayList<Object>> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected ArrayList<Object> doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}