Hi I am having a bit of trouble with the AsyncTask class for android. Here is my code for logging in a user on Parse. There are different cases such when the password is incorrect, etc.
My problem is that the error checking works and the different cases work fine but the progressDialog button will not go away after i close the alertdialog... Can anybody help me with this?
Here is my code
private class LoadTask extends AsyncTask<Map<String, String>, Integer, Void> {
// called before running code in a separate thread
private Result resultCode;
private boolean isSuccess;
private ProgressDialog progressDialog;
public LoadTask(Activity activity) {
onPreExecute();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TitlePage.this,
getString(R.string.login_progress_title),
getString(R.string.login_progress_message), false, false);
}
#Override
protected Void doInBackground(Map<String, String>... arg0) {
// Try to login with the given inputs
ParseUser user = null;
Map<String, String> argMap = arg0[0];
try {
user = ParseUser.logIn(argMap.get("username"), argMap.get("password"));
} catch (ParseException e) {
e.fillInStackTrace();
boolean errorOccured = false;
List<ParseObject> usernameResults = new ArrayList<ParseObject>();
List<ParseObject> passwordResults = new ArrayList<ParseObject>();
ParseQuery query = ParseUser.getQuery();
// try to find the username that the user typed in
query.whereEqualTo("username", argMap.get("username"));
try {
query.count();
usernameResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the username
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// try to find the password that the user typed in
// associated with that username
query.whereEqualTo("username", argMap.get("username"));
query.whereEqualTo("password", argMap.get("password"));
try {
query.count();
passwordResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the password
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// figure out the error
if (errorOccured) {
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
if ((usernameResults.size() == 0) && (passwordResults.size() == 0)) {
resultCode = Result.BOTH_INCORRECT;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if ((usernameResults.size() == 0) && (passwordResults.size() != 0)) {
resultCode = Result.USERNAME_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if ((usernameResults.size() != 0) && (passwordResults.size() == 0)) {
resultCode = Result.PASSWORD_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
// unexpected error
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
isSuccess = false;
return null;
}
// Check for verified email
boolean emailVerified = user.getBoolean("emailVerified");
if (!emailVerified) {
resultCode = Result.EMAIL_NOT_VERIFIED;
ParseUser.logOut();
}
isSuccess = true;
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
if (isSuccess) {
TitlePage.this.setReturnStatus(isSuccess);
} else {
System.out.println("THIS IS RESULT CODE " + resultCode);
if (resultCode == Result.UNEXPECTED_ERROR) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
} else if (resultCode == Result.BOTH_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if (resultCode == Result.USERNAME_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if (resultCode == Result.PASSWORD_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
buildAlertDialog(R.string.error_login_title, R.string.error_login_verif);
}
TitlePage.this.setReturnStatus(isSuccess);
}
}
}
And here is my code to run the async task in my main activity
Map<String, String> argMap = new HashMap<String, String>();
argMap.put("username", usernameString);
argMap.put("password", passwordString);
LoadTask task = new LoadTask(this);
task.execute(argMap);
private void buildAlertDialog(final int title, final int message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.close_alert, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
// if this button is clicked, close the dialog box
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show the message
alertDialog.show();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
Thank you
we can make progress dialog as same in the following example :
#Override
protected void onPreExecute() {
loadingDailog = new ProgressDialog(context,AlertDialog.THEME_HOLO_LIGHT);
((ProgressDialog) loadingDailog).setIndeterminate(true);
((ProgressDialog) loadingDailog).setProgressStyle(ProgressDialog.THEME_HOLO_LIGHT);
loadingDailog.setMessage("Loading...");
loadingDailog.show();
}
when you want to disapear this bar:
if (loadingDailog != null && loadingDailog.isShowing()) {
loadingDailog.dismiss();
}
Related
I'm using google sheets API with which I am creating new google sheets using sheets API, But this is using the account in which the sheet's API is enabled, If I give my app to another user he cannot create a new sheet using his Gmail. I have the API key, Is it possible to create sheets without selecting Gmail accounts
GoogleAccountCredential mCredential;
private static final String BUTTON_TEXT = "Call Google Sheets API";
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
private void getResultsFromApi() {
Log.d(TAG, "getResultsFromApi: ");
if (!isGooglePlayServicesAvailable()) {
Log.d(TAG, "getResultsFromApi: 1");
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
Log.d(TAG, "getResultsFromApi: 2");
chooseAccount();
} else if (!isDeviceOnline()) {
Log.d(TAG, "getResultsFromApi: No network connection available.");
} else {
// x();
try {
new MakeRequestTask(mCredential).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
#AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
Log.d(TAG, "chooseAccount: 1");
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
Log.d(TAG, "chooseAccount: 2");
// Start a dialog from which the user can choose an account
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
// Request the GET_ACCOUNTS permission via a user dialog
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.sheets.v4.Sheets mService = null;
private Exception mLastError = null;
public MakeRequestTask(GoogleAccountCredential credential) throws IOException {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.sheets.v4.Sheets.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Sheets API Android Quickstart")
.build();
new Thread() {
#Override
public void run() {
try {
if (consurEtSurname.getText().toString().isEmpty()) {
consurEtSurname.setError("Please provide survey name!");
consurEtSurname.requestFocus();
} else {
Spreadsheet spreadsheet = new Spreadsheet()
.setProperties(new SpreadsheetProperties()
.setTitle(consurEtSurname.getText().toString()));
spreadsheet = mService.spreadsheets().create(spreadsheet)
.setFields("spreadsheetId")
.execute();
Makecolums(mService,spreadsheet.getSpreadsheetId());
upload(spreadsheet.getSpreadsheetId());
Log.d(TAG, "onCreate: " + spreadsheet.getSpreadsheetId());
Log.d(TAG, "run: " + spreadsheet.getSpreadsheetUrl());
}
// writeToSheetUsingApi(mService,spreadsheet.getSpreadsheetId());
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
// catch (GeneralSecurityException e) {
// e.printStackTrace();
// }
}
}.start();
}
//
// #Override
// protected List<String> doInBackground(Void... params) {
// try {
// return getDataFromApi();
// } catch (Exception e) {
// mLastError = e;
// cancel(true);
// return null;
// }
// }
//
//
// private List<String> getDataFromApi() throws IOException {
// String spreadsheetId = "196tcE1k5RuqTdGSBDpTFAI5h3m_dwXR875Q3csmi4ko";
// String range = "A1:X1";
//
// List<String> results = new ArrayList<String>();
// ValueRange response = this.mService.spreadsheets().values()
// .get(spreadsheetId, range)
// .execute();
//
// List<List<Object>> values = response.getValues();
// if (values != null) {
// for (int i = 0; i < values.size(); i++) {
// results.add(values.get(i).get(0) + ", " + values.get(i).get(1));
// }
// }
// return results;
// }
#Override
protected List<String> doInBackground(Void... voids) {
return null;
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
Log.d(TAG, "\"No results returned.\": ");
} else {
output.add(0, "Data retrieved using the Google Sheets API:");
Log.d(TAG, TextUtils.join("\n", output));
Log.d("TagOutputPost", TextUtils.join("\n", output));
}
}
#Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
REQUEST_AUTHORIZATION);
} else {
Log.d(TAG, "The following error occurred:\n"
+ mLastError.getMessage());
}
} else {
Log.d(TAG, "Request onCancelled: ");
}
}
}
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
Log.d(TAG, "This app requires Google Play Services. Please install " +
"Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
ConfirmSurvey.this,
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
#Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
#Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
I'm trying to get e-mail addresses from parse User class,
here I'm trying to get other users email id's when logging in a
user, logged in users email id is showing but other users email ids
are not showing always null
I try use master key also, still not working ,
below is my java code.
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
protected TextView individualOrganization;
Button emailPerson;
Button callPerson;
Button callPersonTelephone;
ParseObject personObject;
String personEmail;
String personNumber;
String personNumberTelephone;
ParseQuery query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_individual);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.coporateSector);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
individualOrganization =(TextView) findViewById(R.id.individualOrganization);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseUser> query = ParseUser.getQuery();
//query.put("useMasterKey", true);
query.setLimit(2000);
query.include("email");
query.getInBackground(objectId, new GetCallback<ParseUser>() {
#Override
public void done(final ParseUser object, com.parse.ParseException e) {
if (e == null) {
personObject = object;
String username = object.getString("firstname");
txtv.setText(username + " " + object.getString("lastname"));
String position = object.getString("position");
txtv1.setText(position);
String organizationName = object.getString("organizationName");
individualOrganization.setText(organizationName);
URL url = null;
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv2);
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv3);
// try{
// JSONObject jsonObject = parseObjectToJson(object);
// Log.d("Object", jsonObject.toString());
// Log.d("Email", "+" + object.get("email"));
// personNumber = jsonObject.getString("telephone");
// //personEmail = jsonObject.getString("email");
// personEmail= object.getEmail();
//
// }catch (JSONException je){
// }catch (ParseException pe){
// } catch (com.parse.ParseException e1) {
// e1.printStackTrace();
// }
} else {
}
callPerson = (Button) findViewById(R.id.individualMobile) ;
personNumber = object.getString("mobile");
callPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+personNumber));
startActivity(i);
}
});
if(personNumber==null || personNumber.equals("") || personNumber.equals(" ")){
callPerson.setClickable(false);
callPerson.setEnabled(false);
callPerson.setVisibility(View.GONE);
}
else{
callPerson.setEnabled(true);
callPerson.setClickable(true);
callPerson.setVisibility(View.VISIBLE);
}
callPersonTelephone = (Button) findViewById(R.id.individualTelephone);
personNumberTelephone = object.getString("telephone");
callPersonTelephone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+personNumberTelephone));
startActivity(i);
}
});
if(personNumberTelephone==null || personNumberTelephone.equals("") || personNumberTelephone.equals(" ") || personNumberTelephone.equals("6855")){
callPersonTelephone.setClickable(false);
callPersonTelephone.setEnabled(false);
callPersonTelephone.setVisibility(View.GONE);
}
else{
callPersonTelephone.setEnabled(true);
callPersonTelephone.setClickable(true);
callPersonTelephone.setVisibility(View.VISIBLE);
}
emailPerson = (Button)findViewById(R.id.individualEmail);
object.put("useMasterKey", true);
personEmail= object.getString("email");
emailPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setData(Uri.parse("mailto:"));
i.setType("plain/text");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {personEmail});
startActivity(i);
}
});
if(personEmail==null || personEmail.equals("") || personEmail.equals(" ")){
emailPerson.setClickable(false);
emailPerson.setEnabled(false);
emailPerson.setVisibility(View.GONE);
}
else{
emailPerson.setEnabled(true);
emailPerson.setClickable(true);
emailPerson.setVisibility(View.VISIBLE);
}
individualOrganization.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String organizationID = personObject.getString("organizationID");
if(organizationID == null || organizationID.equals("")){
Toast.makeText(SingleIndividual.this, "Sorry No Organization Available!", Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(getApplicationContext(), SingleCorporate.class);
i.putExtra("objectId", organizationID);
i.putExtra("image", organizationID);
startActivity(i);
}
}
});
}
});
}
private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {
JSONObject jsonObject = new JSONObject();
parseObject.fetchIfNeeded();
Set<String> keys = parseObject.keySet();
for (String key : keys) {
Object objectValue = parseObject.get(key);
if (objectValue instanceof ParseObject) {
jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
} else if (objectValue instanceof ParseRelation) {
} else {
jsonObject.put(key, objectValue.toString());
}
}
return jsonObject;
}
}
Master Key can only be used from your server code, not client code. Making your users public read is an option, albeit a very poor one. It would be a better idea to have a cloud code function in which you validate a user session, ensure they're able to access this information, and do the query from there, using the master key.
I am trying to create an app. I want to add search by address on google map in fragment Using the following code-
public class Search extends Fragment implements OnItemClickListener{
private final String TAG = this.getClass().getSimpleName();
MainActivity main=null;
PlacesTask placesTask = null ;
DownloadTask downloadTask=null;
LatLng latLng;
GoogleMap mMap;
Marker CurrentMarker,FindMarker;
AutoCompleteTextView autoCompView=null;
Button findbtn = null;
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
//------------ make your specific key ------------
private static final String API_KEY = "**************************************";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.search, container,false);
autoCompView = (AutoCompleteTextView) view.findViewById(R.id.editplace);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
autoCompView.setOnItemClickListener(this);
findbtn =(Button) view.findViewById(R.id.findbtn);
findbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = autoCompView.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
Log.e(TAG, "login button is clicked");
}
}
});
return view;
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getActivity());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0],3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address>addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getActivity(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker=mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
double mLatitude=address.getLatitude();
double mLongitude=address.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=********************************");
Log.d("Map", "<><>api: " + sb.toString());
//query places with find location
placesTask.execute(sb.toString());
//for direction Route
LatLng origin = CurrentMarker.getPosition();
LatLng dest = FindMarker.getPosition();
String url = getDirectionsUrl(origin, dest);
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Toast.makeText(getActivity(), " Location found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
return false;
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getActionBar().setTitle("IQWINER");
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position,
long id) {
// TODO Auto-generated method stub
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
[enter error description here][2]
how to implement search by address location on Google Map in fragment.Please tell me..
enter error description here
You can do it in another way.
You can generate an api key along with Google maps & Google places api in your developers console (Click on the circled link and Enable the api)
You can call the api like below with your AutoCompleteView onclick listener or any other listener of your wish
private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;// declare this globally
//Call this on your listener method
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
This will open the Google place search screen and you can get the result like below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
mSearchPlace = place;
mSearchText.setText(String.valueOf(place.getName()));
// You will get Lat,Long values here where you can use it to move your map or reverse geo code it.
LatLng latLng = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
} else if (resultCode == getActivity().RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
Hope this helps.
Every time I click on:
assist_update_btn
I the textview should be update with text from a different string value however it never appears to do anything when I click assist_update_btn.
Any input is greatly appreciated.
SOURCE:
public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
public static int count;
AlertDialog mErrorAlert = null;
int version;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
private Button assist_update_btn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
handler = new XmlParserHandlerFinal();
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(this);
} else {// ICS and up
// task.execute();
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
task = new NetworkTask();
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}
}
}
public void onClick(View v) {
if (v.equals(assist_update_btn)) {
// Update button for versions lower than ICS is selected
// setContentView(R.layout.updating);
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
// finish();
} else if (v.getId() == R.id.assist_update_btn) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
//finish();
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
// AsyncTask to call web service
class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content on the console
System.out.println (strLine);
System.out.println (strLine);
in.close();
}
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
return stream;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2], progress[3], progress[4]);
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the ArrayLists
success();
assistUpdate();
//setContentView(R.layout.assist_update);
}
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener(this);
}
private void setProgressImgView(Integer imageViewId1, Integer imageViewId2, Integer imageViewId3, Integer imageViewId4, Integer imageViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview1.setBackgroundResource(imageViewId1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview1.setBackgroundResource(imageViewId2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview1.setBackgroundResource(imageViewId3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview1.setBackgroundResource(imageViewId4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setBackgroundResource(imageViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
//finish();
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
//System.out.println("testing123");
for(int i = 0; i < nameArr.size()-1; i++){
System.out.println(nameArr.get(i));
}
for(int i = 0; i < ApnArr.size()-1; i++){
System.out.println(ApnArr.get(i));
}
}
}
Try doing like this
public void onClick(View v) {
if (v.getId() == R.id.assist_update_btn) {
//Your code
}
else if (v.getId() == R.id.assist_instr_btn) {
//Your code
}
}
You are using
if (v == assist_update_btn)
when you should be using
if (v.equals(assist_update_btn)).
I personally think it's more robust to create a separate OnClickListener for each button instead of handling all buttons with one method.
Change:
public void onClick(View v) {
if (v == assist_update_btn) {
to:
public void onClick(View v) {
if (v.getId() == R.id.assist_update_btn) {
and your problem should be long gone.
Initialize TextView in assistUpdate(). Declare tv as a class member.
#Override // missing override annotation
public void onClick(View v) {
switch(v.getId())
{
case R.id.assist_update_btn :
// do something. assist_update_btn click code here
break;
case R.id.mAssistInstrButton :
// do domething . mAssistInstrButton click code here
break;
}
I see you have setContenView twice for the same activitty. I don't think its necessary.
Edit :
You have a for loop in doInbackground() you also call publishProgress more than once and you have multiple try catch block.
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
I am confused as to what your doing. But i strongly suggest you to rethink your design.
Hello below is a method where fileUpload method is called and after uploading files i want to delete the synchronized object and i did so. and now i have to reload the page by calling fillRecipients() method, what is does is it lists all the information from the database and shows in the listView. Since i have used the thread it doesnot allow me to put fillRecipeints inside the thread but i want it at line no 230[commented below as Line No 230] below
This is my Synchronize method:
public void synchronize(final String id){
dialog = ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//uploading.setText("uploading started.....");
//dialog.show();
}
});
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
//Line NO 230 here i want to add fillRecipients() method
}
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
dialog.dismiss();
}
}
cData.close();
mDbHelper.close();
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
This is my fillRecipeints() method:
private void fillRecipients(){
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor==null){
System.out.println("empty cursor");
}
else{
String [] from = new String[]{MunchaDbAdapter.FLD_RECIPIENT_ID};
int [] to = new int[]{R.id.text1};
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this, R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}
can any body help me?
public void synchronize(final String id) {
new UploadAsync.execute();
}
//async class to do task in background and notify UI after completion of task in onPost()
class UploadAsync extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog = null;
boolean isUploaded = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
}
#Override
protected Void doInBackground(Void... params) {
try{
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
isUploaded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
cData.close();
mDbHelper.close();
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//close dialog
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
if(isUploaded){
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
fillRecipients();
}
}
}
private void fillRecipients() {
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor == null) {
System.out.println("empty cursor");
} else {
String[] from = new String[] { MunchaDbAdapter.FLD_RECIPIENT_ID };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this,
R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}