如何使用用户输入来打开api JSON

问题描述 投票:-1回答:2

我正在开发Android应用,其中正在制作气象应用。该应用程序从JSON打开api数据并显示此信息。更具体地说,它需要用户输入城市或邮政编码,然后将此信息添加到API的URL,然后执行该URL。

MainActivity.java

package com.shanehampcsci3660.weather;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

//import static com.shanehampcsci3660.weather.GetJsonData.*;

public class MainActivity extends AppCompatActivity
{
    public static TextView tempTV, jsonTV;
    public EditText cityORZipET;
    private Button getWeather;
    public String zip, cityOrZip;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tempTV = (TextView) findViewById(R.id.tempTV);
        jsonTV = (TextView) findViewById(R.id.jsonFeedTV);

        cityORZipET = (EditText) findViewById(R.id.cityORZipET);

        getWeather = (Button) findViewById(R.id.getWeatherButton);
        //cityOrZip = cityORZipET.getText().toString();

        getWeather.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {

                GetJsonData getJsonData = new GetJsonData();
                //getJsonData.execute();
                cityOrZip = cityORZipET.getText().toString();
                getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
                jsonTV.setText(cityOrZip);

                /*if(cityOrZip.equals(""))
                {
                    getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");

                }
                else
                {
                    zip = "30528";
                    getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=x");
                }*/


            }
        });

    }

}

GetJsonData.java

package com.shanehampcsci3660.weather;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class GetJsonData extends AsyncTask<Void, Void, Void>
{


    public String data= "", line = "", name = "";
    double temp, minTemp, maxTemp;




    @Override
    protected Void doInBackground(Void... voids)
    {
        try
        {
            URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=30528&appid=id");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            while(line != null)
            {
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONObject jsonObject = new JSONObject(data);
            JSONObject main = jsonObject.getJSONObject("main");

            name = jsonObject.getString("name");
            temp = main.getDouble("temp");
            minTemp = main.getDouble("min_temp");
            maxTemp = main.getDouble("max_temp");

            /*JSONObject jsonObject = new JSONObject(result);
            JSONObject jsonData = new JSONObject(jsonObject.getString("main"));
            String weatherInfo = jsonObject.getString("weather");
            JSONArray jsonArray = new JSONArray(weatherInfo);
            String description, icon, iconURI;
            for(int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject jsonData1 = jsonArray.getJSONObject(i);
                description = jsonData1.getString("description");
                MainActivityController.description.setText(description);
                icon = jsonData1.getString("icon");
                iconURI = "http://openweathermap.org/img/w/" + icon + ".png";
                Picasso.get().load(iconURI).into(MainActivityController.conditionImageView);
            }*/

        }
        catch(MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);

        //MainActivity.jsonTV.setText(data);
        MainActivity.tempTV.setText("City:\t" + name + "\tTemp:\t" + temp);

        Log.d("Json Feed", name + "Temp: " + temp);
    }

    public static void execute(String s) {
    }
}

我的问题是无论放在哪里...

if(cityOrZip.equals(""))
                    {
                        getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=id");

                    }
                    else
                    {
                        zip = "30528";
                        getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=id");
                    }

...它将仅显示在GetJsonData.java中打开的默认Url的数据。我的问题是我在做错什么,为了使我的应用程序能够像应有的用户输入一样工作,我应该纠正什么。

java android json android-asynctask openweathermap
2个回答
0
投票

您正在使用包含客户端数据的url调用GetJsonData.execute,但其中没有代码。查看您当前的代码,客户端输入的zip不会存储到worker类中。


0
投票

这是因为在URL类中始终使用相同的GetJsonData。根据问题What arguments are passed into AsyncTask?,您的类声明应类似于:

public class GetJsonData extends AsyncTask<String, Void, YourPojo> {

    @Override
    protected YourPojo doInBackground(String... urls)
    {
        try
        {
            URL url = new URL(urls[0]);
            ...
        } catch (Exception e) {
           handle(e);
        }
   }
}

其中YourPojo是您需要创建的类,以存储需要从JSON有效负载中读取的所有属性:

class YourPojo {
    private String data;
    private String line;
    private String name;
    private double temp;
    private double minTemp
    private double maxTemp;

    // getters, setters
}
© www.soinside.com 2019 - 2024. All rights reserved.