I'm implementing a simple Geo-coding example where user enters an address and gets its latitude and longitude.
addr = Area_edtxt.getText().toString();
try {
list_addr = gc.getFromLocationName(addr, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Location lookup failed", e.getMessage());
}
if (list_addr != null && list_addr.size() > 0 ){
latitude = list_addr.get(0).getLatitude();
longitude = list_addr.get(0).getLongitude();
latitude_edtxt.setText(latitude.toString());
longitude_edtxt.setText(longitude.toString());
}else {
latitude_edtxt.setText("Address not found");
}
but shows me error : Unable to open stack trace file '/data/anr/traces.txt' : Permission denied.
For a quick try you could use an AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
private class GeocodeTask extends AsyncTask<String, Integer, List> {
protected Long doInBackground(String... address) {
try {
return gc.getFromLocationName(address[0], 1)
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Location lookup failed", e.getMessage());
}
}
protected void onPostExecute(List result) {
if (list_addr != null && list_addr.size() > 0 ){
latitude = list_addr.get(0).getLatitude();
longitude = list_addr.get(0).getLongitude();
latitude_edtxt.setText(latitude.toString());
longitude_edtxt.setText(longitude.toString());
}else {
latitude_edtxt.setText("Address not found");
}
}
}
new GeocodeTask().execute(addr);
Related
I've recently migrated from android webview to Crosswalk 13. The only issue i've run into is telling the XWalkView to load content from the app cache.
In my android webview implementation i had implmemented as this
//check connection on a loop
public void CheckConnectivityTask(){
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
//runs every 0.5s
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
CheckConnectivity(true);
}
}.execute();
}
public void CheckConnectivity(boolean recursiveTask){
cm = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
if(cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()){
Log.v("ConnectivityGG", "IS CONNECTED");
mainWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
else{
mainWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
if(recursiveTask){
CheckConnectivityTask();
}
}
As getSettings() has now been removed from XWalk 13, I've been trying to set this using XWalkSettings
inside OnCreate in MainActivity
xWalkSettings = new XWalkSettings(mainWebView.getContext(), null , false);
xWalkSettings.setAppCacheEnabled(true);
and then modifying my looped task
public void CheckConnectivity(boolean recursiveTask){
cm = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
if(cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()){
xWalkSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
}
else{
xWalkSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
if(recursiveTask){
CheckConnectivityTask();
}
}
However any attempt to load cached pages fails with "Internet connection has been lost" alert dialogue. Am I instantiating the XWalkSettings instance incorrectly, or is there another way of achieving this?
I found a way from this link. And changed it slightly. Basically need to use reflection to get access to a non public (afaik) method.
Method ___getBridge;
try {
___getBridge = XWalkView.class.getDeclaredMethod("getBridge");
___getBridge.setAccessible(true);
XWalkViewBridge xWalkViewBridge = null;
xWalkViewBridge = (XWalkViewBridge)___getBridge.invoke(mainWebView);
xWalkSettings = xWalkViewBridge.getSettings();
xWalkSettings.setAppCacheEnabled(true);
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
If there's a nicer, cleaner way of doing this I'd love to know :)
Crosswalk didn't expose setCacheMode API before, but it has been exposed recently, please see this JIRA, https://crosswalk-project.org/jira/browse/XWALK-6832
It should be available in Crosswalk 21, you can use it like below:
mXWalkView.getSettings().setCacheMode(XWalkSettings.LOAD_NO_CACHE);
So, enjoy it.. :)
I have two objects, a establishment object that belongs to a deal object that can be voted upon. If I up/down vote the same deal multiple times, the seventh time I vote the query just sits and does not do anything. The app does not crash, but it also does not save. If I go into another activity that requires a parse.com query that query also will not work. Here is my up vote logic (down voting is identical).
Assume all vars used are initialized before onCreate().
Are my queries getting backed up in a pipe somewhere?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upVoteButton = (Button) findViewById(R.id.deal_up_vote_button);
upVoteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new UpVoteTask().execute();
}
});
}
// visually changes buttons if they are selected
private void setButtons(Boolean queryDb) {
if (queryDb == true) {
queryParse();
}
// if deal found correctly
if (deal != null) {
// if user found correctly
if (dealVoteUser != null) {
if (dealVoteUser.get("vote").toString().equals("0")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(true);
} else if (dealVoteUser.get("vote").toString().equals("1")) {
upVoteButton.setPressed(true);
downVoteButton.setPressed(false);
} else if (dealVoteUser.get("vote").toString().equals("2")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(false);
}
}
}
}
// queries parse and populates vars
private void queryParse(){
ParseQuery<ParseObject> queryDeal = ParseQuery.getQuery("Deal");
queryDeal.whereEqualTo("objectId", deal_id);
try {
deal = queryDeal.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseQuery<ParseObject> queryDealVoteUser = ParseQuery
.getQuery("deal_vote_users");
queryDealVoteUser.whereEqualTo("deal", deal).whereEqualTo("user",
ParseUser.getCurrentUser());
try {
dealVoteUser = queryDealVoteUser.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// UpVoteTask AsyncTask
private class UpVoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
upVoteProgressDialog = new ProgressDialog(DealsDetailsActivity.this);
// Set progressdialog message
upVoteProgressDialog.setMessage("Saving...");
upVoteProgressDialog.setIndeterminate(false);
// Show progressdialog
upVoteProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
queryParse();
// if deal found correctly
if (deal != null) {
// if user has not voted yet
if (dealVoteUser == null) {
// create new and assign vote to 1
dealVoteUser = new ParseObject("deal_vote_users");
dealVoteUser.put("deal", deal);
dealVoteUser.put("user", ParseUser.getCurrentUser());
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
// if user already down voted
} else if (dealVoteUser.get("vote").toString().equals("0")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes") - 1;
// if user already up voted
} else if (dealVoteUser.get("vote").toString().equals("1")) {
// already voted up, remove vote
dealVoteUser.put("vote", 2);
up_votes = deal.getInt("up_votes") - 1;
down_votes = deal.getInt("down_votes");
// if user already voted but cleared vote
} else if (dealVoteUser.get("vote").toString().equals("2")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
}
// calculate overall rating percentage
if ((up_votes + down_votes) != 0) {
rating = (up_votes / (up_votes + down_votes)) * 100;
} else if ((up_votes == 0) && (down_votes == 0)) {
rating = 0;
} else {
rating = 50;
}
deal.put("rating", rating);
deal.put("up_votes", up_votes);
try {
deal.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dealVoteUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// deal not found problem
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// visually change buttons without querying db
setButtons(false);
//remove progress dialogue
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
}
}
Use the saveInBackground method - it will do the same as save, but also save it to your application's cache so that you won't get different values while the data is being saved, so it won't have any apparent effect on your application. It's the best method to save or find (it has a 'sister' method named findInBackground). It acts like an Async task and does not clog your main thread.
I switched all parse calls over to ._____InBackground() and I moved the save logic to onPause(). This way I am not making multiple save calls to parse if the user decides to change their vote multiple times.
Please help me in getting the user details for the current user in the BoxApi v2 for android
The code which I am using the user details is as follows:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BoxAndroidClient client = null;
if (Activity.RESULT_OK != AUTH_REQUEST) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
} else {
BoxAndroidOAuthData oauth = data
.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
BoxAndroidOAuthData moath = data
.getParcelableExtra(OAuthActivity.USER_SERVICE);
client = new BoxAndroidClient(HelloWorldApplication.CLIENT_ID,
HelloWorldApplication.CLIENT_SECRET, null, null);
client.authenticate(oauth);
accestoken = oauth.getAccessToken().toString();
System.out.println("AUTHDATA" + oauth.getAccessToken().toString());// client.getUsersManager().getCurrentUser(requestObj).toString()
// + oauth.getAccessToken().toString());
BoxUser user = new BoxUser();
System.out.println("ID" + user.getId());
if (client == null) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
} else {
((HelloWorldApplication) getApplication()).setClient(client);
Toast.makeText(this, "authenticated", Toast.LENGTH_LONG).show();
}
}
BoxDefaultRequestObject requestObject = null;
List<BoxUser> userList = null;
try {
userList = client.getUsersManager().getAllEnterpriseUser(
requestObject, null);
} catch (BoxRestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthFatalFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (BoxUser usr : userList) {
System.out.println("Addr: " + usr.getAddress());
System.out.println("Name : " + usr.getName());
System.out.println("Login : " + usr.getLogin());
}
}
I am getting the exception as networkonmainthreadexception...
Can anybody please help me?
Getting current user info in the raw api is done with a call to GET /users/me
Not sure what that looks like in the Java, but probably something more like :
user = client.getUsersManager().getCurrentUser
Make sure your access token is up to date. Also, looking at your code, why have you set
BoxDefaultRequestObject requestObject = null;
Instead do:
BoxDefaultRequestObject requestObject = new BoxDefaultRequestObject()
Otherwise the box library will get a null pointer exception. It gets the JSON parser from the request object.
Let me know if this works.
I am working on an android application which can read and write on an NFC tag.
I have no problem reading a tag which I already wrote something on, but when I use a blank tag I have difficulties reading the UID of the tag in the HEX code.
I am using mifare classic tags and I read the UID directly in the hex with the readblock method. The strange thing is, it works perfectly on debugger mode where I get the UID. But when I am trying without debbuger I get the following exception:
java.io.IOException: Transceive failed
Here's my method to read into the tag :
static String getUID(Intent intent) {
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
MifareClassic mc = MifareClassic.get(tagFromIntent);
try {
mc.connect();
Log.i("connect", "ok");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("connect", "nok");
e.printStackTrace();
}
try {
boolean secA = mc.authenticateSectorWithKeyA(0, mc.KEY_DEFAULT);
Log.i("secA", "ok");
} catch (IOException e) {
Log.i("secA", "nok");
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
boolean secB = mc.authenticateSectorWithKeyB(0, mc.KEY_DEFAULT);
Log.i("secB", "ok");
} catch (IOException e) {
Log.i("secB", "nok");
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] uidBytes = null;
try {
uidBytes = mc.readBlock(0);
Log.i("bytes", "ok");
} catch (IOException e) {
Log.i("bytes", "nok");
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mc.close();
Log.i("close", "ok");
} catch (IOException e) {
Log.i("close", "nok");
// TODO Auto-generated catch block
e.printStackTrace();
}
if (uidBytes != null) {
String uid = HexToString(uidBytes);
return uid;
}
else { return "Repasser le tag";}
}
I have no idea how to fix this, since it works in debug mode.
This code works for me. you have to check the authentication before you can read a block.
MifareClassic mif = MifareClassic.get(detectedTag);
int ttype = mif.getType();
Log.d(TAG, "MifareClassic tag type: " + ttype);
int tsize = mif.getSize();
Log.d(TAG, "tag size: " + tsize);
int s_len = mif.getSectorCount();
Log.d(TAG, "tag sector count: " + s_len);
int b_len = mif.getBlockCount();
Log.d(TAG, "tag block count: " + b_len);
try {
mif.connect();
if (mif.isConnected()){
for(int i=0; i< s_len; i++){
boolean isAuthenticated = false;
if (mif.authenticateSectorWithKeyA(i, MifareClassic.KEY_MIFARE_APPLICATION_DIRECTORY)) {
isAuthenticated = true;
} else if (mif.authenticateSectorWithKeyA(i, MifareClassic.KEY_DEFAULT)) {
isAuthenticated = true;
} else if (mif.authenticateSectorWithKeyA(i,MifareClassic.KEY_NFC_FORUM)) {
isAuthenticated = true;
} else {
Log.d("TAG", "Authorization denied ");
}
if(isAuthenticated) {
int block_index = mif.sectorToBlock(i);
byte[] block = mif.readBlock(block_index);
String s_block = NfcUtils.ByteArrayToHexString(block);
Log.d(TAG, s_block);
}
}
}
mif.close();
} catch (IOException e) {
e.printStackTrace();
}
May be There is Authentication Issue.
You can Authenticate this in this Way....
if (mfc.authenticateSectorWithKeyA(sectorNumber,
MifareClassic.KEY_MIFARE_APPLICATION_DIRECTORY)) {
Log.d("TAG", "Authorized sector with MAD key");
} else if (mfc.authenticateSectorWithKeyA(
sectorNumber, MifareClassic.KEY_DEFAULT)) {
Log.d("TAG",
"Authorization granted to sector with DEFAULT key");
} else if (mfc
.authenticateSectorWithKeyA(sectorNumber,
MifareClassic.KEY_NFC_FORUM)) {
Log.d("TAG",
"Authorization granted to sector with NFC_FORUM key");
} else {
Log.d("TAG", "Authorization denied ");
return false;
}
Here SectorNumber is : The sector you want to authenticate. eg:0,1,2....15 for mifare Classic 1K
When Authentication is done Then you can read or write.
I am creating an android application that uses async task to login and send data(HTTP Post Request. The application works fine when internet connection is good but when logging and it takes too long to post data due to slow connection the application force closes. i would like to display a toast "Error in Connection" when this happens. Please Help
Your application probably crashes, because you are trying to show Toast not in a UI Thread. That is you always should make any changes to UI by using Handler, or within onPostExecute() method, which also runs in UI Thread.
How to catch exceptions in doInBackground's thread and represent them in UI Thread is another question, I can suggest you this solution:
private class LoginTask extends
AsyncTask<Void, Integer, JSONArray[]> {
private static final int NETWORK_NO_ERROR = -1;
private static final int NETWORK_HOST_UNREACHABLE = 1;
private static final int NETWORK_NO_ACCESS_TO_INTERNET = 2;
private static final int NETWORK_TIME_OUT = 3;
// You can continue this list...
Integer serverError = NETWORK_NO_ERROR;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show(); // Don't forget to create it before
}
#Override
protected JSONArray[] doInBackground(Void... v) {
JSONArray[] result = null;
try {
result = NetworkManager.login(/* All params you need */);
} catch (JSONException e) {
return null;
} catch (ConnectException e) {
serverError = NETWORK_NO_ACCESS_TO_INTERNET;
return null;
} catch (UnknownHostException e) {
serverError = NETWORK_HOST_UNREACHABLE;
return null;
} catch (SocketTimeoutException e) {
serverError = NETWORK_TIME_OUT;
return null;
} catch (URISyntaxException e) {
// ..
return null;
} catch (ClientProtocolException e) {
// ..
return null;
} catch (Exception e) {
// ..
return null;
}
return result;
}
#Override
protected void onPostExecute(JSONArray[] result) {
progressDialog.dismiss();
if (result != null) {
processAndShowResult(result);
} else {
switch (serverError) {
case NETWORK_NO_ERROR:
Toast.makeText(YourActivity.this, "Probably, invalid response from server", Toast.LENGTH_LONG).show();
break;
case NETWORK_NO_ACCESS_TO_INTERNET:
// You can customize error message (or behavior) for different type of error
case NETWORK_TIME_OUT:
case NETWORK_HOST_UNREACHABLE:
Toast.makeText(YourActivity.this, "Error in Connection", Toast.LENGTH_LONG).show();
break;
}
}
}
}
By this means, you can flexibly control network errors and undertake appropriate actions, according to these errors.