MainActivity.java
Now we would write our main code for this project. We would be using JSON data. JSON data lets you store. It is a collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. In most languages, this is realized as an array, vector, list, or sequence. In our project, we would be using JSON data as an array.
The API key that we would get is in the format- "api.openweathermap.org/data/2.5/weather?id={city id}&appid={API key}"
Hence add your API key and in place of city id we would add the user entered city by "editText=findViewId(R.id.editText)"
The code is given below for your reference-
package com.example.askweather;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
resultTextView = findViewById(R.id.resultTextView);
}
public void getWeather(View view) {
try {
DownloadTask task = new DownloadTask();
String encodedCityName = URLEncoder.encode(editText.getText().toString(), "UTF-8");
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + editText.getText().toString() + "&APPID=36b8a62828e7fe2a2632d7b5020bbaf6").get();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
}
}
public class DownloadTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
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 (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
String message = "";
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
if (!main.equals("") && !description.equals("")) {
message += main + ": " + description + "\r\n";
}
}
if (!message.equals("")) {
resultTextView.setText(message);
} else {
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
}
.png)
8
