ProgressBar崩溃活动(空对象引用/或不可见)

时间:2019-07-20 12:46:23

标签: java android

在启动HomeActivity之前启动的MainActivity的以下代码(下载另一个活动中需要的json并显示加载进度条)中,我收到一个空对象引用错误(在getProgress()方法上),但是如果我按下“后退”按钮,HomeActivity随即会启动。

我已经搜索了这种错误,但是似乎可行的唯一解决方案是让我在一段时间延迟后启动HomeActivity的解决方案,更改了这样的setProgress方法:(但似乎栏没有改变,并且我认为这不是解决问题的真正方法)

public void setProgress(ProgressBar bar, int progress) {
        int oldProgress = bar.getProgress();
        int totalProgress = oldProgress + progress;
        bar.setProgress(totalProgress);

        if (bar.getProgress() == 100) {

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    final Intent intent = new Intent(MainActivity.this, HomePage.class);
                    startActivity(intent);
                }
            }, 4000);
        }
    }

----------------------------------------------------------------------

package ...

import ...


public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private TextView textView;
    private OkHttpClient httpClient;
    private String url;
    private Request request;
    private static boolean loaded = false;
    private FileInputStream inputStream;
    private FileOutputStream outputStream;
    private static final String FILE_NAME = "data.txt";
    private AlertDialogConnection noResponse;
    private AlertDialogConnection noInternet;
    private AlertDialogConnection serverError;
    private AlertDialogConnection internalError;

    public MainActivity(){
        this.inputStream = null;
        this.outputStream = null;
    }

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

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        this.httpClient = new OkHttpClient();
        this.url = "my url";
        this.request = new Request.Builder().url(url).build();

        this.progressBar = findViewById(R.id.progressBar);
        this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);

        this.textView = findViewById(R.id.textView);

        this.noResponse = new AlertDialogConnection();
        this.noInternet = new AlertDialogConnection();
        this.serverError = new AlertDialogConnection();
        this.internalError = new AlertDialogConnection();

        checkConnectionStatusAndStart();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    public void checkConnectionStatusAndStart(){
        if(checkConnectionStatus())
            requestData();
        else{
            this.noInternet.setTitle("no connection!");
            this.noInternet.setText("connection error!");
            this.noInternet.show(getSupportFragmentManager(), "no connection!");
        }
    }

    public boolean checkConnectionStatus(){
        boolean wifiConnection = false;
        boolean mobileConnection = false;
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = null;
        if (connectivityManager != null)
            networkInfo = connectivityManager.getActiveNetworkInfo();
        if((networkInfo != null) && networkInfo.isConnected()){
            if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
                /* Wifi On */
                wifiConnection = true;
            }
            if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
                /* Mobile data On */
                mobileConnection = true;
            }
            return (wifiConnection || mobileConnection);
        }else{
            /* You are not connected */
            return false;
        }
    }

    public void requestData(){
        textView.setText("waiting server...");
        httpClient.connectTimeoutMillis(); //Timeout
        httpClient.writeTimeoutMillis();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if(!call.isExecuted()){
                    Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
                }
                Log.d("HTTP-Error", "HTTP error!");
                AlertDialogConnection errorDialog = new AlertDialogConnection();
                errorDialog.setTitle("server error!");
                errorDialog.setText("server error, try later");
                errorDialog.show(getSupportFragmentManager(), "messaging error!");
            }

            @Override
            public void onResponse(@NotNull Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    /* HTTP-code: 200 */
                    final String body = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
                            setProgress(progressBar, 10);
                            try {
                                JSONObject json = new JSONObject(body);
                                try {
                                    ((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
                                    saveJSON(json, getApplicationContext());
                                } catch (FileNotFoundException e) {
                                    Log.d("File Not Found!", "FileNotFoundException!");
                                    internalError.setTitle("error while saving data!");
                                    internalError.setText("server error, try later");
                                    internalError.show(getSupportFragmentManager(), "error while saving data!");
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    Log.d("File Not Found!", "IOException!");
                                    internalError.setTitle("error while saving data!");
                                    internalError.setText("server error, try later");
                                    internalError.show(getSupportFragmentManager(), "error while saving data!");
                                    e.printStackTrace();
                                }
                                setProgress(progressBar, 90);
                                MainActivity.loaded = true;

                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.d("JSON-Error", "parsing JSON error!");
                                internalError.setTitle("server error!");
                                internalError.setText("server error, try later");
                                internalError.show(getSupportFragmentManager(), "JSON messaging error!");
                            }
                        }
                    });
                }else{
                    /* Http-code: 500 */
                    Log.d("HTTP-Error", "server error!");
                    serverError.setTitle("server error!");
                    serverError.setText("server error");
                    serverError.show(getSupportFragmentManager(), "server error!");
                }
            }
        });
    }

    public void setProgress(ProgressBar bar, int progress){
        int oldProgress = bar.getProgress();
        int totalProgress = oldProgress + progress;
        bar.setProgress(totalProgress);
        if(bar.getProgress() == 100){
            Intent intent = new Intent(this, HomePage.class);
            startActivity(intent);
            this.onDestroy();
        }
    }

    private void saveJSON(JSONObject json, Context context) throws IOException {
        outputStream = null;
        try{
            outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
            outputStream.write(json.toString().getBytes());
        }finally {
            if(outputStream != null){
                outputStream.close();
            }
        }
    }

    public JSONObject loadJSON(Context context) throws IOException, JSONException {
        inputStream = context.openFileInput(FILE_NAME);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        JSONObject jsonObject = new JSONObject(reader.readLine());
        inputStream.close();
        return jsonObject;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        this.httpClient = null;
        this.noResponse = null;
        this.noInternet = null;
        this.serverError = null;
        this.internalError = null;
        this.request = null;
        this.textView = null;
        this.progressBar = null;
        this.url = null;
        super.onDestroy();
    }


    @Override
    protected void onResume() {
        if(!loaded){
            checkConnectionStatusAndStart();
        }
        super.onResume();
    }

    @Override
    protected void onRestart() {
        if(!loaded){
            checkConnectionStatusAndStart();
        }
        super.onRestart();
    }

    @Override
    protected void onPause() {
        if(!loaded ){
            checkConnectionStatusAndStart();
        }
        super.onPause();
    }
}

0 个答案:

没有答案