Android Geocoder - java

In my android application I do reverse Geocode (address from latitude and longitude) . My layout display 9 addresses from Geocoder, but sometimes from start activity to display adresses it takes 15 seconds. How to make it faster? Here is my one method (one of nine) to get one address:
public void aktualizujRynek() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
HttpURLConnection connection = null;
try {
URL myUrl = new URL("http://......http request....................");
connection = (HttpURLConnection) myUrl.openConnection();
InputStream iStream = connection.getInputStream();
final String fResponse = IOUtils.toString(iStream);
final TextView fView = (TextView) findViewById(R.id.button8);
fView.post(new Runnable() {
#Override
public void run() {
// fView.setText("RESPONSE" + fResponse);
}
});
final boolean post = fView.post(new Runnable() {
#Override
public void run() {
//parse
JSONObject root = null;
try {
root = new JSONObject(fResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//Lat Lon
String Lat = root.getString("Lat");
double Lat_double = Double.parseDouble(Lat);
String Lon = root.getString("Lon");
double Lon_double = Double.parseDouble(Lon);
//not current measurement
String epoch_czujnik = root.getString("Epoch");
long epoch_czujnik_long = Long.parseLong(epoch_czujnik); //czas ostatniego odczytu
long epoch = System.currentTimeMillis() / 1000; //current time
long roznica1 = epoch - epoch_czujnik_long;
//lokalizacja ze współrzędnych
Geocoder geocoder;
List < Address > addresses;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
addresses = geocoder.getFromLocation(Lat_double, Lon_double, 1);
String address = addresses.get(0).getAddressLine(0);
String firstWords = address.substring(0, address.lastIndexOf(" "));
String city = addresses.get(0).getLocality();
//localization
if (roznica1 > 7200) {
String komunikat = "(czujnik nie działa)";
if (city.equals(firstWords)) {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + komunikat);
} else {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + firstWords + System.getProperty("line.separator") + komunikat);
}
} else {
if (city.equals(firstWords)) {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city);
} else {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + firstWords);
}
}
//color
String kolor = root.getString("Color");
TextView test = (TextView) findViewById(R.id.button8);
if (roznica1 > 7200) {
test.setBackgroundColor(Color.parseColor("#b3b3b3"));
} else {
test.setBackgroundColor(Color.parseColor(kolor));
}
//IJP
String ijp1 = root.getString("IJP");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//end parse
}
});
} catch (MalformedURLException ex) {
Log.e(TAG, "Invalid URL", ex);
} catch (IOException ex) {
Log.e(TAG, "IO / Connection Error", ex);
} finally {
if (connection != null)
connection.disconnect();
}
}
});
thread1.start();
}

Related

How to return a specific method on button click event?

Two buttons should update the value "PACK_LIB" inside "Stickers.java".
When they overwrite the String, the method setDefaultStickerPack() should be restarted.
When clicking on buttons b1 or b2 the value "PACK_LIB" will be overwritten by the value "allstickers" or "teststickers".
How can the button b1 or b2 restart the method "if(in==null) "inside setDefaultStickerPack() ?
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "allstickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "teststickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
-------Stickers.java
public static String PACK_LIB ="";
public void setDefaultStickerPack() {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
long packId = 1;
PackData packData = new PackData();
packData.objectId = packId;
packData.name = "ROKOmoji";
packData.iconOn = copyImgFile(in, "i" + packId + "_on");
//packData.iconOff = copyImgFile(inOff, "i" + packId + "_off");
List<StickerData> stickerData = new ArrayList<StickerData>();
long i = 0;
for (String img: packList) {
if(PACK_ICON.equals(img)){
continue;
}
InputStream sIs = null;
try {
sIs = lContext.getAssets().open(curAssets+"/"+img);
} catch (IOException e) {
e.printStackTrace();
}
if (sIs != null) {
StickerData sd = new StickerData();
i=i+1;
File file = copyImgFile(sIs, "s" + img);
sd.objectId = i;
sd.imageId = i;
sd.packId = packId;
sd.packName = packData.name;
sd.file = file;
sd.iconKey = createIconKey(file, "si" + img);
sd.mime = getMimeTypeOfFile(file.getPath());//"image/gif"
sd.url = null;
stickerData.add(sd);
}
}
packData.stickers = stickerData;
packDataListDefault.add(packData);
}
}
U can call the method with parameter. try with this.
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("allstickers");
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("teststickers");
showStickers();
}
});
-------Stickers.java
private static String PACK_LIB ="";
public void setDefaultStickerPack(String packLibValue) {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
PACK_LIB = packLibValue
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
..........
..........
}

