Geo location Json data is not displayed - android

I think i write wrong my code where i try to retrieve geolocation data:
All relevant api keys are added and relevant api enabled...
private class GetCoordinates extends AsyncTask<String, Void, String>
{
ProgressDialog dialog = new ProgressDialog(AroundMeMapsActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
#Override
protected String doInBackground(String... strings) {
String response;
try {
Toast.makeText(AroundMeMapsActivity.this, "!!!!", Toast.LENGTH_SHORT).show();
String address = strings[0];
HttpDataHandler http = new HttpDataHandler();
//String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?adress=%s", address);
String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAzSgqQEZS1K1fowxhUnwxl4hMsKMsLlN4", address);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(String s) {
try {
Toast.makeText(AroundMeMapsActivity.this, "????", Toast.LENGTH_SHORT).show();
JSONObject jsonObject=new JSONObject(s);
String lat=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lat").toString();
String lng=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lng").toString();
answer_location.setText(String.format("Coordinates: %s / %s",lat,lng));
if(dialog.isShowing())
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I should get lat and lng coordinate, but it is not displayed...
Could you help to check why?

Related

How to make a toast when parsing data from json is null or no result?

I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.

In AsyncTask server's data is not getting on first time in android

I am trying to get data from server using AsyncTask, on first time result not showing, but its working from second time. I seen so many examples but none of them working for me. please see my code below
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(Void aVoid) {
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
Whenever you want to use onPostExecute() method in AsyncTask, just make sure use String or other type instead of Void as result parameter of AsyncTask<x, y, String> where x,y are any data type(Integer,String,etc..).
Therefore, make changes in code as per below:
Make both AsyncTask<...> like this AsyncTask<Integer,Void,String>
Change return type of doInBackground from Void to String
Change return null; with return ""; at last line in doInBackground.
Change onPostExecute(Void aVoid) to onPostExecute(String s) for override function of onpostexecute.
Then try it.
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,JSONArray> task = new AsyncTask<Integer, Void, JSONArray>() {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
#Override
protected JSONArray doInBackground(Object... integers) {
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
return array;
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(JSONArray array) {
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}

Multiple Async Tasks one after another Android

I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.

android json parsing No value for tag

I need to parse JSON using following code
urlGetDeviceIdMobileNo = Global.URL + "device_id="
+ strDeviceIdLocal;
public class GetDeviceId extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(LoginScreen.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(urlGetDeviceIdMobileNo);
System.out.println("!!!!!!!!!!!! json==="+json);
try {
strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
My Json data is :
{
status: "success",
data:
{
device_id: "35xxxxxxcccccvvvv",
mobile_number: "955896xxxxx"
}
}
But logcat says:
org.json.JSONException: No value for device_id
Just replace this
try {
strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
WITH
try {
strDeviceIdServer = json.getJSONObject("data").getString(TAG_DEVICE_ID);
strMobileNoServer = json.getJSONObject("data").getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
Your parsing is incorrect. Your JSONObject has child JSONObject "data", and this child JSONObject contains device_id. Therefore, you must parse it like:
try {
JSONObject childJson = json.getJSONObject("data");
if(childJson.has(TAG_DEVICE_ID))
strDeviceIdServer = childJson.getString(TAG_DEVICE_ID);
if(childJson.has(TAG_MOBILE_NO))
strMobileNoServer = childJson.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}

how to stop AsyncTask if some condition is true

I use asynctask to get json data from remote url but sometimes this url return errors in json data like this :
{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: RNN.NES",
"type": "OAuthException",
"code": 803
}
}
in doInBackground, i check if there an error by json ..
if(true) {
//cancel asynctask and show toast with message i use
cancel(true)
}
but i do that the condititon is true but it is not cancelled
this is my code :
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true);
}
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Now how can i stop that and show toast ???
thanks in advance
The method cancel(true) doesn't stop the AsyncTask. It just invokes onCancelled() instead of onPostExecute() after doInBackGround returns. You can use AsyncTask.isCancelled(), which will return true if you cancel the AsyncTask, to prevent further processing in doInBackground().
So override onCancelled() and put your Toast in there.
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true); // after this AsyncTask.isCancelled() returns true
}
if(!this.isCancelled()){ // if it's true, prevent further processing
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// will be called instead onPostExecute after a cancel
#Override
protected void onCancelled() {
// Show your Toast
}
}
You can check using isCancelled() in onPostExecute() method and can show Toast in that method.Here is how you can do that -:
#Override
protected void onPostExecute(Void result) {
if(isCancelled()) {
Toast.makeText(context, "your text", Toast.LENGTH_SHORT).show();
return;
}
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}

Categories

Resources