简体   繁体   English

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

[英]WeatherApp stops suddenly on clicking fab

I have created an Android app using Android Studio and there is no compile error or warning. 我已经使用Android Studio创建了一个Android应用,并且没有编译错误或警告。 But when I run the app in the emulator of Android Studio, it shows the mainActivity where I put the city name to show the weather, but when i click on fab button the app suddenly stops. 但是,当我在Android Studio的仿真器中运行该应用程序时,它显示了mainActivity,我在其中输入了城市名称以显示天气,但是当我单击fab按钮时,该应用程序突然停止。 Please tell me where I am wrong? 请告诉我我哪里错了? following is the code of mainactivity: 以下是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);
    }
}

Make sure, application has Permission for that. 确保应用程序具有该Permission Add checking and/or requesting permission for the Internet connection. 添加检查和/或请求Internet连接的权限。 And in your AsyncTask shouldn't work, because your returning null instead of String value (I think forget). 并且在您的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
        }

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

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