Im new/learning Java and Android, and attempting to make a simple weather app which tells me the weather in my current location. I've got the basics figured out and I'm using OpenWeatherMap APIs - all good here.
What I'm trying to do is the following:
- When API returns to me that the weather is, for example, 'broken clouds', or 'heavy rain', I want to set an ImageView to a picture of, say broken clouds, or heavy rain.
I just cant seem to get the ImageView to take the images (which are in my Drawable folder) - I have tried using setImageResource, tried setImageDrawable, among others. Any pointers? What am I missing?
Here is my code (the important bits):
public class DownloadHtml extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
String tempInfo = jsonObject.getJSONObject("main").getString("temp");
String windInfo = jsonObject.getJSONObject("wind").getString("deg");
JSONArray weatherArr = new JSONArray(weatherInfo);
for (int i = 0; i < weatherArr.length(); i++) {
TextView weatherTextView = findViewById(R.id.weatherTextView);
weatherTextView.setText("");
JSONObject jsonPart = weatherArr.getJSONObject(i);
String description = jsonPart.getString("description");
weatherTextView.setText(description);
iv = findViewById(R.id.imageView2);
if (description == "clear sky") iv.setImageResource(R.drawable.clear_skies);
else if (description == "few clouds")
iv.setImageResource(R.drawable.few_clouds);
else if (description == "scattered clouds")
iv.setImageResource(R.drawable.scattered_clouds);
else if (description == "broken clouds")
iv.setImageResource(R.drawable.broken_clouds);
else if (description == "shower rain")
iv.setImageResource(R.drawable.shower_rain);
else if (description == "rain") iv.setImageResource(R.drawable.heavy_rain);
else if (description == "thunderstorm")
iv.setImageResource(R.drawable.thunderstorm);
else if (description == "snow") iv.setImageResource(R.drawable.snow);
else if (description == "mist") iv.setImageResource(R.drawable.mist);
Log.i("description", jsonPart.getString("description"));
if (description != null) {
locationManager.removeUpdates(locationListener);
}
}
for (int f = 0; f < tempInfo.length(); f++) {
TextView weatherTextView3 = findViewById(R.id.weatherTextView3);
weatherTextView3.setText("");
String tempString = tempInfo + " degrees celcius.\n";
weatherTextView3.setText(tempString);
Log.i("temp: ", tempInfo);
if (tempString != null) {
locationManager.removeUpdates(locationListener);
f = 500;
}
}
for (int j = 0; j < windInfo.length(); j++) {
TextView weatherTextView2 = findViewById(R.id.weatherTextView2);
weatherTextView2.setText("");
// assign text to wind direction
double windDegrees = Double.valueOf(windInfo);
if ((windDegrees > 0) && (windDegrees < 90)) {
String windString = "A North East Wind.\n";
weatherTextView2.setText(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 90) && (windDegrees < 180)) {
String windString = "A South East Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 180) && (windDegrees < 270)) {
String windString = "A South West Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 270) && (windDegrees < 360)) {
String windString = "A North West Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if (windInfo != null) {
locationManager.removeUpdates(locationListener);
j = 500;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You just accidentally used == to compare strings :)
Use description.equals("clear sky") instead of description == "clear sky"
I have an application in which I connected with a device which is connected by USB when I start to ping this device my application is crashed. This device is a RFID scanner which is connected to the phone by USB. A phone and my application see the connected phone with this scanner.
This is a code :
#Override
public synchronized void run() {
if (context == null || usbDevice == null) {
onStatusChanged(Status.NoContextOrUsbDeviceSpecified);
return;
}
//l("Device -> " + usbDevice);
UsbInterface usbInterface = null;
UsbEndpoint usbEndpointIn = null;
UsbEndpoint usbEndpointOut = null;
for (int i = 0; i < usbDevice.getInterfaceCount(); i++) {
usbInterface = usbDevice.getInterface(i);
//l("Interface[" + i + "] -> " + usbInterface);
if (usbInterface != null) {
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
//l("Endpoint[" + j + "] -> " + usbEndpoint);
if (usbEndpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
l("Found input!");
usbEndpointIn = usbEndpoint;
}
else {
l("Found output!");
usbEndpointOut = usbEndpoint;
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
else {
//l("Interface was null");
}
}
if (usbEndpointIn == null || usbEndpointOut == null) {
onStatusChanged(Status.NoEndpointsFoundOnUsbDevice);
return;
}
UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
onStatusChanged(Status.CouldntOpenUsbDeviceConnection);
return;
}
if (!usbDeviceConnection.claimInterface(usbInterface, true)) {
onStatusChanged(Status.CouldntClaimUsbDeviceInterface);
return;
}
onStatusChanged(Status.ScanningInitializing);
currentUsbDeviceConnection = usbDeviceConnection;
currentUsbInterface = usbInterface;
currentUsbEndpointIn = usbEndpointIn;
currentUsbEndpointOut = usbEndpointOut;
// Toast.makeText(context,send(PING) + " wysłane" , Toast.LENGTH_LONG).show();
final String[] a = new String[1];
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);
while (shouldPing && !Thread.interrupted()) {
if (send(PING) >= 0) {
onStatusChanged(Status.PingSuccessful);
} else {
onStatusChanged(Status.PingFailed);
}
SystemClock.sleep(PING_RECEIVE_TIMEOUT / 3);
}
onStatusChanged(Status.PingStopped);
scheduleStopReceiving();
});
byte[] bytes = new byte[36];
int result = currentUsbDeviceConnection.bulkTransfer(currentUsbEndpointIn, bytes, bytes.length, RECEIVE_TIMEOUT);
// Toast.makeText(context, "result " + result , Toast.LENGTH_LONG ).show();
receivingThread = new Thread(() -> {
onStatusChanged(Status.ReceivingStarted);
long lastTagTimestamp = 0;
boolean wasInterrupted = false;
while (shouldReceive) {
byte[] received = receive(36);
if (received != null) {
if (received[0] != (byte) 0xab ||
received[1] != (byte) 0xba ||
received[2] != (byte) 0xcd ||
received[3] != (byte) 0xdc) {
onStatusChanged(Status.ReceivedUnknown);
} else if (received[4] == 0x00) {
if (send(ACK) < 0) {
continue;
}
onStatusChanged(Status.ReceivedTag);
lastTagTimestamp = System.currentTimeMillis();
byte[] tag = new byte[8];
int index = 0;
while (index < tag.length) {
tag[index++] = received[8 + index];
}
long longValue = ByteBuffer.wrap(tag).getLong();
String hexValue = Long.toHexString(longValue).toUpperCase();
onScanCompleted(hexValue);
} else if (received[4] == 0x02) {
onStatusChanged(Status.ReceivedPing);
}
}
if (Thread.interrupted()) {
wasInterrupted = true;
}
if (wasInterrupted) {
if (lastTagTimestamp == 0) {
lastTagTimestamp = System.currentTimeMillis();
}
if (lastTagTimestamp + PING_RECEIVE_TIMEOUT < System.currentTimeMillis()) {
break;
}
}
}
onStatusChanged(Status.ReceivingStopped);
close();
});
shouldPing = true;
shouldReceive = true;
pingingThread.start();
receivingThread.start();
}
In this line I have
java.lang.NoSuchMethodError: No direct method
(Ljava/lang/Object;)V in class
Lrest/hello/org/usbdevice/rfid2/-$Lambda$2; or its super classes
(declaration of 'rest.hello.org.usbdevice.rfid2.-$Lambda$2' appears in
/data/app/rest.hello.org.usbdevice-2/base.apk)
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);
I'm trying to do a Map-Reduce job on big text file which contains my data. To process this data I actually need another array to do lookup's with the data I'm processing.
So ideally the reducers would load this file and populate the array, then start reducing.
I'm trying to use Google Cloud platform because I get £250 free computation, Without going into massive detail about the project, I'm new to map-reduce, only having done a small university course on extreme computing and need a little direction for the best way to achieve this. There are a few things I haven't fixed yet like the output types etc but what I'm struggling with is the setup() function, exactly how to populate my array before the reducer starts reducing, any help would be greatly appreciated!
public static class MapForEquityCalculator extends Mapper<LongWritable, Text, Text, IntWritable> {
public int GetIndex(int R1, int R2, boolean IsSuited) {
if (IsSuited) {
return (int)(((13 - Math.ceil((double)Math.max(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.min(R1, R2) / 4)));
} else {
return (int)(((13 - Math.ceil((double)Math.min(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.max(R1, R2) / 4)));
}
}
public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards=line.split(",");
int ind_1 = GetIndex(Integer.parseInt(cards[0]),Integer.parseInt(cards[1]),Integer.parseInt(cards[0])%4 == Integer.parseInt(cards[1])%4);
int ind_2 = GetIndex(Integer.parseInt(cards[2]),Integer.parseInt(cards[3]),Integer.parseInt(cards[2])%4 == Integer.parseInt(cards[3])%4);
int ind_3 = GetIndex(Integer.parseInt(cards[4]),Integer.parseInt(cards[5]),Integer.parseInt(cards[4])%4 == Integer.parseInt(cards[4])%4);
Text outputKey = new Text(Integer.toString(ind_1) +"," + Integer.toString(ind_2) +"," + Integer.toString(ind_3));
Text outputValue = new Text(line);
con.write(outputKey, outputValue);
}
}
public static class ReduceForEquityCalculator extends Reducer<Text, IntWritable, Text, IntWritable> {
public static final int HandRankSize = 32487834;
public static int HR[] = new int[HandRankSize];
protected static final int littleEndianByteArrayToInt(byte[] b, int offset) {
return (b[offset + 3] << 24) + ((b[offset + 2] & 0xFF) << 16)
+ ((b[offset + 1] & 0xFF) << 8) + (b[offset] & 0xFF);
}
public void setup(Context context) throws IOException{
Path pt=new Path("gs://mybucket/HandRanks.dat");
Configuration conf = new Configuration();
FileSystem fs = pt.getFileSystem(conf);
int tableSize = HandRankSize*4;
byte[] b = new byte[tableSize];
try {
FileInputStream fr = new FileInputStream(fs.open(pt));
int bytesRead = fr.read(b, 0, tableSize);
if (bytesRead != tableSize) {
}
fr.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
for (int i = 0; i < HandRankSize; i++) {
HR[i] = littleEndianByteArrayToInt(b, i * 4);
}
}
public void reduce(Text word, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards_string=line.split(",");
Integer[] cards = new Integer[cards_string.length];
int i=0;
for(String str:cards_string){
cards[i]=Integer.parseInt(str);//Exception in this line
i++;
}
int c0, c1, c2, c3, c4, c5, c6;
int u0, u1, u2, u3, u4, u5;
int su0, su1, su2, su3, su4, su5;
int tu0, tu1, tu2, tu3, tu4, tu5;
u0 = HR[53+cards[0]];
u1 = HR[u0+cards[1]];
su0 = HR[53+cards[2]];
su1 = HR[su0+cards[3]];
tu0 = HR[53+cards[4]];
tu1 = HR[su0+cards[5]];
int A_B_C = 0;
int A_C_B = 0;
int A_BC = 0;
int AB_C = 0;
int AC_B = 0;
int ABC = 0;
int B_A_C = 0;
int B_C_A = 0;
int B_AC = 0;
int BC_A = 0;
int C_A_B = 0;
int C_B_A = 0;
int C_AB = 0;
for (int com1 = 1; com1 < 49; com1++) {
if (com1 != cards[0] && com1 != cards[1] && com1 != cards[2] && com1 != cards[3] && com1 != cards[4] && com1 != cards[5]) {
u2 = HR[u1+com1];
su2 = HR[su1+com1];
tu2 = HR[tu1+com1];
for (int com2 = com1 + 1; com2 < 50; com2++) {
if (com2 != cards[0] && com2 != cards[1] && com2 != cards[2] && com2 != cards[3] && com2 != cards[4] && com2 != cards[5]) {
u3 = HR[u2+com2];
su3 = HR[su2+com2];
tu3 = HR[tu2+com2];
for (int com3 = com2 + 1; com3 < 51; com3++) {
if (com3 != cards[0] && com3 != cards[1] && com3 != cards[2] && com3 != cards[3] && com3 != cards[4] && com3 != cards[5]) {
u4 = HR[u3+com3];
su4 = HR[su3+com3];
tu4 = HR[tu3+com3];
for (int com4 = com3 + 1; com4 < 52; com4++) {
if (com4 != cards[0] && com4 != cards[1] && com4 != cards[2] && com4 != cards[3] && com4 != cards[4] && com4 != cards[5]) {
u5 = HR[u4+com4];
su5 = HR[su4+com4];
tu5 = HR[tu4+com4];
for (int com5 = com4 + 1; com5 < 53; com5++) {
if (com5 != cards[0] && com5 != cards[1] && com5 != cards[2] && com5 != cards[3] && com5 != cards[4] && com5 != cards[5]) {
int rank_a = HR[u5 + com5];
int rank_b = HR[su5 + com5];
int rank_c = HR[tu5 + com5];
if (rank_a > rank_b && rank_b > rank_c) {
A_B_C++;
} else if (rank_a > rank_c && rank_c > rank_b) {
A_C_B++;
} else if (rank_a > rank_b && rank_b == rank_c) {
A_BC++;
} else if (rank_a == rank_b && rank_b > rank_c) {
AB_C++;
} else if (rank_a == rank_c && rank_c > rank_b) {
AC_B++;
} else if (rank_a == rank_c && rank_a == rank_b) {
ABC++;
} else if (rank_b > rank_a && rank_a > rank_c) {
B_A_C++;
} else if (rank_b > rank_c && rank_c > rank_a) {
B_C_A++;
} else if (rank_b > rank_a && rank_a == rank_c) {
B_AC++;
} else if (rank_b == rank_c && rank_c > rank_a) {
BC_A++;
} else if (rank_c > rank_a && rank_a > rank_b) {
C_A_B++;
} else if (rank_c > rank_b && rank_b > rank_a) {
C_B_A++;
} else {
C_AB++;
}
}
}
}
}
}
}
}
}
}
}
Text outputValue = new Text(Integer.toString(A_B_C) +"," + Integer.toString(A_C_B) + "," + Integer.toString(A_BC)+"," + Integer.toString(A_BC) +","+ Integer.toString(AB_C)+","+ Integer.toString(AC_B) +","+ Integer.toString(ABC)+"," +Integer.toString(B_A_C) +","+Integer.toString(B_C_A)+","+Integer.toString(B_AC) +","+Integer.toString(BC_A)+","+Integer.toString(C_A_B) +","+Integer.toString(C_B_A)+","+Integer.toString(C_AB) + "\n");
con.write(word, outputValue);
}
}
}
So I have a LWJGL program that loads config files for entities and when I load a 29kb file the ram is increased from normal by about 200mb(total of 300mb) I don't know what to do about this or why it is happening.
Here is my full file parsing code:
FileReader isr = null;
File file = new File(CONTAINER + file_name + BMEF);
String line = null;
try {
isr = new FileReader(file);
} catch (FileNotFoundException e) {
System.err.println("No BMEF file found in the given context of; BMEF:" + BMEF + ", CONTAINER:" + CONTAINER + ", FILE NAME:" + file_name + ", FULL DIRECTORY USED:" + file);
}
BufferedReader reader = new BufferedReader(isr);
strings = new HashMap<String,String>();
float_arrays = new HashMap<String,float[]>();
int_arrays = new HashMap<String,int[]>();
try {
String name = null;
String current = "";
short type = -1;
short stage = 0;
while (true) {
System.out.println(current);
line = reader.readLine();
if(line == null){
break;
}
for(char c : line.toCharArray()){
current += c;
if(stage == 0){
if(c == ';'){
current = current.substring(0, current.length()-1);
name = current;
current = "";
stage++;
}
}else if(stage == 1){
if(c == '<'){
current = current.substring(0, current.length()-1);
if(current.equals(STRING)){
type = 0;
}else if(current.equals(INT_ARRAY)){
type = 1;
}else if(current.equals(FLOAT_ARRAY)){
type = 2;
}else{
System.err.println("NO SUCH TYPE: '" + current + "'");
System.exit(-1);
}
current = "";
stage++;
}
}else if(stage == 2){
if(c == '>'){
current = current.substring(0, current.length()-1);
if(type == 0){
strings.put(name, current);
}else if(type == 1){
String[] string_arr = current.split(",");
int[] out = new int[string_arr.length];
for(int i = 0; i < string_arr.length; i++){
out[i] = Integer.parseInt(string_arr[i]);
}
int_arrays.put(name, out);
}else if(type == 2){
String[] string_arr = current.split(",");
float[] out = new float[string_arr.length];
for(int i = 0; i < string_arr.length; i++){
out[i] = Float.parseFloat(string_arr[i]);
}
float_arrays.put(name, out);
}
name = null;
current = "";
type = -1;
stage = 0;
}
}
}
}
} catch (IOException e) {
System.err.println("An error was encounter whilst reading " + file_name + '.' + BMEF + "the line in use durring this encounter was:'" + line + "'");
}
I work with j2me polish 2.0.7, in eclipse 3.4.2, with wtk2.5.2_01.
I create control which draws text: normal, bold, and italic.
The code below is parsing raw text, and search for * and _ symbols, if found than add to draw vector the text and the drawer, and it's just stops after getting second time to the line 58:
String test = new String(raw_text_buff.substring(iter));
it stops in raw_text_buff.substring(iter), ONLY in debug mode..
raw text is: bla bla bla *1000* bla bla
Full code:
private String raw_text = "bla bla bla *1000* bla bla";
Vector draw_items = null;
private void prepareText()
{
char open_char = 0;
int open_pos = 0;
Object []param = null;
StringBuffer sb = new StringBuffer();
String raw_text_buff = new String(raw_text);
int iter = 0;
boolean was_reset = false;
while(true)
{
char c = raw_text_buff.charAt(iter);
if(iter == raw_text_buff.length() || c == '*' || c == '_')
{
if(sb.length() > 0)
{
BmFont viewer = null;
String str = sb.toString();
if(open_char == '*' && null != bm_strong)
{
viewer = bm_strong.getViewer(str);
}else
if(open_char == '_' && null != bm_italic)
{
viewer = bm_italic.getViewer(str);
}else if(null != bm_normal)
{
viewer = bm_normal.getViewer(str);
}else
{
}
param = new Object[2];
param[0] = str;
param[1] = viewer;
if(null == draw_items)
draw_items = new Vector();
draw_items.addElement(param);
sb = new StringBuffer();
if(open_char == 0 && (c == '*' || c=='_'))
open_char = c;
else
open_char = 0;
String test = new String(raw_text_buff.substring(iter)); // stucks here.
raw_text_buff = test;
iter = 0;
was_reset = true;
}else
{
open_char = c;
}
if(iter == raw_text_buff.length())
break;
}else
{
sb.append(c);
}
++iter;
}
}
What I'm doing wrong?