Global Variable returning to 0.0 after completion of an AsyncTask

The main part of this question is, when I run this code, the TextViews latitudeTextView and longitudeTextView get updated correctly, therefore the global variable are being change to the correct values. But when i try to access them again after going an asynctask, they are set to 0.0, 0.0? Shouldn't they stay as the same values after onPostExecute ends?
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Weather>{
private static final String GOOGLE_CONVERTER = "https://maps.googleapis.com/maps/api/geocode/json";
private static final String GOOGLE_KEY = "AIzaSyBtt8yaXoRvLTkJHUXrhl5pQaLxomReHIA";
public static final int LOADER_ID = 0;
String jsonResponse = "";
private String address;
private TextView latitudeTextView;
private TextView longitudeTextView;
private TextView summaryTextView;
private TextView tempuratureTextView;
private TextView timezoneTextView;
private TextView textTextView;
private double latitude = 0.0;
private double longitude = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = (TextView) findViewById(R.id.latitude);
longitudeTextView = (TextView) findViewById(R.id.longitude);
summaryTextView = (TextView) findViewById(R.id.summaryTextView);
tempuratureTextView = (TextView) findViewById(R.id.temperatureTextView);
timezoneTextView = (TextView) findViewById(R.id.timezoneTextView);
textTextView = (TextView) findViewById(R.id.test);
final EditText addressEditText = (EditText) findViewById(R.id.edittext_address);
Button submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
address = addressEditText.getText().toString().trim();
address = "5121+Paddock+Court+Antioch+Ca+94531";
String fullUrl = GOOGLE_CONVERTER + "?address=" + address + "&key=" + GOOGLE_KEY;
new getlongAndLat().execute(fullUrl);
textTextView.setText(latitude + "");
//Log.e("TAG", latitude + " " + longitude);
// getLoaderManager().initLoader(LOADER_ID, null, MainActivity.this);
}
});
}
#Override
public android.content.Loader<Weather> onCreateLoader(int id, Bundle args) {
return new WeatherAsyncTaskLoader(this, latitude, longitude);
}
#Override
public void onLoadFinished(android.content.Loader<Weather> loader, Weather data) {
}
#Override
public void onLoaderReset(android.content.Loader<Weather> loader) {
}
public class getlongAndLat extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
Log.e("TAG", connection.getResponseCode() + "");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//trouble closing input stream
e.printStackTrace();
}
}
}
extractJsonResponse(jsonResponse);
return null;
}
#Override
protected void onPostExecute(String s) {
latitudeTextView.setText(latitude + "");
longitudeTextView.setText(longitude + "");
super.onPostExecute(s);
}
}
private void extractJsonResponse(String jsonResponse) {
try {
JSONObject rootJsonObject = new JSONObject(jsonResponse);
JSONArray nodeResultsArray = rootJsonObject.getJSONArray("results");
JSONObject nodeFirstObject = nodeResultsArray.getJSONObject(0);
JSONObject nodeGeometryObject = nodeFirstObject.getJSONObject("geometry");
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
In your code doInBackground(), you are calling extractJsonResponse() method before return statement. In extractJsonResponse(), you are getting lat and long and setting those to Global variables as mentioned in your code
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
I am sure that you are getting those zero values from Json object. You need to verify this thing at your end

get instant notification when a client disconnect from server socket in android

Hai friends i am new in Socket.
Now I implement a Chat app using Socket. I am testing with single Server SA and Client CA and CB. The Socket connection, chat and disconnect are working good.
But my problem is when client(CA) disconnect from server socket server not getting instant notification. Once CA reconnect again with new name CAA server will notify CA removed, and CAA connected.
my point is server must get instant notification when client CA disconnect socket.
This is my server Activity:
public class ServerMain extends ActionBarActivity {
static final int SocketServerPORT = 8080;
TextView infoIp, infoPort, chatMsg;
String msgLog = "";
List<ChatClient> userList;
ServerSocket serverSocket;
private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
chatMsg = (TextView) findViewById(R.id.chatmsg);
infoIp.setText(getIpAddress());
userList = new ArrayList<ChatClient>();
ChatServerThread chatServerThread = new ChatServerThread();
chatServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class ChatServerThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client, socket);
connectThread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private class ConnectThread extends Thread {
Socket socket;
ChatClient connectClient;
String msgToSend = "";
ConnectThread(ChatClient client, Socket socket) {
connectClient = client;
this.socket = socket;
client.socket = socket;
client.chatThread = this;
}
#Override
public void run() {
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.name = n;
msgLog += connectClient.name + " connected#" +
connectClient.socket.getInetAddress() +
":" + connectClient.socket.getPort() + "\n";
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
}
});
dataOutputStream.writeUTF("Welcome " + n + "\n");
dataOutputStream.flush();
broadcastMsg(n + " join our chat.\n");
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
msgLog += n + ": " + newMsg;
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
}
});
broadcastMsg(n + ": " + newMsg);
}
if (!msgToSend.equals("")) {
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
userList.remove(connectClient);
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (connectClient.socket.isClosed()) {
Toast.makeText(ServerMain.this,
connectClient.name + " removed.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ServerMain.this,
"not removed", Toast.LENGTH_LONG).show();
}
Toast.makeText(ServerMain.this,
connectClient.name + " removed.", Toast.LENGTH_LONG).show();
msgLog += "-- " + connectClient.name + " leaved\n";
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
}
});
broadcastMsg("-- " + connectClient.name + " leaved\n");
}
});
}
}
private void sendMsg(String msg) {
msgToSend = msg;
}
}
private void broadcastMsg(String msg) {
for (int i = 0; i < userList.size(); i++) {
userList.get(i).chatThread.sendMsg(msg);
msgLog += "- send to " + userList.get(i).name + "\n";
}
ServerMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
}
});
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
class ChatClient {
String name;
Socket socket;
ConnectThread chatThread;
}
}
This is my Client Activity:
public class ClientMain extends ActionBarActivity {
static final int SocketServerPORT = 8080;
LinearLayout loginPanel, chatPanel;
EditText editTextUserName, editTextAddress;
Button buttonConnect;
TextView chatMsg, textPort;
EditText editTextSay;
Button buttonSend;
Button buttonDisconnect;
String msgLog = "";
Socket socket = null;
ChatClientThread chatClientThread = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginPanel = (LinearLayout) findViewById(R.id.loginpanel);
chatPanel = (LinearLayout) findViewById(R.id.chatpanel);
editTextUserName = (EditText) findViewById(R.id.username);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonDisconnect = (Button) findViewById(R.id.disconnect);
chatMsg = (TextView) findViewById(R.id.chatmsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
editTextSay = (EditText) findViewById(R.id.say);
buttonSend = (Button) findViewById(R.id.send);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (chatClientThread == null) {
Log.e("chatClientThread", "null");
return;
} else {
chatClientThread.disconnect();
}
}
};
OnClickListener buttonSendOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (editTextSay.getText().toString().equals("")) {
return;
}
if (chatClientThread == null) {
return;
}
chatClientThread.sendMsg(editTextSay.getText().toString() + "\n");
}
};
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String textUserName = editTextUserName.getText().toString();
if (textUserName.equals("")) {
Toast.makeText(ClientMain.this, "Enter User Name",
Toast.LENGTH_LONG).show();
return;
}
String textAddress = editTextAddress.getText().toString();
if (textAddress.equals("")) {
Toast.makeText(ClientMain.this, "Enter Addresse",
Toast.LENGTH_LONG).show();
return;
}
msgLog = "";
chatMsg.setText(msgLog);
loginPanel.setVisibility(View.GONE);
chatPanel.setVisibility(View.VISIBLE);
chatClientThread = new ChatClientThread(
textUserName, textAddress, SocketServerPORT);
chatClientThread.start();
}
};
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog += dataInputStream.readUTF();
ClientMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
}
});
}
if (!msgToSend.equals("")) {
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
ClientMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ClientMain.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
ClientMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ClientMain.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ClientMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
loginPanel.setVisibility(View.VISIBLE);
chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg) {
msgToSend = msg;
}
private void disconnect() {
goOut = true;
}
}
}

