WeatherApp在点击晶圆厂时突然停止

时间:2018-09-10 21:23:13

标签: java android android-studio

我已经使用Android Studio创建了一个Android应用,并且没有编译错误或警告。但是,当我在Android Studio的仿真器中运行该应用程序时,它显示了mainActivity,我在其中输入了城市名称以显示天气,但是当我单击fab按钮时,该应用程序突然停止。请告诉我我哪里错了?以下是mainactivity的代码:

package com.bca.weatherapp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

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

/*Steps
* 1. Designing Layout
* 2. Declaring widgets
* 3. Understandnig JSON
* 4. Making AsyncTast to receive JSON
* 5. Making JSON Objects and clarify the data
* 6. Testing...
*  http://api.openweathermap.org/data/2.5/myWeather?q=Beirut&APPID=efed6aa0ebe9434cfd2b425089ea8392
* */

public class MainActivity extends AppCompatActivity {

    EditText cityField;
    TextView resultWeather;
    String cityToFind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        cityField = (EditText) findViewById(R.id.editText);
        resultWeather = (TextView) findViewById(R.id.textView2);




        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Loading Weather", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

                FindWeather(view);
            }
        });
    }

    //this method will execute the link and find the weather data
    public void FindWeather(View v){
        cityToFind = cityField.getText().toString();

        //asynkTask
        try {
            executeTask tasky = new executeTask();
            tasky.execute("http://api.openweathermap.org/data/2.5/myWeather?q=" + cityToFind + "&APPID=efed6aa0ebe9434cfd2b425089ea8392");
        } catch (Exception e){e.printStackTrace();}

    }

    //this method will get all the data from website in background
    public class executeTask extends AsyncTask<String, Void, String>{


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            try {
                String message = "";
                JSONObject jsonObject = new JSONObject(s);
                String infoWeatherToday = jsonObject.getString("weather");
                JSONArray array = new JSONArray(infoWeatherToday);

                for(int i=0; i<array.length(); i++){
                    JSONObject jsonSecondary = array.getJSONObject(i);
                    String main = "";
                    String description = "";

                    main = jsonSecondary.getString("main");
                    description = jsonSecondary.getString("description");

                    if(main != "" && description != ""){
                        message = message + main + ": " + description + "\r\n";
                    }

                }
                if(message != ""){
                    resultWeather.setText(message);
                } else {
                    Toast.makeText(MainActivity.this, "An Error Occured", Toast.LENGTH_SHORT).show();
                }

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

        }

        @Override
        protected String doInBackground(String... params) {
            String result="";
            URL url;
            HttpURLConnection urlConnection = null;
            try{
                url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream is = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(is);
                int data = reader.read();

                while(data != -1){
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }

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


            return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

请确保应用程序具有Permission。添加检查和/或请求Internet连接的权限。并且在您的AsyncTask中不起作用,因为您返回的是null而不是String值(我想算了)。

 @Override
        protected String doInBackground(String... params) {
            String result="";
            URL url;
            HttpURLConnection urlConnection = null;
            try{
                url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream is = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(is);
                int data = reader.read();

                while(data != -1){
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }

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


            return result
        }