该应用程序不起作用。它适用于 Android 5.1,但不适用于 android 10.0

Posted

技术标签:

【中文标题】该应用程序不起作用。它适用于 Android 5.1,但不适用于 android 10.0【英文标题】:The application doesn't work. It works with Andorid 5.1 but it doesn't with android 10.0 【发布时间】:2020-06-19 13:14:13 【问题描述】:

我只是在听课:( 这是错误信息

E/androidRuntime: 致命异常: main 进程:com.example.weather3,PID:8893 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.lang.String.contains(java.lang.CharSequence)” 在 com.example.weather3.MainActivity$GetWeather.onPostExecute(MainActivity.java:166) 在 com.example.weather3.MainActivity$GetWeather.onPostExecute(MainActivity.java:142) 在 android.os.AsyncTask.finish(AsyncTask.java:755) 在 android.os.AsyncTask.access$900(AsyncTask.java:192) 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772) 在 android.os.Handler.dispatchMessage(Handler.java:107) 在 android.os.Looper.loop(Looper.java:214) 在 android.app.ActivityThread.main(ActivityThread.java:7356) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

这是我在那里写的发生错误的部分。

@Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            if(s.contains("Error: Not found city"))
                pd.dismiss();
                return;
            
            Gson gson = new Gson();
            Type mType = new TypeToken<OpenWeatherMap>().getType();
            openWeatherMap = gson.fromJson(s, mType);
            pd.dismiss();

            txtCity.setText(String.format("%s,%s",openWeatherMap.getName(),openWeatherMap.getSys().getCountry()));
            txtLastUpdate.setText(String.format("Last Updated: %s", Common.getDateNow()));
            txtDescription.setText(String.format("%s",openWeatherMap.getWeather().get(0).getDescription()));
            txtHumidity.setText(String.format("%d%%",openWeatherMap.getMain().getHumidity()));
            txtTime.setText(String.format("%s/%s",Common.unixTimeStampToDateTime(openWeatherMap.getSys().getSunrise()), Common.unixTimeStampToDateTime(openWeatherMap.getSys().getSunset())));

            txtCelsius.setText(String.format("%.2f °C",openWeatherMap.getMain().getTemp()));
            Picasso.with(MainActivity.this)
                    .load(Common.getImage(openWeatherMap.getWeather().get(0).getIcon()))
                    .into(imageView);


        

如果您需要帮助,这是整个代码

package com.example.weather3;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.weather3.Common.Common;
import com.example.weather3.Helper.Helper;
import com.example.weather3.Model.OpenWeatherMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;

public class MainActivity extends AppCompatActivity implements LocationListener 

    TextView txtCity, txtLastUpdate, txtDescription, txtHumidity, txtTime, txtCelsius;
    ImageView imageView;

    LocationManager locationManager;
    String provider;

    static double lat, lng;
    OpenWeatherMap openWeatherMap = new OpenWeatherMap();

    int MY_PERMISSION = 0;

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

        //Control
        txtCity = (TextView) findViewById(R.id.txtCity);
        txtLastUpdate = (TextView) findViewById(R.id.txtLastUpdate);
        txtDescription = (TextView) findViewById(R.id.txtDescription);
        txtHumidity = (TextView) findViewById(R.id.txtHumidity);
        txtTime = (TextView) findViewById(R.id.txtTime);
        txtCelsius = (TextView) findViewById(R.id.txtCelsius);
        imageView = (ImageView) findViewById(R.id.imageView);


        //Get Coordinates

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = locationManager.getBestProvider(new Criteria(), false);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(MainActivity.this, new String[]

                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE

            , MY_PERMISSION);
        
        Location location = locationManager.getLastKnownLocation(provider);
        if (location == null) 
            Log.e("TAG", "No Location");

        
    


    protected void onPause() 
        super.onPause();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(MainActivity.this, new String[]

                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE

            , MY_PERMISSION);
        
        locationManager.removeUpdates(this);
    

    protected void onResume() 

        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(MainActivity.this, new String[]

                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE

            , MY_PERMISSION);
        
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    


    @Override
    public void onLocationChanged(Location location) 
        lat=location.getLatitude();
        lng=location.getLongitude();

        new GetWeather().execute(Common.apiRequest(String.valueOf(lat), String.valueOf(lng)));

    

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) 

    

    @Override
    public void onProviderEnabled(String provider) 

    

    @Override
    public void onProviderDisabled(String provider) 

    

    private class GetWeather extends AsyncTask<String, Void, String> 
        ProgressDialog pd = new ProgressDialog(MainActivity.this);


        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            pd.setTitle("Please wait...");
            pd.show();
        

        @Override
        protected String doInBackground(String... params) 
            String stream = null;
            String urlString = params[0];

            Helper http = new Helper();
            stream = http.getHTTPData(urlString);
            return stream;
        

        @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            if(s.contains("Error: Not found city"))
                pd.dismiss();
                return;
            
            Gson gson = new Gson();
            Type mType = new TypeToken<OpenWeatherMap>().getType();
            openWeatherMap = gson.fromJson(s, mType);
            pd.dismiss();

            txtCity.setText(String.format("%s,%s",openWeatherMap.getName(),openWeatherMap.getSys().getCountry()));
            txtLastUpdate.setText(String.format("Last Updated: %s", Common.getDateNow()));
            txtDescription.setText(String.format("%s",openWeatherMap.getWeather().get(0).getDescription()));
            txtHumidity.setText(String.format("%d%%",openWeatherMap.getMain().getHumidity()));
            txtTime.setText(String.format("%s/%s",Common.unixTimeStampToDateTime(openWeatherMap.getSys().getSunrise()), Common.unixTimeStampToDateTime(openWeatherMap.getSys().getSunset())));

            txtCelsius.setText(String.format("%.2f °C",openWeatherMap.getMain().getTemp()));
            Picasso.with(MainActivity.this)
                    .load(Common.getImage(openWeatherMap.getWeather().get(0).getIcon()))
                    .into(imageView);


        
    

【问题讨论】:

【参考方案1】:

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference at

snull,这里:

 if(s.contains("Error: Not found city"))

s 变量从这里的doInBackground 方法传递给onPostExecute

    @Override
    protected String doInBackground(String... params) 
        String stream = null;
        String urlString = params[0];

        Helper http = new Helper();
        stream = http.getHTTPData(urlString);
        return stream;
    

这意味着stream 为空。

意思是stream = http.getHTTPData(urlString); 在某些方面不起作用/返回null

【讨论】:

以上是关于该应用程序不起作用。它适用于 Android 5.1,但不适用于 android 10.0的主要内容,如果未能解决你的问题,请参考以下文章

适用于 android 的 Cordova '本机文件选择器'插件不起作用

是否已经有适用于 android 的 StopWatch 类,为啥我的实现不起作用?

自定义图块覆盖在最新的适用于 Android 的 Google Maps SDK 中不起作用

iPhone - 为啥全屏不起作用,但它适用于 iPad?

<select> 在 Android 2.3.3 上的 Phonegap 应用程序中不起作用

Ionic 3.x:iOS 上的推送通知不起作用(适用于 Android?) Ionic Native Plugin Push