This is my sample code, where I make a json parsing class to parse data from a given link.
package com.billosuch.listviewblogpost;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class ListViewBlogPost extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<SearchResults> searchResultss = new ArrayList<SearchResults>();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(url);
// looping through All Contacts
Log.d("*********oSR", "B4 TRy");
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
SearchResults oSR = new SearchResults();
JSONObject c = contacts.getJSONObject(i);
oSR.setId(c.getString(TAG_ID));
oSR.setName(c.getString(TAG_NAME));
oSR.setEmail(c.getString(TAG_EMAIL));
oSR.setAddress(c.getString(TAG_ADDRESS));
oSR.setGender(c.getString(TAG_GENDER));
JSONObject phone = c.getJSONObject(TAG_PHONE);
oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));
searchResultss.add(oSR);
Log.d("*********oSR", oSR.getName());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("*********oSR", "AFTER TRy");
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));
}
}
This code showing me warning to do this in Asyntask. I want it to be supported on ICS and JellyBean.
Skipped 391 frames! The application may be doing too much work on its main thread.
You should use a asynctask for this purpose and move the network related code to doinBackground()
http://developer.android.com/reference/android/os/AsyncTask.html.
Load your asynctask on the UI thread as
new TheTask().execute()
Asynctask Class.
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//Network related opearaiton. Do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
You can pass the URL to the conbstructor of the asynctask or directly to doInbackground()
You are currently making a server request in the UI thread. While the app waits for the server response, your UI freezes and that's a bad user experience. Use an AsyncTask in order to load your data in another thread and update the UI when you get the server response.
here is an example
Change your code like below
package com.billosuch.listviewblogpost;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class ListViewBlogPost extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
final ListView lv1;
ArrayList<SearchResults> searchResultss;
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchResultss = new ArrayList<SearchResults>();
lv1 = (ListView) findViewById(R.id.ListView01);
new MyAsync(Youractivity.this).execute();
}
public class MyAsync extends AsyncTask<Void, Integer, Void> {
public MyAsync(Activity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
private ProgressDialog dialog;
/** application context. */
private Activity activity;
private Context context;
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(url);
// looping through All Contacts
Log.d("*********oSR", "B4 TRy");
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
SearchResults oSR = new SearchResults();
JSONObject c = contacts.getJSONObject(i);
oSR.setId(c.getString(TAG_ID));
oSR.setName(c.getString(TAG_NAME));
oSR.setEmail(c.getString(TAG_EMAIL));
oSR.setAddress(c.getString(TAG_ADDRESS));
oSR.setGender(c.getString(TAG_GENDER));
JSONObject phone = c.getJSONObject(TAG_PHONE);
oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));
searchResultss.add(oSR);
Log.d("*********oSR", oSR.getName());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("*********oSR", "AFTER TRy");
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));
}
}
}
Make LongOperation class like this.
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(url);
// looping through All Contacts
Log.d("*********oSR", "B4 TRy");
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
SearchResults oSR = new SearchResults();
JSONObject c = contacts.getJSONObject(i);
oSR.setId(c.getString(TAG_ID));
oSR.setName(c.getString(TAG_NAME));
oSR.setEmail(c.getString(TAG_EMAIL));
oSR.setAddress(c.getString(TAG_ADDRESS));
oSR.setGender(c.getString(TAG_GENDER));
JSONObject phone = c.getJSONObject(TAG_PHONE);
oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));
searchResultss.add(oSR);
Log.d("*********oSR", oSR.getName());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));
//might want to change "executed" for the returned string passed into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You can use async task like this...
package com.billosuch.listviewblogpost;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class ListViewBlogPost extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<SearchResults> searchResultss = new ArrayList<SearchResults>();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
new MyTask().execute(url);
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SocialActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("No data found from web!!!");
YourActivity.this.finish();
} else {
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
SearchResults oSR = new SearchResults();
JSONObject c = contacts.getJSONObject(i);
oSR.setId(c.getString(TAG_ID));
oSR.setName(c.getString(TAG_NAME));
oSR.setEmail(c.getString(TAG_EMAIL));
oSR.setAddress(c.getString(TAG_ADDRESS));
oSR.setGender(c.getString(TAG_GENDER));
JSONObject phone = c.getJSONObject(TAG_PHONE);
oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));
searchResultss.add(oSR);
Log.d("*********oSR", oSR.getName());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("*********oSR", "AFTER TRy");
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));
}
}
Related
I can't seem to figure this out, since im just a beginner with this android stuff.
My app gets the customer names from my WebAPI via JSON.
Now I am trying to load it into a spinner, but how can I load my JSON arraylist in there?
I tried loading custTable in it but its shows "com.jetron.jetronbuitendienst.CustomerDetailsTable....." in the spinner now.
My Code:
package com.jetron.jetronbuitendienst;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Gegevens extends Main {
String Naam;
Spinner spCustomers;
private ArrayList<CustomerDetailsTable> Klanten;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gegevens);
new AsyncLoadCustDetails().execute();
spCustomers = (Spinner) findViewById(R.id.spKlanten);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
protected class AsyncLoadCustDetails extends
AsyncTask<Void, JSONObject, ArrayList<CustomerDetailsTable>> {
ArrayList<CustomerDetailsTable> custTable = null;
#Override
protected ArrayList<CustomerDetailsTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
return custTable;
}
#Override
protected void onPostExecute(ArrayList<CustomerDetailsTable> result) {
// TODO Auto-generated method stub
// Application of the Array to the Spinner
ArrayAdapter<CustomerDetailsTable> spinnerArrayAdapter = new ArrayAdapter<CustomerDetailsTable>(getApplicationContext(), android.R.layout.simple_spinner_item, custTable);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spCustomers.setAdapter(spinnerArrayAdapter);
}
}
}
This is the jsonObj: D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
Well Since you are getting this:
D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
That implies that you are having an array that is called Value. So what you can do is this:
declare public variables :
private JSONObject jsonChildNode;
private JSONArray jsonMainNode;
private String name;
and then modify your code as:
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
jsonMainNode = jsonObj.optJSONArray("Value");
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("Naam");
}
//and then you can add the name to a List<String> which will contain all the values of each item in the Value JSON Array.
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
Hope it helps!!!
That worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
Check API reference here.
ArrayAdapter uses the Object.toString() to fill the view.
Here in the code, with the Object CustomerDetailsTable does not override the toString() function, So it just print the name of the class.
So I have 4 strings that I got from a JSON API and was wondering how to style them? Eg: the 4 strings I have are max players, current players, a Boolean saying true or false if the server is online or offline, and the current ping. Right now it just displays like this:
35053
26690
true
205
But I want it to display like
26690/35053 players online
ping: 205
server online: true
So how would I go about doing that?
MainActivity.java:
package in.untie.hypixelmobile;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://api.razex.de/server/status/mc.hypixel.net:25565";
private static final String PMAX = "Max";
private static final Boolean ONLINE = false;
private static final String PING = "Ping";
private static final String PCURRENT = "Current";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_item, new String[]{PCURRENT, PMAX, ONLINE.toString(), PING}, new int[]{R.id.ping, R.id.max, R.id.online, R.id.current});
setListAdapter(adapter);
lv = getListView();
}
#Override
protected Boolean doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromURL(url);
try {
String ping = json.getString("ping");
Boolean isonline = json.getBoolean("online");
JSONObject playersObject = json.getJSONObject("players");
String pmax = playersObject.getString("max");
String pcurrent = playersObject.getString("online");
HashMap<String, String> map = new HashMap<String, String>();
if (isonline) {
map.put(PING, ping);
map.put(ONLINE.toString(), isonline.toString());
map.put(PMAX, pmax);
map.put(PCURRENT, pcurrent);
jsonlist.add(map);
} else {
map.put(ONLINE.toString(), isonline.toString());
jsonlist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
}
String.format() is commonly used for such tasks, e.g.
String.format("%d/%d players online\n\nping: %s\n\n server online: %s", PCURRENT, PMAX, PING, ONLINE.toString())
Read up on it here.
I guess this is what you want, result will be in jsonResults
package in.untie.hypixelmobile;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://api.razex.de/server/status/mc.hypixel.net:25565";
private static final String PMAX = "Max";
private static final Boolean ONLINE = false;
private static final String PING = "Ping";
private static final String PCURRENT = "Current";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
StringBuilder jsonResults = new StringBuilder();
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_item, new String[]{PCURRENT, PMAX, ONLINE.toString(), PING}, new int[]{R.id.ping, R.id.max, R.id.online, R.id.current});
setListAdapter(adapter);
lv = getListView();
}
#Override
protected Boolean doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromURL(url);
try {
String ping = json.getString("ping");
Boolean isonline = json.getBoolean("online");
JSONObject playersObject = json.getJSONObject("players");
String pmax = playersObject.getString("max");
String pcurrent = playersObject.getString("online");
if (isonline) {
jsonResults.append(pcurrent+"/"+pmax+" players online");
jsonResults.append("ping: "+ping);
jsonResults.append("server online: "+ isonline.toString());
} else {
jsonResults.append("server online: "+ isonline.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
}
I am trying to add markers from JSON Parsing. but the markers are not showing in the map. Can anyone please help me? Here is my code:
MainActivity.java
package com.hasibhasan.sampletask;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity {
private GoogleMap googlemap;
private static String TAG_POSTS = "posts";
private static String TAG_DRIVER = "driver";
private static String TAG_ID = "id";
private static String TAG_LATITUDE = "lat";
private static String TAG_LONGITUDE = "lon";
private static String TAG_DATETIME = "recorded_datetime";
private static String TAG_USERID = "user_id";
private static String TAG_STATE = "cabby_state";
private static String TAG_VTYPE = "vehicleType";
private static String TAG_DRIVERNAME = "driver_name";
private static String TAG_PICNAME = "pic_name";
private static String TAG_RATING = "rating";
private static String TAG_CARMODEL = "car_model";
private static String TAG_NUMBERSIT = "number_sit";
private static String TAG_DISTANCE = "distance";
private static String TAG_OPERATOR = "operator";
private static String TAG_NEARESTDISTANCE = "nearest_distance";
private static String TAG_NDISTANCE = "distance";
private static String TAG_TIME = "time";
private static String TAG_CARMODELS = "car_models";
ArrayList<Taxi> taxi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taxi = new ArrayList<Taxi>();
new ParseJSONTask().execute();
googlemap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
}
private class ParseJSONTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String jsonstr = webServiceHandler
.getJSONData("http://54.186.247.213/unicabi/mobileservice/CurrentLocationService.php");
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray postJson = jsonObject.getJSONArray(TAG_POSTS);
for (int i = 0; i < postJson.length(); i++) {
Taxi aTaxi = new Taxi();
JSONObject postObject = postJson.getJSONObject(i);
aTaxi.lat = postObject.getString(TAG_LATITUDE);
aTaxi.lon = postObject.getString(TAG_LONGITUDE);
aTaxi.driver_name = postObject.getString(TAG_DRIVERNAME);
taxi.add(aTaxi);
double lati = Double.parseDouble(aTaxi.lat);
double lon = Double.parseDouble(aTaxi.lon);
googlemap.addMarker(new MarkerOptions().title(
aTaxi.driver_name).position(new LatLng(lati, lon)));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
Taxi. java (the model class)
package com.hasibhasan.sampletask;
public class Taxi {
public String posts = "";
public String success = "";
public String driver = "";
public String id = "";
public String lat = "";
public String lon = "";
public String recorded_datetime = "";
public String vehicleType = "";
public String driver_name = "";
public String pic_name = "";
public String rating = "";
public String car_model = "";
public String number_sit = "";
public String distance = "";
public String operator = "";
public String nearest_distance = "";
public String car_models = "";
}
Webservicehandler.java
package com.hasibhasan.sampletask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class WebServiceHandler {
public WebServiceHandler() {
}
public String getJSONData(String url) {
String response = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Pass the array of MarkerOptions to your onPostExecute method which runs on the UI thread. You can add the markers to your map there. Example:
private class ParseJSONTask extends AsyncTask<Void, Void, List<MarkerOptions>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<MarkerOptions> doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String jsonstr = webServiceHandler
.getJSONData("http://54.186.247.213/unicabi/mobileservice/CurrentLocationService.php");
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray postJson = jsonObject.getJSONArray(TAG_POSTS);
List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
for (int i = 0; i < postJson.length(); i++) {
Taxi aTaxi = new Taxi();
JSONObject postObject = postJson.getJSONObject(i);
aTaxi.lat = postObject.getString(TAG_LATITUDE);
aTaxi.lon = postObject.getString(TAG_LONGITUDE);
aTaxi.driver_name = postObject.getString(TAG_DRIVERNAME);
taxi.add(aTaxi);
double lati = Double.parseDouble(aTaxi.lat);
double lon = Double.parseDouble(aTaxi.lon);
markers.add(new MarkerOptions().title(aTaxi.driver_name).
position(new LatLng(lati, lon)));
return markers;
}
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<MarkerOptions>();
}
#Override
protected void onPostExecute(List<MarkerOptions> markers) {
super.onPostExecute(markers);
for (MarkerOptions marker : markers) {
googlemap.addMarker(marker);
}
}
}
You are trying to update the UI from a non-UI thread. This not allowed and should normaly throw an exception. You should better use an custom listener to pass the taxi list to your UI thread from your onPostExecute method.
Make a custom Listener:
public interface ParsingFinishedListener{
public abstract void onParsingFinished(List<MarkerOptions> markers;
}
Add a constructor to your asyncTask like this:
public ParseJsonTask(ParsingFinishedListener l){
this.mParsingFinisedListener = l;
}
And in onPostExecute return the list:
#Override
protected void onPostExecute(List<MarkerOptions> markers) {
super.onPostExecute(markers);
mParsingFinishedListener.onParsingFinished(markers);
}
And rewrite your onCreate method:
#Override
public void onCreate(Bundele savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
googlemap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
taxi = new ArrayList<Taxi>();
new ParseJSONTask().execute(new ParsingFinishedListener(){
#Override
public void onParsingFinished(List<MarkerOptions> m){
for (MarkerOptions marker : markers) {
googlemap.addMarker(marker);
}
}
);
My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}
You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
I have this code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.romantic.aacplay.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
// import android.text.Html;
// import android.text.Html;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class PodCast extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
private static String url_all_products = "http://mysite.net/andro/pcast.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "podcast";
private static final String TAG_LINK = "link";
private static final String TAG_NAME = "nume";
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poadcast);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Color.RED,Color.BLACK});
View title = getWindow().findViewById(android.R.id.title);
View titleBar = (View) title.getParent();
titleBar.setBackgroundDrawable(gd);
productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PodCast.this);
pDialog.setMessage("Se incarca. Asteapta...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("Ultimele 10 piese: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String link = c.getString(TAG_LINK);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// String href = String.format(" %s ", link, name);
// String cici = Html.fromHtml(href).toString();
map.put(TAG_NAME, name);
map.put(TAG_LINK, "" + Html.fromHtml(link));
// map.put(TAG_LINK, link);
productsList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
}
}
}
Now i'm trying to figure out how can i make the links in listview clickable. I`m trying to linkify a textview that is in found here:
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
}
R.layout.list_item which is a different .xml layout for the listview.
So can you guys help me solve this? Thanks in advance!
I feel instead of using SimpleAdapter,Please extend the BaseAdapter and make the textview you are using as linkify.so it will automatically get click.
please refer:
Android dev blog
put this line to ur textview
android:autoLink="web"
i hope this will solve ur query
I wanted as well to create a linkeable textView on my list adapter so I used:
Linkify.addLinks(textViewLocationPhone, Linkify.PHONE_NUMBERS);
textViewLocationPhone.setLinksClickable(true);
and it worked.