简体   繁体   English

如何让天气信息默认显示用户当前位置的天气? Openweather map

[英]How can I make the weather information default to display the weather in the user's current location? Openweather map

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) 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.然后 go 到这个站点。

Copy all the data and paste it to the json file.复制所有数据并将其粘贴到 json 文件中。

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!并将响应解析为 json 类型或了解它,它的基本!

Then make a arrayList and store all the city names taken from json, and return it from the method.然后制作一个 arrayList 并存储取自 json 的所有城市名称,并从方法中返回。

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.您应该使用 (FusedLocationProviderClient) (由 google 推荐)来获取存储在用户手机中的最后一个用户位置(纬度和经度)。 The OpenWeather's API has two parameters that you should send Latitude & Longitude in that API. OpenWeather 的 API 有两个参数,您应该在 API 中发送纬度和经度。 Try this tutorial.试试这个教程。 it will help you.它会帮助你。 How to track the current location 如何跟踪当前位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM