我对Java非常陌生,一直在制作天气应用程序。 我只是使用主要活动来制作天气应用程序。我想通过城市功能添加天气。我倾向于通过构建可在下面的代码中看到的url来实现这一点。 “url”+ cityname +“apikey”。现在我想从用户处取得城市名称,然后我希望应用程序刷新并在此之后发送新的请求。如何将输入添加到变量?
package com.example.sabi.thisapp;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
TextView tempview;
TextView weatherdesc;
TextView cityname;
Button mButton;
EditText mEdit;
TextView mText;
String currentcity;
Context context;
boolean start=false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEdit= (EditText) findViewById(R.id.citylocation);
currentcity= mEdit.toString();
tempview= (TextView) findViewById(R.id.temp);
weatherdesc=(TextView) findViewById(R.id.Weatherdesc);
String url = "http://api.openweathermap.org/data/2.5/weather?q=";
url= url + currentcity +"&units=imperial&appid="+API_KEY;
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
tempview.setText("Response: " + response.toString());
weatherdesc.setText("Respnse: " + response.toString());
try {
JSONObject Jobject= response.getJSONObject("main");
String tempvalue = Integer.toString((int)Math.round(Jobject.getDouble("temp")/2.8666));
tempview.setText(tempvalue);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
RequestQueue queue= Volley.newRequestQueue(this);
queue.add(jsObjRequest);
start=false;
}
}}
“currentcity = mEdit.toString();”部分在很多方面都是错误的。这不是一个控制台应用程序,我认为你应该暂停开发这个应用程序,并开始学习Android框架及其基础知识。然后你可以恢复你离开的地方。 –
是的,@OğuzhanDöngül是正确的.'currentcity = mEdit.getText()。toString();'应该做,而不是在按钮单击事件处理程序'button1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ currentcity = mEdit.getText()。toString(); } });' –