How to make model class that receive data - android

How i Receive this data into to Model class i want to make a model class like getter setter andi use data from getter setter.
I want to make Model class
Basically i store it into variables not in separate class so i want to make model class
> Here is my code
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/* dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);*/
Toast.makeText(getApplicationContext(), "fetch data from server", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
LatLng latLng = new LatLng(Double.parseDouble(latitudeServer), Double.parseDouble(longitudeServer));
latLngList.add(latLng);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}

Although #Guillaume answer is correct, i would like to suggest a better and faster way. You can use a third party library LoganSquare to serialize and parse your models to and from JSON respectively. You just have to annotate your models and use LoganSquare class to parse data.
In your case it would be like this: (pay close attention to annotations above class name and fields)
#JsonObject
public class MyServer {
#JsonField(name = "longi")
public String longitudeServer;
#JsonField(name = "lati")
public String latitudeServer;
#JsonField(name = "uniqueid")
public String uniqueidSserver;
public MyServer(){
// blank constructor is required
}
}
Now use LoganSquare static class to parse the json response received from server:
for (int i = 0; i < jsonarray.length(); i++) {
MyServer s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), MyServer.class);
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}

First define your desired model into a class with for example a constructor allwing to create a new instance from a JSONObject
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
class MyServer {
private String longitudeServer;
private String latitudeServer;
private String uniqueidSserver;
public MyServer(JSONObject obj){
try{
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}catch(JSONException jse){
e.printStackTrace();
}
}
public String getLongitude(){
return longitudeServer;
}
public void setLongitude(String longitudeServer){
this.longitudeServer = longitudeServer;
}
//... More setter and getter here
}
// ... The existing code of your async task here
}
Once this done your can instanciate a new MyServer and use its getter/setter
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
MyServer s = new MyServer(obj); // Create your server from the JSONObject
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}

Related

How to take items from a JSON and convert to class

I need to extract values from the api of a city to a class in my own project.
This is the class i want to convert to.
public class Parada {
#SerializedName("wgs84_pos:long")
private long lon;
#SerializedName("wgs84_pos:lat")
private long lat;
#SerializedName("ayto:parada")
private String parada;
#SerializedName("vivo:address1")
private String direccion;
}
public class Santander {
private List<Result> results;
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
This is my code.
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://datos.santander.es/api/datos/paradas_bus.json");
httpGet.setHeader("content-type", "application/json");
HttpResponse resp = httpClient.execute(httpGet);
String respStr = EntityUtils.toString(resp.getEntity());
Gson gson = new GsonBuilder().create();
Santander santander = gson.fromJson(respStr, Santander.class);
List<Parada> paradas=new ArrayList<Parada>();
for (Parada p : santander.getResults())
{
paradas.add(p);
}
return paradas;
}
catch(Exception ex)
{
Log.e("ServicioRest", "Error!", ex);
}
Toast.makeText(getApplicationContext(), "Error grabbing values, return is null", Toast.LENGTH_LONG).show();
return null;
}
protected void onPostExecute(List<Parada> lParadas) {
if (lParadas!=null&&lParadas.size()>0) {
paradas=new Parada[lParadas.size()];
for (int i = 0; i < paradas.length; ++i){
paradas[i]=lParadas.get(i);
}
}
}
I need to get coordinates, address and name from the api into the array to then add them as points in a map, which is in a separate activity.
It gets the data in respStr but it doesnt go into class Santander
I dont think this is important but i add the code i use for the map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Parada[] paradas=MainActivity.paradas;
if (paradas!=null&&paradas.length>0) {
List<MarkerOptions> marcadores=new ArrayList<MarkerOptions>();
for (int i = 0; i < paradas.length; ++i) {
Parada p=paradas[i];
LatLng pCoords = new LatLng(p.getLat(), p.getLon());
marcadores.add(new MarkerOptions().position(pCoords).title(p.getParada()));
}
}
// Add a marker in Sydney and move the camera
LatLng ayto = new LatLng(43.461, -3.80793);
mMap.moveCamera(CameraUpdateFactory.newLatLng(ayto));
}

Nothing happens in the try

In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.

JSON from php file to java array

I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}
Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding

How to return an arraylist/list generated in an AsysnTask

