TextWatcher and SharedPreferences don't recognize Edittext after first value is entered - java

I am encountering a problem in my Android application. The problem is that the Edittext is not being changed with a TextWatcher and a SharedPreferences. IT WORKS FINE WITHOUT A SHAREDPREFERENCES. Here's my code:
public interface CurrencyConverter {
public double convert(String currencyFrom, String currencyTo)
throws Exception;
}
public class YahooCurrencyConverter implements CurrencyConverter {
public double convert(String currencyFrom, String currencyTo)
throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom
+ currencyTo + "=X&f=l1&e=.csv");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpGet, responseHandler);
httpclient.getConnectionManager().shutdown();
return Double.parseDouble(responseBody);
}
}
public String convertvalues(String convertfrom, String convertto) {
double current;
double val = Double.parseDouble(edittextdollars.getText()
.toString());
DecimalFormat df = new DecimalFormat(".##");
YahooCurrencyConverter ycc = new YahooCurrencyConverter();
try {
current = ycc.convert(convertfrom, convertto);
edittexteuros.setText(df.format(val * current));
return "passed";
} catch (Exception e) {
return "passed";
}
}
private void addListenerOnButton2() {
edittextdollars.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String text1 = spinner1.getSelectedItem().toString().trim();
String text2 = spinner2.getSelectedItem().toString().trim();
//TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);
//myOutputBox.setText(s);
String hello = edittextdollars.getText().toString();
if (hello.matches("")) {
img1.setImageDrawable(null);
edittexteuros.setText("");
}
if (edittextdollars.getText().toString().length() != 0) {
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR")) {
try {
convertvalues("USD", "EUR");
getGraph("USD", "EUR");
String hello1 = edittextdollars.getText().toString();
double hello2 = Double.parseDouble(hello1);
String hello3 = edittexteuros.getText().toString();
double hello4 = Double.parseDouble(hello3);
String h = Double.toString(hello4 / hello2);
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("rohit", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(getString(R.string.data1), h);
editor.commit();
} catch(Exception e) {
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("rohit", 0);
String name2 = sharedPrefs.getString(getString(R.string.data1), "not found");
double name3 = Double.parseDouble(name2);
String hello1 = edittextdollars.getText().toString();
double hello2 = Double.parseDouble(hello1);
double ee = hello2 * name3;
//String h = Double.toString(ee);
//edittexteuros.setText(h);
DecimalFormat df = new DecimalFormat(".##");
edittexteuros.setText(df.format(hello2 * name3));
}
}
It works here:
But it doesn't here:
By the way, edittextdollars is the top edittext, edittexteuros is the bottom edittext, spinner1 is the top spinner, and spinner2 is the bottom spinner.
What is wrong here? What problem have I encountered? The reason I use sharedpreferences is when the internet connection is down. As I said, it works flawlessly with internet connection. So what did I add in the SharedPreferences that was wrong?
Any help would be appreciated regarding this problem.

Related

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the string.
public class Main2Activity extends AppCompatActivity {
String getdate, getday, gethijri, gettimezone, getfajr, getsunrise, getduhr, getasr, getsunset, getmaghrib, getisha, getimsak;
public static final String inputFormat = "hh:mm";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat);
String compareFajrOne = "";
String compareFajrTwo = "";
private Date date;
private Date dateComparefajrOne;
private Date dateComparefajrTwo;
private Date dateCompareishaTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailynamazrecord);
Button fajrofer = (Button) findViewById(R.id.fajrada);
final boolean[] ispressed = {false};
Calendar now = Calendar.getInstance();
final int hour = now.get(Calendar.HOUR);
final int minute = now.get(Calendar.MINUTE);
date = parseDateeb(Integer.toString(hour)+":"+ Integer.toString(minute));
dateComparefajrOne = parseDateeb(compareFajrOne);
dateComparefajrTwo = parseDateeb(compareFajrTwo);
fajrofer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, compareFajrOne+"\n"+compareFajrTwo+"\n"+dateComparefajrOne+"\n"+date+"\n"+dateComparefajrTwo, Toast.LENGTH_LONG).show();
if ( dateComparefajrOne.before(date)&& dateComparefajrTwo.after(date)) {
if (ispressed[0]) {
fajrofer.setBackgroundResource(R.drawable.namazoffered);
} else {
fajrofer.setBackgroundResource(R.drawable.ofeer);
}
ispressed[0] = !ispressed[0];
} else {
if (p != null)
showPopup(Main2Activity.this, p);
}
}
});
public class FectchDetails2 extends AsyncTask<String, String, String> {
String data = "";
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL("http://api.aladhan.com/v1/timingsByCity?city=Karachi&country=Pakistan&method=8");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject json = new JSONObject(data);
JSONObject gtimings=json2.getJSONObject("timings");
getfajr = gtimings.getString("Fajr");
getsunrise = gtimings.getString("Sunrise");
getduhr = gtimings.getString("Dhuhr");
getasr = gtimings.getString("Asr");
getsunset = gtimings.getString("Sunset");
getmaghrib = gtimings.getString("Maghrib");
getisha = gtimings.getString("Isha");
getimsak = gtimings.getString("Imsak");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
compareStringOne=getfajr.toString();
compareStringTwo=getsunrise.toString();
}
}
private Date parseDateeb(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
}
String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting.
like:
String compareFajrOne = "05:18";
String compareFajrTwo = "06:40";
Kindly guide me i just want to check that current time is in the range of given times

