using aSyncTask with variables - java

I am making a simple weather app and i have a problem with reading variables by aSyncTask. I am very beginner in programming for andorid, so I am asking for understanding. So, i want to put variables "latitude" and "longitude" choosen from place picker into asyncTask.execute("Latitude", "Longitude") and refresh a screen to show weather for new location. Now it dosent work, but i noticed, that when i put coordinates in code not by variables (for ex. asyncTask.execute("52.2296756", "38,3435546") then weather for this location appears after using Place Picker. I have also added outprint to check this varibles, and they looks okay.
public class MainActivity extends AppCompatActivity {
TextView cityField, detailsField, currentTemperatureField,
humidity_field, pressure_field, weatherIcon, updatedField;
ImageView mPlacePicker;
Typeface weatherFont;
int PLACE_PICKER_REQUEST = 1;
String latitude;
String longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new
PlacePicker.IntentBuilder();
Intent intent;
try {
intent = builder.build(MainActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
String address = String.format("Place %s", place.getAddress());
Toast.makeText(this, address, Toast.LENGTH_LONG).show();
LatLng latLng = place.getLatLng();
latitude = String.valueOf(latLng.latitude);
longitude = String.valueOf(latLng.longitude);
//System.out.println(latitude);
//System.out.println(longitude);
}
}
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
weatherIcon = (TextView) findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
mPlacePicker = (ImageView) findViewById(place_picker);
Function.placeIdTask asyncTask = new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
System.out.println('"' + latitude + '"');
System.out.println('"' + longitude + '"');
asyncTask.execute('"' + latitude + '"', '"' + longitude + '"'); // asyncTask.execute("Latitude", "Longitude")
}
}
And this is second class with doInBackground
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "3b30fbc239f6a1ed664220635330aa46";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}
}

Remove the extra "". You don't need those e.g.
asyncTask.execute(latitude,longitude);

you can use a constructor for your class AsyncTask
something like this :
class placeIdTask extends AsynckTask<Void,Void,Void>{
Double latitude;
Double longitude;
public placeIdTask(Double latitude, Double longitude){
this.latitude = latitude;
this.longitude=longitude;
}
...//implement doInbackground using latitude and longitude
}
or
just you change the type of generic CLass like this
class placeIdTask extends AsynckTask<Double,Void,Void>{
#Override
protected Void doInBackground(Double... arg0) {
Double latitude = arg0[0];
Double longitude = arg0[1];
... }
... }
and I suggest u to use Double instead of String
hope that help you

//Add async task
private class SampleAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// this might take a while ...
// Do your task over here
// Use parameterlike this
latitude=params[0];
longitude=params[1];
return "Success";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//Call asyc task
new SampleAsyncTask().execute(String.valueOf(latitude),String.valueOf(longitude));
Hope this help you. Happy coding

Related

How to acces TextView From another class