Json object parsing error using http request

I am having an issue when http request is attempted the code that does the parsing works well...i tried to put a sample json string into the variable result and commented out all the code related to http request...i found the code works fine.But when i do a http request it is not working.Thank you in advance.The following is my code
`
public class MainActivity extends AppCompatActivity {
String result = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclick();
}
public void onclick(){
Asynctaskrunner run = new Asynctaskrunner();
run.execute("http://headers.jsontest.com/");
TextView text = (TextView) findViewById(R.id.textView);
TextView text1 = (TextView) findViewById(R.id.textView2);
final TextView text2= (TextView) findViewById(R.id.textView5);
final TextView text3 = (TextView) findViewById(R.id.textView6);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
JSONObject json = new JSONObject(result);
String name = json.getString("Accept-Language");
String salary = json.getString("Host");
text2.setText(name);
text3.setText(salary);
}catch (Exception e){
e.printStackTrace();
}
}
}
);
}
//-----------------------------------
private class Asynctaskrunner extends AsyncTask<String,Void,Void>{
private String response;
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response=convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
result=response;
TextView textView = (TextView) findViewById(R.id.textView4);
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
}`
String name = json.getString("Accept-Language");
the problem is here! JSON response is not returning any value for the Accept-Language key.
This is the response.
{
"X-Cloud-Trace-Context": "8bc66db5c468f43daff9c6a69fa7d0be/11367517399452323805",
"Host": "headers.jsontest.com",
"User-Agent": "Dalvik/2.1.0 (Linux; U; Android 6.0.1; D6503 Build/23.5.A.0.570)"
}
Change it with other key!
String trace = json.getString("X-Cloud-Trace-Context");
String host = json.getString("Host");
String agent = json.getString("User-Agent");

