Can anyone tell me what is going wrong here. I am trying to obtain the address using reverse geocoding..`
if (locationGPS != null) {
list = geocoder.getFromLocation(locationGPS.getLatitude(),
locationGPS.getLongitude(), 3);
if (list != null) {
if (list.size() > 0) {
strZipcode = list.get(0).getPostalCode();
strAdminArea = list.get(0).getAdminArea();
strLocality = list.get(0).getLocality();
strAddressLine = list.get(0).getAddressLine(0);
Log.d(TAG, "list of address: "+ list);
Log.d(TAG, "Data: "+ mobileDataEnabled);
Log.d(TAG, "Data: "+ mobile);
int count = 0;
while ((strZipcode == null || strAdminArea == null
|| strLocality == null || (strAddressLine == null || strAddressLine == "USA"))
&& count < list.size()) {
strZipcode = list.get(count).getPostalCode();
strAdminArea = list.get(count).getAdminArea();
strLocality = list.get(count).getLocality();
strAddressLine = list.get(count)
.getAddressLine(count);
count++;
}`
This thing works fine and gives out the right address. But sometimes it gives out null for the all of the values which i am trying to retrieve despite the fact that i have a check in place for null values.. Am i missing something here?
Reverse Geocoder does not always return a value. It sounds weird but this is the way it is. F0r example if you hit for address 5 times, you won't be lucky enough to get response for all hits. You may get 3 instead. So workaround may be, instead of hitting geocoder one at a time, try looping your request to 2 or 3 times or more, one of the requests will work hopefully.
Related
I do the following:
if (!items.containsKey(item) || items.get(item).getPrice() != 0) continue;
For the above I get the warning. In order to avoid it, I do
Objects.requireNonNull(items.get(item)).getPrice() != 0
The above works but it's not clean and anyway, I just checked that the item exists so for sure it's not null.
Is there a cleaner way? Thanks
Here is the full line of code:
if (!Utils.getInstance().items.containsKey(item.getId()) || Objects.requireNonNull(Utils.getInstance().items.get(item.getId())).getPrice() == 0) continue;
if (!Utils.getInstance().items.containsKey(item.getId()) || Objects.requireNonNull(Utils.getInstance().items.get(item.getId())).getPrice() == 0) continue;
That's quite a feat for a code!
You make to many logic in a single line.You need to divide it to a more readable one.
Let's simplify your code,
First, remove the requireNonNull. So it will be like this:
if (!Utils.getInstance().items.containsKey(item.getId()) || Utils.getInstance().items.get(item.getId()).getPrice() == 0) continue;
Second, extract Utils.getInstance().items to a single variable. So, it will be like this (Here I assume you're using a Map with HashMap):
// assuming a HashMap
HashMap items = Utils.getInstance().items;
if (!items.containsKey(item.getId()) || items.get(item.getId()).getPrice() == 0) continue;
Third, we extract the key as a single variable:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key) || items.get(key).getPrice() == 0) continue;
Now, we can split the or part to this:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key)) continue;
if(items.get(key).getPrice() == 0) continue;
the last code will gives you warning because Map.get() can return a null value. You can see from Map.get() documentation. So, we need to guard it.
Here the final version:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key)) continue;
if(items.get(key) == null) continue;
if(items.get(key).getPrice() == 0) continue;
It maybe end up with more extra lines for your code. But it makes your code more readable and maintainable because you don't need to push your brain to hard to understand the code.
You could annotate your method/variable with #NonNull
#NonNull
fun test(){
}
#NonNull
private lateinit var test:List<String>
Maybe you should change your if condition from
if (!items.containsKey(item) || items.get(item).getPrice() != 0) continue;
to
if (items.get(item) == null || items.get(item).getPrice() != 0) continue;
You don't need to ensure that items contains the key item, just do it in following way:
Object value = items.get(item);
if (value == null || value.getPrice() != 0) continue;
I am trying to calculate mobile data usage so I am using a broadcast that inform me about 3G connection then I run a Service to count data.
The problem is the calculating value is always less than the value calculated by the Android data usage default app.
Here is the code :
long now = TrafficStats.getMobileRxBytes();
long before = now;
do {
now = TrafficStats.getMobileRxBytes() ;
Diffnow = now - before;
SystemClock.sleep(500);
}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));
Log.i(TAG,"delta = "+(float)Diffnow/(1024*1024));
I think that i found the answer
To calculate data usage we must calculate either transmetted and received data so i have to change my code as following :
long now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes();
long before = now;
long Diffnow ;
do {
now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes() ;
Diffnow = now - before;
SystemClock.sleep(500);
}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));
Log.i(TAG,"delta = "+(float)Diffnow/(1024*1024));
I use the following method, but every time i use it i got error.
I cant figure out why because i perfrom this checking
if(unWanted == null || unWanted[0] == null)
The error is in this code:
unWanted[0] == null
but if i do only
if(unWanted == null)
It doest not see unWaned as null.
Thank for helping :)
the error code:
05-12 06:24:41.293: E/AndroidRuntime(24373): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
My method:
public void checking(){
DataBaseMain data = new DataBaseMain(this);
data.open();
String[] unWanted = data.getAllUnwantedExercies();
data.close();
if(unWanted == null || unWanted[0] == null)
Toast.makeText(this, "good", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "bad", Toast.LENGTH_LONG).show();
The method to get the String array from my DB.
public String[] getAllUnwantedExercies() {
Cursor c = ourDatabase.query(true, TABLE_NAME, new String[] {COLUMN_NOT_ON_LIST_EXERCISE}, null, null, COLUMN_NOT_ON_LIST_EXERCISE, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_NOT_ON_LIST_EXERCISE);
if(c.getCount() < 1)
return null;
int f = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false)
f++;
}
String[] list = new String[f];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false){
list[j] = c.getString(dayExercise);
j++;
}
}
return list;
}
unWanted[0] == null
It's clear that your array has no values in it. Attempting to reference the first index of an array of length 0, as explained in your stack trace, is a run time error.
unWanted == null
This doesn't work because the array object itself is not null.
A work around
A simple solution here is, at the end of your function, check the length of the array. If it is 0, you know it has no values, and you can return null.
if(list.length == 0)
{
return null;
}
else
{
return list;
}
or more concisely:
return list.length == 0? null:list;
Then when you get your array back from your function, all you need to do is test to check if the array is null.
if(unWanted == null)
{
// Array is empty.
}
Maybe just change this line:
if(unWanted == null || unWanted[0] == null)
By this one:
if(unWanted.length <= 0)
unWanted[0] == null
Here you are trying to check the first position of your array is null or not. Instead of this check your array size is 0 or not.
if(unWanted.length==0){
// your code
}
I hope this will help you.
You need to check that the length is greater than 0. It is not null because you are returning a list albeit an empty list. So it isn't null but also doesn't have a length
unWanted is not null does not mean you can reference it is first element by using unWanter[0] because it might be an empty array.
In my application there is a search option. If the user enters a search value, I have to get a value from the webservice. I am getting a large webservice value. In my webservice string values are coming. I am getting like <> like xml character entity reference like. I want to replace all characters and parse xml. Can anybody tell me how to do this and give an example?
I tried with StringBuffer for unescapexml character, I am getting out of memory error
public String unescapeXML(String str) {
if (str == null || str.length() == 0)
return "";
StringBuffer buf = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c == '&') {
int pos = str.indexOf(";", i);
if (pos == -1) { // Really evil
buf.append('&');
} else if (str.charAt(i + 1) == '#') {
int val = Integer.parseInt(str.substring(i + 2, pos), 16);
buf.append((char) val);
i = pos;
} else {
String substr = str.substring(i, pos + 1);
if (substr.equals("&"))
buf.append('&');
else if (substr.equals("<"))
buf.append('<');
else if (substr.equals(">"))
buf.append('>');
else if (substr.equals("""))
buf.append('"');
else if (substr.equals("'"))
buf.append('\'');
else if (substr.equals(" "))
buf.append(" ");
else
// ????
buf.append(substr);
i = pos;
}
} else {
buf.append(c);
}
}
return buf.toString();
}
I tried with stream, I am not able to do it. Can anybody give an example how to do this?
You should not parse it on your own. There are better ways - SAX or DOM.
This resource contains a lot of useful inforamtion about these both ways (and code examples too): http://onjava.com/pub/a/onjava/2002/06/26/xml.html
Take a look here in order to get more details about android included parsers :
http://developer.android.com/reference/javax/xml/parsers/package-summary.html
But make your own parser with SAX is probably the best choice in your case ;)
I have a city simulation game and try to find a way to check the flow of our power system.
The basics:
The map for the city is based on tiles (30 by 30 tiles = 900 tiles).
Now i start at a power plant and do a recursive neighbor check (top, left, right, bottom) to check if there is something that will transport the power. If there is something, I start checking this tiles for neighbors, too.
To prevent double checks and/or infinite recursive calls, I fill a ArrayList with processed tiles and check if a new tile was already processed and added to the ArrayList...
Recursively started:
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
Log.w("GT", "update env for id: " + id);
int newId = id - GameMap.mMapSize;
if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
updatePowerEnvironment(newId, elements);
}
newId = id + GameMap.mMapSize;
if (newId < GameMap.mMapCells.size() && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
updatePowerEnvironment(newId, elements);
}
newId = id - 1;
if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
updatePowerEnvironment(newId, elements);
}
newId = id + 1;
if (newId < GameMap.mMapCells.size()
&& GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
updatePowerEnvironment(newId, elements);
}
}
If I can trust the log output, no tile was tried to processed twice. That means, that I have no errors in the recursive calls. Which also means, the stack is simply too small.
Does someone have an idea how to avoid the stack limit?
[Update and my code as a result of Erics answer]
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
Stack<Integer> toProcess = new Stack<Integer>();
toProcess.push(id);
int mapSize = GameMap.mMapCells.size();
while (!toProcess.empty()) {
id = toProcess.pop();
Log.e("GT", "id to process: " + id);
if (elements.contains(id)) {
continue;
}
int[] neighborIds = computeNeighbors(id);
for (int neighbor : neighborIds) {
if (neighbor < 0 || neighbor >= mapSize) {
continue;
}
if (!GameMap.mMapCells.get(neighbor).mPowerEnabled) {
continue;
}
toProcess.push(neighbor);
}
elements.add(id);
}
}
private int[] computeNeighbors(int id) {
return new int[] {id + GameMap.mMapSize, id - GameMap.mMapSize, id + 1, id - 1};
}
If I understand your problem correctly you are attempting to compute the transitive closure of the "is powered by" relation between two tiles. It is certainly possible to compute a transitive closure non-recursively.
Here's a non-recursive algorithm that computes the transitive closure of a relation in C#. You should be able to adapt that to the language of your choice.
http://blogs.msdn.com/b/ericlippert/archive/2010/02/08/making-the-code-read-like-the-spec.aspx
Note that basically what I'm doing here is avoiding the stack limit by allocating my own stack on the heap. That thing can grow as big as you like. (If you run out of heap memory then you've got bigger problems!)
Note also that it would be wise to choose a data structure that makes the "is a member of?" predicate extremely cheap. An array list of size n is usually O(n) to answer the question "is this element a member of this collection?" which means your algorithm is O(n^2) overall. Can you use a collection like a set or a hash table that has O(1) containment testing?
Also, on a purely "code quality" level, this method could use some work. The fact that there is so much duplicated code in there is a red flag. I would be inclined to write this method like this sketch:
Set<int> PoweredTiles(int powersource)
{
Set<int> result = an empy set;
Stack<int> stack = an empty stack;
stack.Push(powersource);
while (stack is not empty)
{
int current = stack.Pop();
if (result.Contains(current)) continue;
result.Add(current);
int[] neighbours = { compute the neighbours }
foreach(int neighbour in neighbours)
{
if (neighbour is not in range of grid) continue;
if (neighbour is not a power carrier) continue;
stack.Push(neighbour);
}
}
return result;
}
Short, to the point, not recursive, no duplicated code, and O(n).
You just need to convert your recursive implementation into an iterative one (as theory tells us is always possible).
For example, you could:
maintain a queue of cells-to-be-checked
while this queue is not empty, process the front element
to process a cell, do whatever you have to do to the cell itself, then for each of its four nneighbours
if they are not already in the queue, add them to the queue
repeat until the queue is empty
An efficient, recursive algorithm should work provided you do clear the flags (I assume you're simply setting flags on whether a tile has power or not) before doing the recursion. Something like this:
void updateCell(position)
{
for each direction (north, south, east, west) do the following:
-- is there a cell there? (test for edges), if not, exit now;
-- can it be powered?
false: exit now;
true: set powered=true, call updateCell(this position);
}
void updatePowerGrid(start)
{
clearPowerFlags();
set powered=true for start;
updateCell(start);
}
This should work well enough until you use really huge grid sizes.
You can make it iterative. Have two lists, one that keeps track of where you have been, and one that keeps track of where you are currently checking.
Psuedo Code with your code:
While(ToBeChecked is not empty) {
//Note In python i'd be using a copy of the list so I could edit it without
//concequence during the iteration. ie for a in b[:]
for each element in ToBeChecked
updatePowerEnvironment(...);
//Remove element you are checking
removeElementFromToBeChecked(...);
}
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
Log.w("GT", "update env for id: " + id);
int newId = id - GameMap.mMapSize;
if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
//call addElementToBeChecked instead and I beleive the above already
//makes sure it has not already been checked
addElementToBeChecked(newId, elements);
}
newId = id + GameMap.mMapSize;
if (newId < GameMap.mMapCells.size() && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
addElementToBeChecked(newId, elements);
}
newId = id - 1;
if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
addElementToBeChecked(newId, elements);
}
newId = id + 1;
if (newId < GameMap.mMapCells.size()
&& GameMap.mMapCells.get(newId).mPowerEnabled
&& !elements.contains(newId)) {
elements.add(newId);
addElementToBeChecked(newId, elements);
}
}
addElementToBeChecked(...) {
ToBeChecked.add();
//Some other stuff if needed
}
removeElemenToBeChecked(...) {
ToBeChecked.remove();
//Some other stuff if needed
}
The very first thing I would try is just to change the search order from North-South-West-East to North-East-South-West. Like this:
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
if (!GameMap.ValidCellId(id))
return;
if (!GameMap.mMapCells.get(id).mPowerEnabled)
return;
if (elements.Contains(id))
return;
elements.Add(id);
updatePowerEnvironment(id - GameMap.mMapSize, elements);
updatePowerEnvironment(id + 1, elements);
updatePowerEnvironment(id + GameMap.mMapSize, elements);
updatePowerEnvironment(id - 1, elements);
}
This might reduce the recursion depth, depeding on the maps involved.