I've got my main startup class loading MainActivity but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
private class DateValidation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog
}
#Override
protected String doInBackground(String... arg0) {
String hallId = arg0[0];
String date = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?id=" + URLEncoder.encode(hallId, "UTF-8");
data += "&date=" + URLEncoder.encode(date, "UTF-8");
link = "https://www.adoetech.co.tz/ehall/frontend/index.php/hall/validate-date" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
Log.d("postData: ", link);
return result;
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
boolean query_result = jsonObj.getBoolean("success");
String response = jsonObj.getString("data");
if (query_result) {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_LONG).show();
} else if (!query_result) {
Log.d("onPostExecute: ", "free");
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
//JSONArray dateVal = jsonObj.getJSONArray("data");
I need to setTest from here and I have declear hallPrice from MainActivity help Please
hallPrice.setText("300000000");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("onPostExecute: ", String.valueOf(result));
Toast.makeText(HallsDetails.this, "Error parsing JSON data.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HallsDetails.this, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Use intent to pass data from one activity to another like this:-
Intent in = new Intent(MainActivity.this, DateValidation.class);
in.putExtra("key", "300000000");
startActivity(in);
And in your DateValidation Activity do:-
Intent i = getIntent();
String value = i.getStringExtra("key");
hallPrice.setText(value);
You can pass the TextView in your AsyncTask.
public class DateValidation extends AsyncTask<String,String,String> {
TextView mTextView;
public DateValidation (TextView textView){
mTextView = textView;
}
#Override
protected String doInBackground(String... strings) {
/**
* do process here
*/
return "Result String here";
}
#Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}

HttpURLConnection won't work after pausing on activity

I have an Activity that uses a ListView to display an array of data fetched from a JSON response. Clicking on one of the items will present the user with a business card activity, displaying the data associated with the item clicked. When the application first loads, it works fine. I can close the business card and reopen it multiple times. However, if i pause on the ListView activity, the page will no longer load the data. I have placed Log.d commands before and after the connection to try debugging the issue. The activity is receiving the information necessary to perform the connection. However, the closest I have gotten to a solution is knowing that when it doesn't work, I cannot Log.d the response code immediately after opening the connection.
To be clear, I am including the entirety of the code I am using, just in case the issue lies somewhere else. First is the code for the ListView Activity, then is the Business Card Activity code.
This is the Directory Activity.
public class DirectoryActivity extends AppCompatActivity {
ListView lvContacts;
Button goMenu;
Button goFilter;
TextView tempText;
static ArrayList<String> arrlst = new ArrayList<>();
static ArrayAdapter<String> adapter;
private FetchList process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directory);
lvContacts = findViewById(R.id.lvContacts);
goMenu = findViewById(R.id.btn_goMenu);
goFilter = findViewById(R.id.btn_goSearch);
tempText = findViewById(R.id.temptext);
// Set adapter for listview: used in FetchList
adapter = new ArrayAdapter<>(this, R.layout.layout_org_list, R.id.listViewItem, arrlst );
lvContacts.setAdapter(adapter);
// Get list from DB
process = new FetchList();
process.setListener(new FetchList.FetchListTaskListener() {
#Override
public void onFetchListTaskFinished(String[] result) {
// update UI in Activity here
arrlst.clear();
for (String OrgName:result) {
addItemsToList(OrgName);
}
adapter.notifyDataSetChanged();
}
});
process.execute();
// Set onclick listener for listview
lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String selectedOrg = lvContacts.getItemAtPosition(position).toString(); // Get org name from list view
goBusinessCard(selectedOrg); // Go to business card
}
});
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
public static void addItemsToList(String item) {
arrlst.add(item);
}
// Set Methods for Buttons
public void goMenu(View v) {
startActivity(new Intent(this, HomeActivity.class));
}
public void goFilter(View v) {
startActivity(new Intent(this, FilterActivity.class));
Log.d("FILTER DEBUG", "checking if extras are filled " + this.getIntent().getExtras());
}
// Method for opening BusinessCardActivity and passes orgID
public void goBusinessCard(String selectedOrg) {
Bundle extras = new Bundle();
extras.clear();
extras.putString("selectedOrg", selectedOrg);
Intent BusinessCard = new Intent(this, BusinessCardActivity.class);
BusinessCard.putExtras(extras);
startActivity(BusinessCard);
}
// ASYNC TASK
static class FetchList extends AsyncTask<Void, Void, String[]> {
private FetchListTaskListener listener;
#Override
protected String[] doInBackground(Void... voids) {
try {
URL url = new URL(URL_READ_ORG ); // Set url to API Call location
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Open connection to html
InputStream inputStream = httpURLConnection.getInputStream(); // create input stream from html location
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); // create reader for inputStream
StringBuilder data = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null ) {
data.append(line); // creates string from all lines in response
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
JSONObject JO = new JSONObject(data.toString()); // creates object from json response in data string
JSONArray JA = JO.getJSONArray("orgs");
// Create array list to store items from json response
List<String> al_orgList = new ArrayList<>();
// Iterate through JSON array to get json object org_name
for (int i = 0; i < JA.length(); i++) {
JSONObject Orgs = JA.getJSONObject(i);
String org_name = Orgs.getString("org_name");
al_orgList.add(org_name);
}
// convert array list to array
return al_orgList.toArray(new String[al_orgList.size()]);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
// UI Process - allows manipulation of UI
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchListTaskFinished(result);
}
}
private void setListener(FetchListTaskListener listener) {
this.listener = listener;
}
public interface FetchListTaskListener {
void onFetchListTaskFinished(String[] result);
}
}
This is the Business Card Activity that runs the data fetch for individual items
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, selectedOrg, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
// Set variable for selectedOrg from DirectoryActivity
selectedOrg = Objects.requireNonNull(this.getIntent().getExtras()).getString("selectedOrg");
// Get Org data from DB using async
process = new FetchOrg();
process.setListener(new FetchOrg.FetchOrgTaskListener() {
#Override
public void onFetchOrgTaskFinished(String[] result) {
setTextView(result);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
}
});
process.execute(selectedOrg);
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
static class FetchOrg extends AsyncTask<String, Void, String[]> {
private FetchOrgTaskListener listener;
#Override
protected String[] doInBackground(String... params) {
try {
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchOrgTaskFinished(result);
}
}
private void setListener(FetchOrgTaskListener listener) {
this.listener = listener;
}
public interface FetchOrgTaskListener {
void onFetchOrgTaskFinished(String[] result);
}
}
Activity lifecycle would go back from paused to resume state.
You need to provide the expected behaviour inside onResume something like below
public void onResume(){
super.onResume();
new XXXAsyncTask( new XXXAsyncListener(){
public void postTaskMethod(){
//do stuff here
}
}).execute();
}
I made a few changes in your onCreate()method of your BusinessCardActivity. I check for hasExtra instead--a little more flexibility. I got rid of the Listener and packed all onClick listener below. I felt it was a bit too complicated using the Listener approach (So you can remove this process.setListener(null); from the onDestroy()method). I also added a few Log.e(); so you can see what is going on in the logcat.
(BTW "TAG" would be:
private static final Strting TAG = BusinessCardActivity.class.getSimpleName();)
With "BusinessCardActivity.class.getSimpleName();" written out just in case you refactor sometime.
This is part of your BusinessCardActivity onCreate() method:
// Set variable for selectedOrg from DirectoryActivity
Intent intent = this.getIntent();
if(intent.hasExtra(selectedOrg)){
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
}
else{
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
//Move all your onClick Listeners below...
I don't think this is the best case to use a Listener so lets use the AsyncTask like this (I also removed the static):
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
try {
Log.e(TAG, "doInBackground ... Started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
Log.e(TAG, "Data Returned : " + line);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
setTextView(result);
}
}
Also I would change your method goBusinessCard() a bit (and no need to be public):
private void goBusinessCard(String selectedOrg) {
//Java variables should written in lower case and Classes Capitalized
Intent businessCard = new Intent(this, BusinessCardActivity.class);
businessCard.putExtra("selectedOrg", selectedOrg);
startActivity(businessCard);
}
Please let me know if you have any issues! I typed this out in a standard Text Editor..so there might be a few typos.
Posting a new answer so I can add all the code for the BusinessCardActivity class.
I added some additional logging and changed getString() to optString() in order to be able to offer an alternative value. For example if the value or "key" is invalid or missing you would get an error.
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
Intent intent = this.getIntent();
if(!intent.hasExtra("selectedOrg")){
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection con = null;
String[] org_data = null;
try {
Log.e(TAG, "FetchOrg doInBackground started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
URL url = new URL(orgbyname);
con = (HttpURLConnection) url.openConnection();
Log.e(TAG, "FetchOrg doInBackground Connected!");
//Check the response code of the server -
Integer replyCode = con.getResponseCode();
logMess += " Reply Code: " + replyCode.toString();
responseStream = new BufferedInputStream(con.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
logMess += " elapsed Time : " + elapsedTime + " ms";
Log.e(TAG, "FetchOrg logMess: --- " + logMess);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
//Make sure you get everything!
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
//this will close underlying streams
responseStreamReader.close();
String data = stringBuilder.toString();
Log.e(TAG, "FetchOrg Data: --- " + data);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject obj = new JSONObject(data); // creates object from json response in data string
JSONObject orgs = obj.getJSONObject("orgs"); // creates array for parsing of json data
String nA = "not available";
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = orgs.optString("org_name", nA);
String FirstName = orgs.optString("contact_first_name", nA);
String LastName = orgs.optString("contact_last_name", nA);
String Email = orgs.optString("contact_email", nA);
String Phone = orgs.optString("contact_phone", nA);
String Website = orgs.optString("org_website", nA);
String ServiceType = orgs.optString("org_type", nA);
String ServicesProvided = orgs.optString("org_services", nA);
String Address = orgs.optString("org_street_address", nA);
String City = orgs.optString("org_city", nA);
String State = orgs.optString("org_state", nA);
String Zip = orgs.optString("org_zip", nA);
String Lat = orgs.optString("latitude", nA);
String Long = orgs.optString("longitude", nA);
// Add items to string array
org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
} catch (Exception ex) {
Log.e(TAG, "FetchOrg doInBackground: " + ex.getMessage());
}
finally{
//just in case you get an error above
if(con != null){
con.disconnect();
}
}
return org_data;
}
#Override
protected void onPostExecute(String[] result) {
if(result != null){
setTextView(result);
}
else{
Log.e(TAG, "FetchOrg onPostExecute: result is null");
}
}
}
Be aware that I did not clean up things like maintaining minimal scope: For example :public void showEmailDialog() and public void goMap() which do not need to be public methods! Any method that does not need to be accessed outside the class (and that is rare!) should not be made public.
You have also defined many class variables at the beginning of the class like "Favorite, Latitude, Longitude, FavoriteChanged" do they need to have class wide scope?? And they are variables! So in java naming convention, variables and methods are written in lower case, while classes are capitalized--this helps reading code easier (for the SO community!)
When working with Indent extras often mistakes are made when entering the "key" like "selectedOrg". Therefore it is some times an advantage to create a global class to help keep things straight. Example public class GlobalExtras and just keep public static final String SELECTED_ORG = "selectedOrg"; Then just use intent.getString(SELECTED_ORG);
Another thing: I am not a big fan of String[] as you have used to store your "org" strings. They can be tricky with size and indexes. You might want to consider using another object.
I do not have access to your API and your data, so I was only able to make requests on my server trying to duplicate your user scenario, but I was unable to reproduce your issue. I hope this helps, let me know what the logcat spits out!

I want to fetch Longitude and Latitude separately from a particular address

I followed an example from Android Geocoding to Get Latitude Longitude for an Address tutorial, it worked but I want to fetch the longitude and latitude coordinates separately but could not.
Here is my code:
public class MainActivity extends AppCompatActivity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
static TextView txtLatitude;
TextView txtLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressTV = (TextView) findViewById(R.id.addressTV);
latLongTV = (TextView) findViewById(R.id.latLongTV);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLatitude= (TextView) findViewById(R.id.txtLongitude);
addressButton = (Button) findViewById(R.id.addressButton);
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.addressET);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
});
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress,latitude ,longitude ;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
break;
default:
locationAddress = null;
latitude = null;
longitude= null;
}
latLongTV.setText(locationAddress);
txtLatitude.setText(latitude);
// txtLongitude.setText(longitude);
}
}
private static class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String strLatitude = null, strLongitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
double latitude = address.getLatitude();
double longitude = address.getLongitude();
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
strLatitude = String.valueOf(latitude);
strLongitude= String.valueOf(longitude);
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
According to this answer, bundle keys are case-sensitive. You set the strings with:
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
But then get them with:
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Notice you put with a capital L, but get with a lower-case l.