How to display openweather map data separately in Android?

I am trying to learn Android Async and json data parsing. I am using openweathermap.org API for displaying current weather for a place user type. My application displayed it However, it is not flexible as it is displaying all different details such as weather description, latitude, longitude, Wind Speed , current temperature.. all in a single string so it is not reusable which we should make. Suppose if i want to display the place on google map with current temperature with a map marker, I should be able to get only what i want in this case current temperature and latitude and longitude.
I want these details to display on separate textfields. I am beginner in Android. Please look into my code and suggest me with a solution and guidance.
Here is my JSONWeatherData.java
public class JSONWeatherData {
public static String getData(String weatherJson) throws JSONException {
String jsonResult = "";
try {
JSONObject JsonObject = new JSONObject(weatherJson);
String cod = jsonHelperGetString(JsonObject, "cod");
if(cod != null) {
if (cod.equals("200")) {
jsonResult += jsonHelperGetString(JsonObject, "name") + "\n";
JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys");
if (sys != null) {
jsonResult += jsonHelperGetString(sys, "country") + "\n";
}
jsonResult += "\n";
JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord");
if(coord != null){
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
jsonResult += "Lon: " + lon + "\n";
jsonResult += "Lat: " + lat + "\n";
}
jsonResult += "\n";
JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather");
if(weather != null){
for(int i=0; i<weather.length(); i++){
JSONObject thisWeather = weather.getJSONObject(i);
jsonResult += "Weather " + i + ":\n";
jsonResult += jsonHelperGetString(thisWeather, "main") + "\n";
jsonResult += jsonHelperGetString(thisWeather, "description") + "\n";
jsonResult += "\n";
}
}
JSONObject main = jsonHelperGetJSONObject(JsonObject, "main");
if(main != null){
jsonResult += "temp: " + jsonHelperGetString(main, "temp") + "\n";
jsonResult += "\n";
}
JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind");
if(wind != null){
jsonResult += "Wind Speed: " + jsonHelperGetString(wind, "speed") + "\n";
jsonResult += "\n";
}
}
else if(cod.equals("404")){
String message = jsonHelperGetString(JsonObject, "message");
jsonResult += "cod 404: " + message;
}
} else{
jsonResult += "cod == null\n";
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage(), e);
jsonResult += e.getMessage();
}
return jsonResult;
}
private static String jsonHelperGetString(JSONObject obj, String k){
String v = null;
try {
v = obj.getString(k);
} catch (JSONException e) {
e.printStackTrace();
}
return v;
}
private static JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){
JSONObject o = null;
try {
o = obj.getJSONObject(k);
} catch (JSONException e) {
e.printStackTrace();
}
return o;
}
private static JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){
JSONArray a = null;
try {
a = obj.getJSONArray(k);
} catch (JSONException e) {
e.printStackTrace();
}
return a;
}
}
Main Activity
Public class MainActivity extends Activity {
Button btnSubmitCity, btnMap;
EditText editCityText;
TextView weather_description, current_temp, wind_speed, textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editCityText = (EditText) findViewById(R.id.editCity);
btnMap =(Button) findViewById(R.id.mapButton);
btnSubmitCity = (Button) findViewById(R.id.submitCity);
weather_description = (TextView) findViewById(R.id.weatherDescription);
current_temp = (TextView) findViewById(R.id.currentTemp);
wind_speed = (TextView) findViewById(R.id.windSpeed);
//textViewResult = (TextView)findViewById(R.id.result);
textViewResult = (TextView)findViewById(R.id.result);
btnMap.setVisibility(View.INVISIBLE);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnSubmitCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//editCityText.getText().toString();
//HttpGetTask
String cityString = editCityText.getText().toString();
if(TextUtils.isEmpty(cityString)) {
Toast.makeText(MainActivity.this, "Enter a place", Toast.LENGTH_LONG).show();
return;
} else{
new HttpGetTask(cityString, weather_description).execute(cityString);
btnMap.setVisibility(View.VISIBLE);
}
//String cityString = city.getText().toString();
//new HttpGetTask().execute();
/*
new HttpGetTask(
editCityText.getText().toString(),
textViewResult).execute();
*/
}
});
}
private class HttpGetTask extends AsyncTask<String, Void, String> {
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/weather?";
private static final String TAG = "HttpGetTask";
String cityName;
TextView tvResult;
HttpGetTask(String cityName, TextView tvResult){
this.cityName = cityName;
this.tvResult = tvResult;
}
#Override
protected String doInBackground(String... params){
InputStream in = null;
HttpURLConnection httpUrlConnection = null;
String result = "";
try {
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter("q", cityName+",us") // city
.appendQueryParameter("mode", "json") // json format as result
.appendQueryParameter("units", "imperial") // metric unit
.appendQueryParameter("APPID", "Replace with your openweathermap API ID")
.build();
URL url = new URL(builtUri.toString());
httpUrlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(
httpUrlConnection.getInputStream());
String data = readStream(in);
result = edu.uco.rawal.p6rabina.JSONWeatherData.getData(data);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
if (null != httpUrlConnection) {
httpUrlConnection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result == "") {
Toast.makeText(MainActivity.this,
"Invalid weather data. Possibly a wrong query",
Toast.LENGTH_SHORT).show();
return;
} else {
//btnMap.setVisibility(View.VISIBLE);
tvResult.setText(result);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer data = new StringBuffer("");
try {
reader = new BufferedReader(new InputStreamReader(in));
String line ;
while ((line = reader.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
Log.e(TAG, "IOException");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
}
}
This code runs and output current weather but its not reusuable because everything is concatenated to single string.
To make it reusable and easy to access to each attribute as you want, how about making a class Weather that contains those attribute and when you start parsing the json, make an instance of it and write them there.
For example, instead of just this:
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
jsonResult += "Lon: " + lon + "\n";
jsonResult += "Lat: " + lat + "\n";
...
change to sth like:
Weather aWeather = new Weather();
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
aWeather.lon = long;
aWeather.lat = lat;
...
return aWeather;
Remember to change return type onPostExcute(String string) into onPostExcute(Weather weather);

Categories

Resources