Android Foursquare how to get the token

I have an app that connects to my Foursquare account. The authentication is successful, but when it comes to showing my username (it shows null) and the list of venues around me, I can't get through it.
What should be done?
Main.java
public class Main extends Activity {
private FoursquareApp mFsqApp;
private ListView mListView;
private NearbyAdapter mAdapter;
private ArrayList<FsqVenue> mNearbyList;
private ProgressDialog mProgress;
public static final String CLIENT_ID = "XXXXXXXXXXXXXXX";
public static final String CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXX";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView nameTv = (TextView) findViewById(R.id.tv_name);
Button connectBtn = (Button) findViewById(R.id.b_connect);
final EditText latitudeEt = (EditText) findViewById(R.id.et_latitude);
final EditText longitudeEt = (EditText)findViewById(R.id.et_longitude);
Button goBtn = (Button) findViewById(R.id.b_go);
mListView = (ListView) findViewById(R.id.lv_places);
mFsqApp = new FoursquareApp(this, CLIENT_ID, CLIENT_SECRET);
mAdapter = new NearbyAdapter(this);
mNearbyList = new ArrayList<FsqVenue>();
mProgress = new ProgressDialog(this);
mProgress.setMessage("Loading data ...");
if (mFsqApp.hasAccessToken()) nameTv.setText("Connected as " + mFsqApp.getUserName());
FsqAuthListener listener = new FsqAuthListener() {
#Override
public void onSuccess() {
Toast.makeText(Main.this, "Connected as " + mFsqApp.getUserName(), Toast.LENGTH_SHORT).show();
nameTv.setText("Connected as " + mFsqApp.getUserName());
}
#Override
public void onFail(String error) {
Toast.makeText(Main.this, error, Toast.LENGTH_SHORT).show();
}
};
mFsqApp.setListener(listener);
//get access token and user name from foursquare
connectBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mFsqApp.authorize();
}
});
//use access token to get nearby places
goBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String latitude = latitudeEt.getText().toString();
String longitude = longitudeEt.getText().toString();
if (latitude.equals("") || longitude.equals("")) {
Toast.makeText(Main.this, "Latitude or longitude is empty", Toast.LENGTH_SHORT).show();
return;
}
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
loadNearbyPlaces(lat, lon);
}
});
}
private void loadNearbyPlaces(final double latitude, final double longitude) {
mProgress.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
mNearbyList = mFsqApp.getNearby(latitude, longitude);
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgress.dismiss();
if (msg.what == 0) {
if (mNearbyList.size() == 0) {
Toast.makeText(Main.this, "No nearby places available", Toast.LENGTH_SHORT).show();
return;
}
mAdapter.setData(mNearbyList);
mListView.setAdapter(mAdapter);
} else {
Toast.makeText(Main.this, "Failed to load nearby places", Toast.LENGTH_SHORT).show();
}
}
};
}
FoursquareApp.java
public class FoursquareApp {
private FoursquareSession mSession;
private FoursquareDialog mDialog;
private FsqAuthListener mListener;
private ProgressDialog mProgress;
private String mTokenUrl;
private String mAccessToken;
public static final String CALLBACK_URL = "https://www.foursquare.com";
private static final String AUTH_URL = "https://foursquare.com/oauth2/authenticate";
private static final String TOKEN_URL = "https://foursquare.com/oauth2/access_token";
private static final String API_URL = "https://api.foursquare.com/v2";
private static final String TAG = "FoursquareApi";
public FoursquareApp(Context context, String clientId, String clientSecret) {
mSession = new FoursquareSession(context);
mAccessToken = mSession.getAccessToken();
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=authorization_code"
+ "&redirect_uri=" + CALLBACK_URL;
String url = AUTH_URL + "?client_id=" + clientId + "&response_type=code" + "&redirect_uri=" + CALLBACK_URL;
FsqDialogListener listener = new FsqDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new FoursquareDialog(context, url, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = 0;
try {
URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
JSONObject jsonObj = (JSONObject) new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
mAccessToken = jsonObj.getString("access_token");
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user name");
int what = 0;
try {
String v = timeMilisToString(System.currentTimeMillis());
URL url = new URL(API_URL + "/users/self?oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject resp = (JSONObject) jsonObj.get("response");
JSONObject user = (JSONObject) resp.get("user");
String firstName = user.getString("firstName");
String lastName = user.getString("lastName");
Log.i(TAG, "Got user name: " + firstName + " " + lastName);
mSession.storeAccessToken(mAccessToken, firstName + " " + lastName);
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 == 1) {
if (msg.what == 0) {
fetchUserName();
} else {
mProgress.dismiss();
mListener.onFail("Failed to get access token");
}
} else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(FsqAuthListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public void authorize() {
mDialog.show();
}
public ArrayList<FsqVenue> getNearby(double latitude, double longitude) throws Exception {
ArrayList<FsqVenue> venueList = new ArrayList<FsqVenue>();
try {
String v = timeMilisToString(System.currentTimeMillis());
String ll = String.valueOf(latitude) + "," + String.valueOf(longitude);
URL url = new URL(API_URL + "/venues/search?ll=" + ll + "&oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray groups = (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length = groups.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
JSONObject group = (JSONObject) groups.get(i);
JSONArray items = (JSONArray) group.getJSONArray("items");
int ilength = items.length();
for (int j = 0; j < ilength; j++) {
JSONObject item = (JSONObject) items.get(j);
FsqVenue venue = new FsqVenue();
venue.id = item.getString("id");
venue.name = item.getString("name");
JSONObject location = (JSONObject) item.getJSONObject("location");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.valueOf(location.getString("lat")));
loc.setLongitude(Double.valueOf(location.getString("lng")));
venue.location = loc;
venue.address = location.getString("address");
venue.distance = location.getInt("distance");
venue.herenow = item.getJSONObject("hereNow").getInt("count");
venue.type = group.getString("type");
venueList.add(venue);
}
}
}
} catch (Exception ex) {
throw ex;
}
return venueList;
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
private String timeMilisToString(long milis) {
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public interface FsqAuthListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
FsqVenue.java
public class FsqVenue {
public String id;
public String name;
public String address;
public String type;
public Location location;
public int direction;
public int distance;
public int herenow;
}
FoursquareDialog.java
public class FoursquareDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private FsqDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Foursquare-WebView";
public FoursquareDialog(Context context, String url, FsqDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
CookieSyncManager.createInstance(getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.foursquare_icon);
mTitle = new TextView(getContext());
mTitle.setText("Foursquare");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFF0cbadf);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(FoursquareApp.CALLBACK_URL)) {
String urls[] = url.split("=");
mListener.onComplete(urls[1]);
FoursquareDialog.this.dismiss();
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
FoursquareDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
public interface FsqDialogListener {
public abstract void onComplete(String accessToken);
public abstract void onError(String error);
}
}
FoursquareSession.java
public class FoursquareSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String SHARED = "Foursquare_Preferences";
private static final String FSQ_USERNAME = "username";
private static final String FSQ_ACCESS_TOKEN = "access_token";
public FoursquareSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(String accessToken, String username) {
editor.putString(FSQ_ACCESS_TOKEN, accessToken);
editor.putString(FSQ_USERNAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(FSQ_ACCESS_TOKEN, null);
editor.putString(FSQ_USERNAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(FSQ_USERNAME, null);
}
public String getAccessToken() {
return sharedPref.getString(FSQ_ACCESS_TOKEN, null);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.londatiga.fsq"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Main" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses- permission>
</manifest>

EditText mask with 3 decimal places in java [android]

i'm newbie in Android and i want to do a mask for an EditText with a decimal number with 3 decimal places(ex: 0.658), i need a mask that user doesn't need write the ".", only the numbers, like a conventional mask for currency.
I'm trying create a TextWatcher based in this:
public static TextWatcher currency(final EditText editText) {
return new TextWatcher() {
String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
editText.removeTextChangedListener(this);
String cleanString = s.toString();
if(count != 0) {
String substr = cleanString.substring(cleanString.length() - 2);
if (substr.contains(".") || substr.contains(",")) {
cleanString += "0";
}
}
cleanString = cleanString.replaceAll("[R$,.]", "");
double parsed = Double.parseDouble(cleanString);
Locale locale = new Locale("pt", "BR");
String formatted = NumberFormat.getCurrencyInstance(locale).format((parsed / 100));
formatted = formatted.replaceAll("[R$]", "");
current = formatted;
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}
But without success.
There are a better way to do this?
Thanks.
Try to use MaskedEditText from github.
I had a similar problem. So I started looking for any implementation of TextWatcher. I finally decided to build my own:
public class BrRealMoneyTextWatcher implements TextWatcher {
private static final Locale DEFAULT_LOCALE = new Locale("pt", "BR");
private static DecimalFormat NUMBER_FORMAT = (DecimalFormat) DecimalFormat.getCurrencyInstance(DEFAULT_LOCALE);
private static final int FRACTION_DIGITS = 2;
private static final String DECIMAL_SEPARATOR;
private static final String CURRENCY_SIMBOL;
static {
NUMBER_FORMAT.setMaximumFractionDigits(FRACTION_DIGITS);
NUMBER_FORMAT.setMaximumFractionDigits(FRACTION_DIGITS);
NUMBER_FORMAT.setParseBigDecimal(true);
DECIMAL_SEPARATOR = String.valueOf(NUMBER_FORMAT.getDecimalFormatSymbols().getDecimalSeparator());
CURRENCY_SIMBOL = NUMBER_FORMAT.getCurrency().getSymbol(DEFAULT_LOCALE);
}
final EditText target;
public BrRealMoneyTextWatcher(EditText target) {
this.target = target;
}
private boolean updating = false;
#Override
public void onTextChanged(CharSequence s, int start, int before, int after) {
if (updating) {
updating = false;
return;
}
updating = true;
try {
String valueStr = formatNumber(fixDecimal(s.toString()));
BigDecimal parsedValue = ((BigDecimal) NUMBER_FORMAT.parse(valueStr));
String value = NUMBER_FORMAT.format(parsedValue);
target.setText(value);
target.setSelection(value.length());
} catch (ParseException | NumberFormatException ex) {
throw new IllegalArgumentException("Erro ao aplicar a máscara", ex);
}
}
private String formatNumber(String originalNumber) {
String number = originalNumber.replaceAll("[^\\d]", "");
switch(number.length()) {
case 0 :
number = "0" + DECIMAL_SEPARATOR + "00";
break;
case 1 :
number = "0" + DECIMAL_SEPARATOR + "0" + number;
break;
case 2 :
number = "0" + DECIMAL_SEPARATOR + number;
break;
default:
number = number.substring(0, number.length() - 2) + DECIMAL_SEPARATOR + number.substring(number.length() - 2);
break;
}
return CURRENCY_SIMBOL + number;
}
private String fixDecimal(String number) {
int dotPos = number.indexOf('.') + 1;
int length = number.length();
return (length - dotPos < FRACTION_DIGITS) ? fixDecimal(number + "0") : number;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
}
I hope it helps somebody else.

Android Database with MySQL Where Clause

I'm new in Android Programming, and I'm stuck in a middle of SQL query with Where condition. I want to store my data from database into an arraylist. But my script's always fail with Error message. Anyone have a clue? Thanks before
SearchActivity.java
public class SearchActivity extends Activity {
private RadioGroup radiosexGroup;
private RadioButton radiosexButton;
public SeekBar seekBar;
public ArrayList<detailKosan> listKosan = new ArrayList<>();
int progress;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.1.133/php_kukelkos/search_kosan.php";
// JSON Node names
private static final String TAG_KOSAN = "arrayKosan";
private static final String TAG_ID = "id";
private static final String TAG_NAMAKOS = "namaKosan";
private static final String TAG_ALAMAT = "alamat";
private static final String TAG_SEX = "gender";
private static final String TAG_TLP = "tlp";
private static final String TAG_HARGA = "harga";
private static final String TAG_KAMAR = "jmlKamar";
private static final String TAG_FASILITAS = "fasilitas";
private static final String TAG_KET = "keterangan";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
// contacts JSONArray
JSONArray arrayKosan = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
textView.setText("Rp 0 - Rp 0");
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue * 500000;
textView.setText("Rp 0 - Rp " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
textView.setText("Rp 0 - Rp " + progress);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//Fungsi Button Search
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
searchKosan();
Intent menuSearch = new Intent(SearchActivity.this, ListKosanActivity.class);
startActivity(menuSearch);
finish();
}
});
public void searchKosan (){
int selected = radiosexGroup.getCheckedRadioButtonId();
radiosexButton = (RadioButton) findViewById(selected);
String buttonradio = radiosexButton.getText().toString();
String msg = "";
String keyval[][]= {{"harga", String.valueOf(progress)},{"gender", buttonradio}};
AsyncTask<String, Void, String> asycn = new myAsyncData(SearchActivity.this, keyval, "Loading...");
asycn.execute(url);
String data = "";
boolean state = false;
try {
JSONObject jobj = null;
try {
data = asycn.get().toString();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jobj = new JSONObject(data);
msg = jobj.getString("message").toString();
state = jobj.getBoolean("state");
// Getting JSON Array node
arrayKosan = jobj.getJSONArray(TAG_KOSAN);
/**
* Updating parsed JSON data into Arraylist_detail
**/
for (int i = 0; i < arrayKosan.length(); i++) {
try {
JSONObject c = arrayKosan.getJSONObject(i);
int id = Integer.parseInt(TAG_ID);
String namaKosan = c.getString(TAG_NAMAKOS);
String alamat = c.getString(TAG_ALAMAT);
String sex = c.getString(TAG_SEX);
String tlp = c.getString(TAG_TLP);
int harga = c.getInt(TAG_HARGA);
String kamar = c.getString(TAG_KAMAR);
String fasilitas = c.getString(TAG_FASILITAS);
String ket = c.getString(TAG_KET);
String lat = c.getString(TAG_LAT);
Double latt = Double.parseDouble(lat);
String lng = c.getString(TAG_LNG);
Double lngg = Double.parseDouble(lng);
LatLng PosisiMarker = new LatLng(latt, lngg);
listKosan.add(new detailKosan(id, namaKosan, alamat, sex, tlp, harga, kamar, fasilitas, ket, latt, lngg));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String title = (!state) ? "Error" : "Success";
if(title.equals("Success")) {
Toast.makeText(getApplicationContext(), msg , Toast.LENGTH_LONG).show();
finish();
Intent i = new Intent(SearchActivity.this, ListKosanActivity.class);
startActivity(i);
}
else {
AlertDialog.Builder b = new AlertDialog.Builder(SearchActivity.this);
b.setTitle(title);
b.setMessage(msg);
b.setNegativeButton("Dismiss", null);
AlertDialog a = b.create();
a.show();
}
}
}
And this is my .php file
<?php
if ($_POST) {
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$harga = $_POST["harga"];
$gender = $_POST["gender"];
$fasilitas = $_POST["fasilitas"];
if(!empty($harga)&&!empty($gender)) {
$ins= mysql_query("SELECT * from tbkosan where harga <='".$harga."' and gender = '".$gender"'");
if (mysql_num_rows($ins> 0) {
$response["state"] = true;
$response["message"] = "Success";
$response["arrayKosan"] = array();
while ($row = mysql_fetch_array($ins)) {
// temp user array
$dataa= array();
$dataa["id"] = $row["id"];
$dataa["namaKosan"] = $row["namaKosan"];
$dataa["alamat"] = $row["alamat"];
$dataa["gender"] = $row["gender"];
$dataa["tlp"] = $row["tlp"];
$dataa["harga"] = $row["harga"];
$dataa["jmlKamar"] = $row["jmlKamar"];
$dataa["fasilitas"] = $row["fasilitas"];
$dataa["keterangan"] = $row["keterangan"];
$dataa["lat"] = $row["lat"];
$dataa["lng"] = $row["lng"];
// push single product into final response array
array_push($result["arrayKosan"], $dataa);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "Data tidak ada";
}
}
else {
$response["success"] = 0;
$response["message"] = "Harap isi data search terlebih dulu!";
echo json_encode($result);
}
}
?>
and this is my ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
and the result is :
alert box with no message, and dissmiss button (sorry i cant post a pic hehe)
mysql_query("SELECT * from tbkosan where harga <='$harga' and gender='$gender'");
I had the same problem AS THIS one of yours i have chosen to use volley library on android part where it helped me to pass input variable to php where clause
refer to this post and check the answer:
How to parse multiple rows with jsonOject
or follow the followithing tutorial watch function called function StoreUserInfo and refer to second part to activity called RegisterActivity.java these can help you to fetch using where clause:
https://www.androidtutorialpoint.com/androidwithphp/android-login-and-registration-with-php-mysql/

Format currency string using EditText in Android

I'm trying to format the input value of an EditText in Android, I want to format the input in currency value, I' ve tried the following:
EditText minimo = (EditText) view.findViewById(R.id.minimo);
Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
minimo.setText("", TextView.BufferType.valueOf(String.valueOf(fmt.format(TextView.BufferType.EDITABLE))));
Log:
java.lang.IllegalArgumentException: Bad class: class android.widget.TextView$BufferType
try this :
set TextChangedListner as :
minimo.addTextChangedListener(new NumberTextWatcher(minimo));
create custom TextWatcher as:
class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}

Categories

Resources