How to access response value outside onResponse method in android

I am working on a android project. I got the response from google api and parsed the json. But i want to return the value outside of onResponse method which seems to be impossible for me now. Below is my code, I have already seen this answer here. But i want this value outside of this async method. Is it possible to access this value.
UPDATE - I have updated my code for more details. This is my full activity class. You can see what i want to achieve. Please help me how i can access value returned by Volley onResponse in method get_time_to_travel, inside method parseJson. This is really killing me now. My first android project and i am stuck here from last two days.
Any help on this would be appreciated.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private CustomAdapter adapter;
private List<UserData> userData;
private LocationManager locationManager;
private LocationListener locationListener;
String origin, mode = "driving";
private String API = "APIKey";
TextView textView;
RequestQueue requestQueue;
RequestQueue requestQueue1;
String url = "https://url/users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
origin = String.valueOf(lat)+","+String.valueOf(lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
return;
}
else{
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
getData();
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
}
private void getData(){
userData = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJson(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonArrayRequest);
}
private void parseJson(JSONArray response){
try {
for (int i = 0; i < response.length(); i++) {
JSONObject users = response.getJSONObject(i);
String id = ("id: "+users.getString("id"));
String name = ("Name: "+users.getString("name"));
String username = ("Username: "+users.getString("username"));
String email = ("Email: "+users.getString("email"));
String address = parseAddress(users);
String destination = parseCoordinates(users);
String company = parseCompany(users);
String phone = ("Phone: "+users.getString("phone"));
String website = ("Website: "+users.getString("website"));
String eta = get_time_to_travel(origin, destination, API, mode);
UserData udata = new UserData(id, name, username, email, address, phone, website, company,eta);
userData.add(udata);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String parseAddress(JSONObject users) {
JSONObject completeAdd = null;
String address = null;
try {
completeAdd = users.getJSONObject("address");
String street = completeAdd.getString("street");
String suite = completeAdd.getString("suite");
String city = completeAdd.getString("city");
String zipcode = completeAdd.getString("zipcode");
address = ("Address :" + street + ", " + suite + ", " + city + ", " + zipcode);
} catch (JSONException e) {
e.printStackTrace();
}
return address;
}
private String parseCoordinates(JSONObject users) {
JSONObject completeAdd = null;
String destination = null;
try {
completeAdd = users.getJSONObject("address");
JSONObject coordinates = completeAdd.getJSONObject("geo");
String latitude = coordinates.getString("lat");
String longitude = coordinates.getString("lng");
destination = latitude + "," + longitude;
} catch (JSONException e) {
e.printStackTrace();
}
return destination;
}
private String parseCompany(JSONObject users) {
JSONObject companyDetail = null;
String company = null;
try {
companyDetail = users.getJSONObject("company");
String company_name = companyDetail.getString("name");
String catchPhrase = companyDetail.getString("catchPhrase");
String bs = companyDetail.getString("bs");
company = ("Company: " + company_name + ", " + catchPhrase + ", " + bs);
} catch (JSONException e) {
e.printStackTrace();
}
return company;
}
private String get_time_to_travel(String origin, String destination, String API, String mode){
requestQueue1 = Volley.newRequestQueue(this);
String eta = null;
String google_api = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+origin+"&destinations="
+destination+"s&mode="+mode+"&language=fr-FR&key="+API;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, google_api, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue1.add(jsonObjectRequest);
return eta;
}
private String parseGoogleData(JSONObject response) {
String estimated_time_arrival = null;
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements = rows.getJSONObject(0);
JSONArray elementsArr = elements.getJSONArray("elements");
JSONObject durationObj = elementsArr.getJSONObject(0);
JSONObject durationData = durationObj.getJSONObject("duration");
estimated_time_arrival = durationData.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return estimated_time_arrival;
}
}
Async task is doing work on other thread. So if you want to access any variable out side that method, you need to wait until the task get completed. Otherwise the variable will be null.
eg: on on response method
#Override
public void onResponse(String response) {
res=response;
anyMethodtopassVar(DataType data);
}
in OnCreate() of activity, remove these 2 lines
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
in getData() remove this line
userData = new ArrayList<>();
put them in parseJson() as below:
private void parseJson(JSONArray response){
try {
if(userData==null){
userData = new ArrayList<>();
}else{
userData.clear();
}
for (int i = 0; i < response.length(); i++) {
JSONObject users = response.getJSONObject(i);
String id = ("id: "+users.getString("id"));
String name = ("Name: "+users.getString("name"));
String username = ("Username: "+users.getString("username"));
String email = ("Email: "+users.getString("email"));
String address = parseAddress(users);
String destination = parseCoordinates(users);
String company = parseCompany(users);
String phone = ("Phone: "+users.getString("phone"));
String website = ("Website: "+users.getString("website"));
String eta = get_time_to_travel(origin, destination, API, mode);
UserData udata = new UserData(id, name, username, email, address, phone, website, company,eta);
userData.add(udata);
}
if(adapter == null){
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this way, when json call finish, parseJson() is called.
and after parsing the array into userData the adapter is initialized or notified.
EDIT:
Well, this is not the best sol. but it's just something from the top of my head
little nasty/dirty. i don't know but i think it will do the job
1- you don't have to reinit the queue every time, so in get_time_to_travel() put that line out of the method:
requestQueue1 = Volley.newRequestQueue(this);
add final int index param to the method and make it void:
private void get_time_to_travel(String origin, String destination, String API, String mode, final int index){...
make onResponse() in the method like this:
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
userData.get(index).setEta(eta);//add this setter to your data object if not exist.
}
remove return eta;
init udata with empty string as eta for now:
UserData udata = new UserData(id, name, username, email, address, phone, website, company,"");
userData.add(udata);
modify the call to get_time_to_travel() in parseJson() as below:
get_time_to_travel(origin, destination, API, mode, i);
when get_time_to_travel() is called at onResponse() the object will be modified to hold the eta value retrieved from the API
this is nasty, sometimes the adapter might be notified before all calls to google api is completed. so this is just to show you how to make it
Edit2
a workaround for this is
init userData object with label "Loading..." for eta
UserData udata = new UserData(id, name, username, email, address, phone, website, company,"Loading...");
and notify the adapter at end of onResponse() of get_time_to_travel():
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
userData.get(index).setEta(eta);//add this setter to your data object if not exist.
adapter.notifyDataSetChanged();
}
Do you want to get the result of parseJson inside onResponse?
Change the return type of parseJson to UserData, call return userDate; inside try block and return null; in catch block. This will help you catch the result of parseJson from where you are calling it.
Let me know if I did not understand your question properly.
public void getString(final VolleyCallback callback) {
StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
res=response;
callback.onSuccess(res);
}
}...
}}
public interface VolleyCallback{
void onSuccess(String result);
}
Now inside your mainactivity you can do like this.
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
#Override
public void onSuccess(String res){
... //do something
}
});
}

cant set text in postExecute ,Async, Android

I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}

Categories