JSON parsing in android: opening objects inside objects - java

This should be really simple and i've been getting close to figuring it out but am starting to loose my sanity.
Simply trying to pull data from an api
How do i pull JSON data from an object (inside another object)?
This is the first day i've ever heard of JSON so ill be the first to admit i have very little knowledge about this. Thanks for your time!
This post: JSON parsing in android: No value for x error was super helpful and got me to where i am now which is trying to open "list" then get into "0" so i can gather weather data.
Been using jsonviewer.stack to try to understand this stuff
Api url: http://api.openweathermap.org/data/2.5/forecast/city?id=4161254&APPID=e661f5bfc93d47b8ed2689f89678a2c9
My code:
public class MainActivity extends AppCompatActivity {
TextView citySpot;
TextView cityTemp;
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// this works flawlessly and gathers the city name
JSONObject container = new JSONObject(result);
JSONObject cityTest = container.getJSONObject("city");
citySpot.setText(cityTest.getString("name"));
// this is my failed attempt to get inside of the "list" folder
JSONObject listList = new JSONObject(result);
JSONObject listTest = listList.getJSONObject("list");
JSONObject listTestOne = listTest.getJSONObject("0");
JSONObject listTestTwo = listTestOne.getJSONObject("main");
cityTemp.setText(listTestTwo.getString("temp"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
citySpot = (TextView) findViewById(R.id.cityName);
cityTemp = (TextView) findViewById(R.id.textView3);
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/forecast/city?id=4161254&APPID=e661f5bfc93d47b8ed2689f89678a2c9");
}
}

You could try use gson library to parse the response. Add below in build.gradle
compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
Create beans to match your response. Use fields to match what comes back in the json response. Sample below.
public class ResultsResponse {
private List<MyList> list;
}
public class MyList {
private String main;
}
If you want MyList can have another list. Finally try
GsonBuilder gsonBuilder = new GsonBuilder();
ResultsResponse response = gsonBuilder.create().fromJson(jsonString, ResultsResponse.class)
response object should have your list populated.

Related

REST API OpenWeatherMap not working with Variable Input, works correctly with fixed input..

Application fetches data from OpenWeatherMap API and works correctly when I indicate a city, e.g. "London". There is an error when I replace "London" with a variable "place".. Underneath you can find the code.
Can anyone help me?
**MAIN ACTIVITY**
public class MainActivity extends AppCompatActivity {
//create the fields on the Activity
private TextView cityName;
private TextView temp;
private TextView description;
private TextView humidity;
private TextView pressure;
private TextView wind;
private TextView sunrise;
private TextView sunset;
private TextView updated;
private Exception error;
Weather weather = new Weather();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up all the resources for the Views here
cityName = (TextView)findViewById(R.id.cityText);
temp = (TextView)findViewById(R.id.tempText);
description = (TextView)findViewById(R.id.CloudText);
humidity = (TextView)findViewById(R.id.HumidText);
pressure = (TextView)findViewById(R.id.PressureText);
wind = (TextView)findViewById(R.id.WindText);
sunrise = (TextView)findViewById(R.id.RiseText);
sunset = (TextView)findViewById(R.id.SetText);
updated = (TextView)findViewById(R.id.UpdateText);
//instantiate a CityPreference object from the MainActivity that
carries the city with it..
//render the data based on the city you get through the parsing
CityPreference cityPreference = new CityPreference(MainActivity.this);
renderWeatherData(cityPreference.getCity());
}
public void renderWeatherData (String city){
// we want to do all of our tasks in the background, use AsyncTask for this
WeatherTask weatherTask = new WeatherTask();
weatherTask.execute(new String[]{city} + "&units=metric");
}
//last parameter is Weather, this is what we will be populating
private class WeatherTask extends AsyncTask<String, Void, Weather>{
//AsyncTask <PARAMETERS, TASK, RESULT>
#Override
protected Weather doInBackground(String... params) {
//background computation
//data variable holds all the data that we have got..
//instantiate the weather client and get the weather data..
//getWeatherData gets all necessary data from HTTPClient
//getWeather parses all the data from the JSONParser
try {
String data = ((new WeatherHTTPClient().getWeatherData(params[0])));
weather = JSONWeatherParser.getWeather(data);
//create a log to test if everything is working
Log.v("Data:",weather.currentCondition.getDescription());
return weather;
} catch (Exception e) {
error = e;
}
return null;
}
//here you will populate the data so you can show it to the user
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
try {
//gets time and decimal formats and applies it to the data underneath
DateFormat df = DateFormat.getTimeInstance();
String sunriseDate = df.format(new Date(Weather.place.getSunrise()));
String sunsetDate = df.format(new Date(Weather.place.getSunset()));
String updateDate = df.format(new Date(Weather.place.getLastupdate()));
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String tempFormat = decimalFormat.format(weather.currentCondition.getTemperature());
//gets the value from the JSON and parses it in the view of the activity
cityName.setText(weather.place.getCity() + "," + weather.place.getCountry());
temp.setText("" + tempFormat + "C");
humidity.setText("Humidity" + weather.currentCondition.getHumidity() + "%");
pressure.setText("Pressure" + weather.currentCondition.getPressure() + "hPa");
wind.setText("Wind" + weather.wind.getSpeed() + "mps");
sunrise.setText("Sunrise" + sunriseDate);
sunset.setText("Sunset" + sunsetDate);
updated.setText("Updated" + updateDate);
description.setText("Condition" + weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescription() + ")");
} catch(Exception e) {
error = e;
}
}
}
//create an alert dialog to put in the city you want to parse the data for - A subclass of Dialog that can display one, two or three buttons.
private void showInputDialog () {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Change City");
final EditText cityInput = new EditText(MainActivity.this);
cityInput.setInputType(InputType.TYPE_CLASS_TEXT);
cityInput.setHint("put down city name");
builder.setView(cityInput);
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which){
CityPreference cityPreference = new CityPreference(MainActivity.this);
cityPreference.setCity(cityInput.getText().toString());
String newCity = cityPreference.getCity();
renderWeatherData(newCity);
}
});
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate the menu, this adds items to the action bar if it is present
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_cityId){
showInputDialog();
}
return super.onOptionsItemSelected(item);
}
}
**HTTP CLIENT**
public class WeatherHTTPClient {
public String getWeatherData (String place) throws IOException {
// setting things up.., create connection between application and the web, everything we get from the web comes as an inputstream
HttpURLConnection connection = null;
InputStream inputStream = null;
// api.openweathermap.org/data/2.5/weather?q=London
// errors may occur when you connect to the internet, build this in the model with try...catch
WHEN I REPLACE "place" by "London" in the next statement, the application works. THERE MUST BE AN ERROR WITH THIS PART, BUT I CANNOT FIND IT.. I NEED HELP..
try {
connection = (HttpURLConnection) (new URL(Utils.BASE_URL + place +"&APPID=f77c39703fb6be71e2c5a96e58edc077")).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
//read the response, buffer "bucket" where you are going to put your data
StringBuffer stringBuffer = new StringBuffer();
//you get a stream of bits and data to your device - everything comes in as an inputstream
inputStream = connection.getInputStream();
//BufferedReader is the only thing that can read the stream of data - hold it and start reading
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
//line is set as the data read by the BufferedReader, Stringbuffer reads the Buffer and goes to the next one
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line + "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {e.printStackTrace();}
return null;
}
}
**WEATHER DATA MODEL JSON**
public class Weather {
public static Place place;
public String IconData;
public CurrentCondition currentCondition = new CurrentCondition();
public Temperature temperature = new Temperature();
public Wind wind = new Wind();
public Snow snow = new Snow();
public Clouds clouds = new Clouds();
}
**PLACE DATA MODEL, left out getters and setters**
**LEFT OUT THE FULL DATA MODEL**
public class Place {
private float lon ;
private float lat ;
private long sunset;
private long sunrise;
private String country;
private String city;
private long lastupdate;
**THE WEATHER PARSER**
public class JSONWeatherParser {
public static Weather getWeather(String data){
//we call the top JSON object weather
Weather weather = new Weather();
//create JSONObject that holds all of the data you get from the web
//place is the parameter you use to get all the data for
//the rest of the variables you have to "calculate" from your data model
//tagName needs to be EXACTLY as it is in the JSON
try {
JSONObject jsonObject = new JSONObject(data);
Place place = new Place();
//for each "header" in JSON you create a JSONObject or a JSONArray
JSONObject coorObj = Utils.getObject("coord", jsonObject);
//you set the latitude by getting the "lat" variable from the coorObj from the top JSON Object weather
place.setLat(Utils.getFloat("lat",coorObj));
place.setLon(Utils.getFloat("lon",coorObj));
//get the sys object
JSONObject sysObj = Utils.getObject("sys", jsonObject);
place.setCountry(Utils.getString("country", sysObj));
//dt Lastupdate is found directly under the jsonObject, hence ...
place.setLastupdate(Utils.getInt("dt", jsonObject));
place.setSunrise(Utils.getInt("sunrise",sysObj));
place.setSunset(Utils.getInt("sunset",sysObj));
place.setCity(Utils.getString("name",jsonObject));
weather.place = place;
//get the weather info, it is a JSONArray of the main jsonObject (the whole thing) - starts with square brackets
JSONArray jsonArray = jsonObject.getJSONArray("weather");
//get the underlying Jsonobject from the jsonarray
JSONObject jsonWeather = jsonArray.getJSONObject(0);
weather.currentCondition.setWeatherId(Utils.getInt("id",jsonWeather));
weather.currentCondition.setDescription(Utils.getString("description", jsonWeather));
weather.currentCondition.setCondition(Utils.getString("main",jsonWeather));
weather.currentCondition.setIcon(Utils.getString("icon",jsonWeather));
JSONObject mainObj = Utils.getObject("main", jsonObject);
weather.currentCondition.setHumidity(Utils.getInt("humidity",mainObj));
weather.currentCondition.setPressure(Utils.getInt("pressure",mainObj));
weather.currentCondition.setMin_temp(Utils.getFloat("temp_min",mainObj));
weather.currentCondition.setMax_temp(Utils.getFloat("temp_max", mainObj));
weather.currentCondition.setTemperature(Utils.getDouble("temp",mainObj));
JSONObject windObj = Utils.getObject("wind", jsonObject);
weather.wind.setSpeed(Utils.getFloat("speed", windObj));
weather.wind.setDeg(Utils.getFloat("deg",windObj));
JSONObject cloudObj = Utils.getObject("clouds", jsonObject);
weather.clouds.setPrecipitation(Utils.getInt("all", cloudObj));
return weather;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
If you look at the URL
https://api.openweathermap.org/data/2.5/weather?q=[Ljava.lang.String;#34e4306&units=metric&APPID=f77c39703fb6be71e2c5a96e58edc077
The value for the query field (q) is [Ljava.lang.String;#34e4306, which is invalid. Ensure that you are sending a proper string value in this place.
Can this line be modified from:
weatherTask.execute(new String[]{city} + "&units=metric");
to the code below:
weatherTask.execute(city + "&units=metric");
Hope this would help.

Android Login screen from Json

I´m newbie on Android and need help.
I have a JSON that looks like this:
{
"Id": 1,
"Name": "user",
"userId": 4,
"active": true,
"ProfileId": 1,
"Tema": "green",
"Language": "english",
"success": true,
"error": false
}
Json 2:
{"message":"no user or password","success":false,"erroAplicacao":false}
This is my code:
public class MainActivity extends AppCompatActivity {
EditText usernameWidget;
EditText passwordWidget;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
usernameWidget = (EditText) findViewById(R.id.tv_username);
passwordWidget = (EditText) findViewById(R.id.tv_password);
}// END ON CREATE
public class DownloadTask extends AsyncTask<String, Void, String> {
String message = "message";
String loginSuccess;
String Id = "Id";
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1){
char current = (char) data; // each time creates a char current
result += current;
data = reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
} // END doInBackground
//Method called when the doInBack is complete
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("***JSON ITSELF***", result);
loginSuccess = jsonObject.getString("success");
Log.i("*****LOGIN SUCCESS*****", loginSuccess);
message = jsonObject.getString("message");
Log.i("*****MESSAGE*****", message);
Id = jsonObject.getString("Id");
Log.i("*****ID*****", pessoaFisicaId);
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
if (loginSuccess.contains("true")){
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}else if (loginSuccess.contains("false")){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}// END POST EXECUTE
}// END Download Task
public void login(View view) {
String user = usernameWidget.getText().toString();
String pass = passwordWidget.getText().toString();
String stringJSON = "*URL*login=" + user + "&senha=" + pass;
DownloadTask task = new DownloadTask();
task.execute(stringJSON);
Log.i("*****JSON URL*****", stringJSON);
}// END LOGIN
}// END MAIN
In this order:
loginSuccess = jsonObject.getString("success");
message = jsonObject.getString("message");
Id = jsonObject.getString("Id");
I get the message ("no user or password") from json2 (different url) as a Toast.
If I change the order, lets say, to:
loginSuccess = jsonObject.getString("success");
Id = jsonObject.getString("Id");
message = jsonObject.getString("message");
I don´t get a message. In fact I get the value "message" from the String message at the start of the DownloadTask class.
It seems that the json is only getting two values, the first ones I ask for.
One thing though is that only when the user or password is wrong is that the json has a message (json2):
{"message":"no user or password","success":false,"erroAplicacao":false}
Since my json cant be transformed into an array json (I tried and got error saying this), what should I do?
When you call jsonObject.getString("your_string"), this will throw a JSONException if your string cannot be found. Therefore, the remaining lines in of code in the method will not be executed. Change your LogCat settings to verbose and you should be able to see what's going on.
More info on the getString() method here:
https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)
Use GSON
public class User{
private int Id;
private String Name;
}
Parse
User user = GSON.fromJSON(jsonString, User.class);

Fetching data from an API with JSON and storing two objects in a single row of an Array Adapter

I've got this code with fetches the "rate" data from an API, along with "rate", I need to get the "name". If I get "name" it often binds it below the "rate".
I need it to join on the same row of the List View, so it is like [Rate Name].
I need to get two objects of a JSON Array and bind it to the array adapter so I can display two objects in the same row of a List View so it is more user friendly.
The code below is of the AsyncTask, the code works fine but I need to add one more object and make sure it is displayed as one rate - one name and then iterating through the loop and adding more as needed in the same order.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
// the url of the web service to call
String yourServiceUrl = "eg: URL";
#Override
protected void onPreExecute() {
}
String filename = "bitData";
#Override
protected String doInBackground(String... arg0) {
try {
// create new instance of the httpConnect class
httpConnect jParser = new httpConnect();
// get json string from service url
String json = jParser.getJSONFromUrl(yourServiceUrl);
// parse returned json string into json array
JSONArray jsonArray = new JSONArray(json);
// loop through json array and add each currency to item in arrayList
//Custom Loop Initialise
for (int i = 1; i < 8; i++) {
JSONObject json_message = jsonArray.getJSONObject(i);
// The second JSONObject which needs to be added
JSONObject json_name = jsonArray.getJSONObject(i);
if (json_message != null) {
//add each currency to ArrayList as an item
items.add(json_message.getString("rate"));
String bitData = json_message.getString("rate");
String writeData = bitData + ',' +'\n';
FileOutputStream outputStream;
File file = getFileStreamPath(filename);
// first check if file exists, if not create it
if (file == null || !file.exists()) {
try {
outputStream = openFileOutput(filename, MODE_PRIVATE);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// if file already exists then append bit data to it
else if (file.exists()) {
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// below method will run when service HTTP request is complete, will then bind text in arrayList to ListView
#Override
protected void onPostExecute(String strFromDoInBg) {
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
}
}
Just Create Custom Class Messsage:
public class Item{
private String name;
private String rate;
public void Message(String n, String r){
this.name=n;
this.rate=r;
}
// create here getter and setter
}
Now in your background, you have to add name and rate in Message class
Public class MainAcitity extends Activity{
public static List<Item> items= new ArrayList<>();// define in inside the class
// this has to be down on background
Item i=new Item(json_message.getString("name"),json_message.getString("rate"));
items.add(i);
Now pass this listmessge onPostExecute :
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
Is that any helpful for you.
Follow this link.You will get my point.
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

Efficient way of downloading data in Android App from MySQL

I was just wondering if my code is ok in terms of downloading. My app needs a lot of data from a database so quick download times are crucial. The download time is ok but I think it can be programmed more efficient. Can you have a look at this? This class downloads many different companies and when downloaded they are put in a HashMap corresponding to their category. When finished downloading this class return a HashMap which contains multiple Hashmaps(categories) and in these Hashmaps the downloaded data. Dont mind the actual workflow but please concentrate on the way this class downloads data. Is there a way to do this faster?
public class CompanyDAO {
private static Controller delegate;
private static String companyUrl = "http:// URL HERE";
private Map<Object, Object> companyMap = new HashMap<Object, Object>();
private Map<String, Integer> pinMap = new HashMap<String, Integer>();
public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
delegate = _delegate; //reference to controller
pinMap = map;
}
public void getCompanyData(ArrayList<Object> categoriesArray) {
for (int i = 0; i < categoriesArray.size(); i++) {
Map<String, Object> categoriesInMap = new HashMap<String, Object>();
//ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
companyMap.put(categoriesArray.get(i), categoriesInMap);
}
this.downloadCompanyData();
}
private void downloadCompanyData() {
companyUrl = companyUrl + delegate.ID;
try {
new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DownloadCompanyData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
JSONArray companyDataArray;
try {
companyDataArray = new JSONArray(result);
for(int i=0;i<companyDataArray.length();i++){
JSONObject id = companyDataArray.getJSONObject(i);
String catName = id.getString(Controller.CAT_NAME);
if (companyMap.get(catName) != null) {
Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));
((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);
}
}
delegate.setCompanyHashMap(companyMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I guess you're missing the point of the AsyncTask
it's supposed to do all the work in doInBackground() and then use the onPostExecute to deliver it to the UI.
But what you're doing is doing the network operation on doInBackground and doing data parsing on onPostExecute.
Furthermore, a JSON object is a raw data that needs further parsing. You should do all the parsing on the background. For example, let's say your companyData is address, phone number, size and name. You could have a class like this (p.s. I'm writing all this without testing, there will be a little mistake here in there, but you'll get the idea):
public class CompanyData{
private String name, address, phone;
private int size;
public CompanyData(JsonObject jo){
name = jo.getString("name");
address = jo.getString("address");
phone = jo.getString("phone");
size = jo.getInt("size");
}
// put a bunch of get methods here...
// getName(), getAddress(), etc.
}
then on your 'protected Map doInBackground(String... urls) ' you complete the network operation, create the JsonArray, create a Map<String,CompanyData>, loop through the array creating CompanyData objects and placing them into the Map and return the map to your protected void onPostExecute(Map<String,CompanyData> result) and inside the post execute it's just pass this result to the UI.
happy coding.
I always doing something like this..
...
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....
private class CompanyData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Load data..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
CompanyList = new ArrayList<HashMap<String, String>>();
// Building Parameters if any.. to fetching all data, don't declare any param
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);
// Check your log cat for JSON reponse
Log.d("All Company: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Company found
// Getting Array of Company
Company = json.getJSONArray(TAG_COMPANIES);
// looping through All Company
for (int i = 0; i < Company.length(); i++) {
JSONObject json = Company.getJSONObject(i);
// Storing each json item in variable
String id = json.getString(TAG_GID);
String name = json.getString(TAG_NAME);
String jml = json.getString(TAG_EMPLOYEE);
String deskripsi = json.getString(TAG_DESKRIPSI);
String logo = json.getString(TAG_LOGO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_GID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMPLOYEE, jml);
map.put(TAG_DESKRIPSI, deskripsi);
map.put(TAG_LOGO, logo);
// adding HashList to ArrayList
CompanyList.add(map);
}
} else {
// no CompanyList found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing data ArrayList
adapter=new LazyAdapter(MainActivity.this, CompanyList);
list.setAdapter(adapter);
pDialog.dismiss();
}
}

AsyncTask is cancelled at constructor

I have an asynctask that - when executed - is cancelled right away.
My class looks like this:
public class JSONParser extends AsyncTask<String, Void, JSONArray> {
private ListFragment fragment;
#Override
protected JSONArray doInBackground(String... strings) {
JSONArray ja = null;
String string = "";
try {
URL url = new URL(strings[0]);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
string = br.readLine();
ja = new JSONArray(string);
} catch (Exception e ) {
Log.w("Special", e.toString());
}
return ja;
}
public JSONParser(ListFragment fragment) {
this.fragment = fragment;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
try {
ArrayList<HashMap<String ,String>> datalist = new ArrayList<HashMap<String, String>>();
int i = 0;
while (i < jsonArray.length()) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject tool = jsonArray.getJSONObject(i);
map.put("id", tool.getInt("Id") + "");
map.put("name", tool.getString("Name"));
datalist.add(map);
i++;
}
fragment.setListAdapter(new SimpleAdapter(fragment.getActivity(), datalist, R.layout.tools_list, new String[] {"name"}, new int[] {R.id.text}));
} catch (Exception e) {
e.getMessage();
}
}
}
and from my fragment I'm calling it like this
AsyncTask task = new JSONParser(this).execute("http://10.0.2.2:1288/webservice/gettools.aspx");
Using the debugger I can see that as soon as the constructor is called, it skips to onCancelled() and returns. The URL is valid and working, I get no messages in the Log, and the JSON is valid.
Update: Also I have the required permission and OnCancelled() is called before it enters doInBackground(). doInBackground() is never called.
Any ideas?
I'm using IntelliJ and an AVD with Android 4.0.3.
Do you have set Internet permissions in your AndroidManifest?
Are you sure that in the doInBackground there is no exception fired?
Maybe it could be a better idea to also put the while (i < jsonArray.length()) part in the doInBackground :) (for performance)
Code to read String:
BufferedReader reader = new BufferedReader(yourInputStreamReader,8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
oehm...
you are creating your task with an activity object (this) (???)
AsyncTask task = new JSONParser(this).execute("http://10.0.2.2:1288/webservic /gettools.aspx");
but your task expects a View
public JSONParser(ListFragment fragment) {
im surprised that this doesnt throw an exception

Categories

Resources