I am trying to implement an google map app that will store the google marker on the cloud database. But I have a problem to get back the coordinate of the marker on the cloud.
How do I return a List generated in an AsyncTask back to a custom java class? The problem that I have encountered right now is when I initialize a Alistener class in different class, for example, in class B:
AListener a = new Alistener( ..., ... );
...
a.getMarkerData();
List<Pair> myList = a.getList();
myList is just null, and I think because the a.getList() has executed before the data is fetched back from that cloud database in onPostExecute(). Any insight will help a lot.
This is my java class:
public class AListener {
protected static final String TAG = null;
double lat, lon;
List<Pair> myList = new ArrayList<Pair>();
CustomMarkerListener( double lat, double lon ) {
this.lat = lat;
this.lon = lon;
}
public void getMarkerData() {
MarkerDataInfo ms = new MarkerDataInfo();
ms.execute( UserLogin.ITEM_URI );
}
public void setList(List<Pair> myList ) {
this.myList = myList;
}
public List<Pair> getList() {
return this.myList;
}
}
And this is my AsyncTask an inner class of AListener:
private class MarkerDataInfo extends AsyncTask<String, Void, List<Pair>> {
List<Pair> list;
private CustomMarkerListener mLis;
public MarkerDataInfo() {}
public MarkerDataInfo( CustomMarkerListener mLis ) {
this.mLis = mLis;
}
#Override
protected List<Pair> doInBackground(String... url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet( UserLogin.ITEM_URI);
list = new ArrayList<Pair>();
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Log.d(TAG, data);
JSONObject myjson;
try {
myjson = new JSONObject(data);
JSONArray array = myjson.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String markerOfUser = obj.get("marker").toString();
if( markerOfUser.equals( UserLogin.accountName )) {
String latname = obj.get("lat").toString();
String lonname = obj.get("lon").toString();
double latData = Double.parseDouble(latname);
double lonData = Double.parseDouble(lonname);
list.add( new Pair( latData, lonData ));
}
}
} catch (JSONException e) {
Log.d(TAG, "Error in parsing JSON");
}
} catch (ClientProtocolException e) {
Log.d(TAG, "ClientProtocolException while trying to connect to GAE");
} catch (IOException e) {
Log.d(TAG, "IOException while trying to connect to GAE");
}
return list;
}
protected void onPostExecute(List<Pair> list) {
super.onPostExecute(list);
mLis.setList( list );
Log.d("CUstome", "" + list.size());
}
}
If only one request is active at any time, you can use singleton pattern for your class.

Get returned JSON from AsyncTask

So I have this loader class which extends AsyncTask. Then I do new loader().execute(); but I want to use the JSONArray response which my loader class returns how do I do that? Because I need it in several different places? Or should I just move my code to onPostExecute and do everything from there?
public class loader extends AsyncTask<String, Integer, JSONArray> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(ChallengeList.this, "", "Laddar...");
dialog.setCancelable(true);
}
#Override
protected JSONArray doInBackground(String... params) {
JSONArray response = null;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(listURL);
try {
HttpResponse resp = client.execute(httppost);
StatusLine statusLine = resp.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.i("Statuscode", "statusCode"+statusCode);
if (statusCode == 200) {
final JSONObject json = new JSONObject();
json.put("userID", prefs.id());
response = SendHttp.parseHttp(listURL, json);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return response;
}
protected void onPostExecute(JSONArray result) {
dialog.dismiss();
}
}
The method onPostExecute has as parameter the JSONArray you returned from the doInBackground method.
onPostExecute runs on your main (caller) activity's thread, so besides dismissing the dialog in that method, you can process the result array further, pass it safely to other methods, etc:
#Override
protected void onPostExecute(JSONArray result)
{
super.onPostExecute(result);
final Message msg = new Message();
msg.obj = result;
if (youWantToUseHandler)
handler.dispatchMessage(msg);
else
writeJSONArray(result);
}
the handler:
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
final JSONArray result = (JSONArray)msg.obj;
writeJSONArray(result);
};
};
Some other method:
private void writeJSONArray(final JSONArray result)
{
for (int i = 0; i < result.length(); i++)
{
try
{
Log.d("SAMPLE", result.get(i).toString());
}
catch (JSONException e)
{
Log.e("SAMPLE", "error getting result " + i, e);
}
}
}
Since onPostExecute "Runs on the UI thread after doInBackground. The specified result is the value returned by doInBackground or null if the task was cancelled or an exception occured." ~API Docs
You can call any method you've declared in your class, and pass this array as a parameter to it.
After downloading the content web you can use the code below in onPostExecute method:
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources