如何在Java类(Android Studio)中使用getApplicationContext?
我想建立自己的图书馆来了解天气。我在MainActivity中也做了同样的操作,但当一个应用程序将相同的方法放在另一个java类中时,Tosts和getApplicationContext方法会出错。我怎样才能修好它如何在Java类(Android Studio)中使用getApplicationContext?,java,android,Java,Android,我想建立自己的图书馆来了解天气。我在MainActivity中也做了同样的操作,但当一个应用程序将相同的方法放在另一个java类中时,Tosts和getApplicationContext方法会出错。我怎样才能修好它 public class WeatherClass { public static void getCurrentWeather(String location) { final String[] urlCityGetTemperature = {&
public class WeatherClass {
public static void getCurrentWeather(String location) {
final String[] urlCityGetTemperature = {"https://www.metaweather.com/api/location/"};
String urlCityGetId = "https://www.metaweather.com/api/location/search/?query=";
final String[] finishUrl = new String[1];
String tempUrl = "";
String city = "";
city = location;
if(city.equals("")) {
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
else {
tempUrl = urlCityGetId + city;
String finalCity = city;
StringRequest stringRequest = new StringRequest(Request.Method.GET, tempUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("response", response);
String output = "";
try {
JSONArray jsonResponce = new JSONArray(response);
if(response.equals("[]")) {
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex = jsonResponce.getJSONObject(0);
int woeid = jsonObjectZeroIndex.getInt("woeid");
//tvRes.setText(output);
finishUrl[0] = urlCityGetTemperature[0] + output;
//тут мы будем получат температуру по id города.
StringRequest stringRequestGetTeperatureWithId = new StringRequest(Request.Method.GET, finishUrl[0], new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("finalLink", response);
String outputTemp = "";
String outPutWeather;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObectFromArray = jsonArray.getJSONObject(0);
int woeid = jsonObectFromArray.getInt("the_temp");
outputTemp = String.valueOf(woeid);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequestGetTeperatureWithId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequest);
}
}
}
公共类天气类{
公共静态无效getCurrentWeather(字符串位置){
最后一个字符串[]urlCityGetTemperature={”https://www.metaweather.com/api/location/"};
字符串urlCityGetId=”https://www.metaweather.com/api/location/search/?query=";
最终字符串[]finishUrl=新字符串[1];
字符串tempUrl=“”;
字符串城市=”;
城市=位置;
if(城市等于(“”){
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
否则{
tempUrl=urlCityGetId+city;
字符串finalCity=城市;
StringRequest StringRequest=新建StringRequest(Request.Method.GET、tempUrl、new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
Log.d(“响应”,响应);
字符串输出=”;
试一试{
JSONArray JsonResponse=新的JSONArray(响应);
if(响应等于(“[]”){
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex=JSONResponse.getJSONObject(0);
int-woeid=jsonObjectZeroIndex.getInt(“woeid”);
//tvRes.setText(输出);
finishUrl[0]=URLCITYGETTERATURE[0]+输出;
//бббчаааааааааааааа识别码。
StringRequestStringRequestGetTeperationWithId=new StringRequest(Request.Method.GET,finishUrl[0],new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
Log.d(“finalLink”,回复);
字符串输出emp=“”;
字符串输出天气;
试一试{
JSONObject JSONObject=新JSONObject(响应);
JSONArray JSONArray=jsonObject.getJSONArray(“综合天气”);
JSONObject jsonObectFromArray=jsonArray.getJSONObject(0);
int-woeid=jsonObectFromArray.getInt(“温度”);
outputTemp=String.valueOf(woeid);
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(MainActivity.this,error.toString().trim(),Toast.LENGTH_SHORT.show();
}
});
RequestQueue RequestQueue=Volley.newRequestQueue(getApplicationContext);
add(stringrequestgetterperaturewithid);
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(这个,error.toString().trim(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue RequestQueue=Volley.newRequestQueue(getApplicationContext);
添加(stringRequest);
}
}
}
getApplicationContext和Toast不起作用。您可以将第二个参数上下文传递给getCurrentWeather,然后将该上下文传递给Toast 下面是WeatherClass中的getCurrentWeather方法,如下所示
public class WeatherClass {
public static void getCurrentWeather(String location,Context context){
// Here is your fetch whether code
// Your Toast like this
Toast.makeText(context,"Your Message", Toast.LENGTH_SHORT).show();
}
}
当您从MainActivity调用此方法时,按如下方式调用此方法
getCurrentWeather(location,getApplicationContext())
您需要创建一个新线程来显示toast,因为http调用是异步的。谢谢!这是可行的,但我只需要取一个参数。这是一个学习项目。我得到一个任务,用一个方法和一个参数创建一个库。可能吗?