I'm trying to make a basic weather app so this might be a long one.
I'd like the app to display the weather in the user's current location when it loads up. Also, I have an edit text where the user can search for a city and it displays the current weather for that city.
However, how can I data validate the edit text and throw an error message if they don't enter a city/ leave the box empty?
I have no idea how I can default the weather to the user's location. Can anyone help with this?
Here's what I've got so far:
package com.example.weatherapp;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
TextView view_city;
TextView view_temp;
TextView view_desc;
TextView view_hum;
TextView view_pres;
TextView view_wspeed;
ImageView view_weather;
EditText search;
Button btnsearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view_city = findViewById(R.id.location);
view_city.setText("");
view_temp = findViewById(R.id.temp);
view_temp.setText("");
view_desc = findViewById(R.id.condition);
view_desc.setText("");
view_hum = findViewById(R.id.humidity);
view_hum.setText("");
view_pres = findViewById(R.id.pressure);
view_pres.setText("");
view_wspeed = findViewById(R.id.wspeed);
view_wspeed.setText("");
view_weather = findViewById(R.id.weathericon);
search = findViewById(R.id.citysearch);
btnsearch = findViewById(R.id.searchbtn);
btnsearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm=(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getRootView().getWindowToken(), 0);
api_key(String.valueOf(search.getText()));
}
});
}
private void api_key(final String City) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=febe19d9086a360a7f9283cedac01bfd")
.get()
.build();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
Response response = client.newCall(request).execute();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { }
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String responseData = response.body().string();
try {
JSONObject json = new JSONObject(responseData);
JSONArray array = json.getJSONArray("weather");
JSONObject object = array.getJSONObject(0);
String description = object.getString("description");
String icons = object.getString("icon");
JSONObject templ = json.getJSONObject("main");
Double Temperature = templ.getDouble("temp");
JSONObject hum = json.getJSONObject("main");
Double Humidity = hum.getDouble("humidity");
JSONObject pre = json.getJSONObject("main");
Double Pressure = pre.getDouble("pressure");
JSONObject wind = json.getJSONObject("wind");
Double windSpeed = wind.getDouble("speed");
setText(view_city, City);
String temps = Math.round(Temperature) + "°C";
setText(view_temp, temps);
String hums = Math.round(Humidity) + "%";
setText(view_hum, hums);
String pres = Math.round(Pressure) + " hPa";
setText(view_pres, pres);
String wspeed = Math.round(windSpeed) + " mph";
setText(view_wspeed, wspeed);
setText(view_desc, description);
setIcon(view_weather, icons);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}catch (IOException e){
e.printStackTrace();
}
}
private void setText(final TextView text, final String value){
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(value);
}
});
}
private void setIcon(final ImageView imageView, final String value){
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (value){
case "01d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.sun));
break;
case "01n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.sun));
break;
case "02d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.suncloud));
break;
case "02n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.suncloud));
break;
case "03d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.cloudsun));
break;
case "03n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.cloudsun));
break;
case "04d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.cloud));
break;
case "04n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.cloud));
break;
case "09d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.rain));
break;
case "09n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.rain));
break;
case "10d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.heavyrain));
break;
case "10n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.heavyrain));
break;
case "11d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.thunder));
break;
case "11n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.thunder));
break;
case "13d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.snow));
break;
case "13n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.snow));
break;
default:
imageView.setImageDrawable(getResources().getDrawable(R.drawable.sun));
}
}
});
}
}
Just put
btnsearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mSearch = search.getText().toString().trim();
if (mSearch.equals("")) {
//Put Some Error like**
Toast.makeText(context, "Please Input City Name*", Toast.LENGTH_SHORT).show();
} else {
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getRootView().getWindowToken(), 0);
api_key(String.valueOf(search.getText()));
}
}
});
Edit Here is the edit of your comment
First go to 'you package name'/right click/new/file/: name as CityNames.json (Rembeber to put.json extension correctly)
Then go to this site.
Copy all the data and paste it to the json file.
And make a method in your project
File file = new File(context.getFilesDir(),FILE_NAME);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null){
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
// This responce will have Json Format String
String responce = stringBuilder.toString();
And parse the response as json type or leran about it, Its basic!
Then make a arrayList and store all the city names taken from json, and return it from the method.
Then use the method to check if city is valid like this:
for (int i = 0 ; methodName.size> i ; i++)
{
if (cityName.equals(methodName.get(i)))
{
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getRootView().getWindowToken(), 0);
api_key(String.valueOf(search.getText()));
break;
}
}
You should use (FusedLocationProviderClient) (recommended by google) to get the last user location as (Latitude & Longitude) stored in the user's phone. The OpenWeather's API has two parameters that you should send Latitude & Longitude in that API. Try this tutorial. it will help you. How to track the current location
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.