无法更改Progressbar的可见性

时间:2018-06-02 18:04:51

标签: java android

我已经看到了与此问题相关的所有其他问题,但似乎没有任何帮助。我想要实现的只是非常非常简单。

我想在OnCreate()方法中将不确定进度条的可见性更改为不可见。但我只是因为某种原因继续得到NullPointerException。是的,我使用正确的ID来引用进度条。

public class MainActivity extends Activity implements
    RecognitionListener {

private static TextView txt;
ProgressBar pb;

/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";

/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "hey iris";


/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;

private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.result_text);

    pb = (ProgressBar) findViewById(R.id.pbar);
    pb.setVisibility(View.GONE);
    System.out.println(pb.getVisibility());

    captions = new HashMap<>();
    captions.put(KWS_SEARCH, R.string.kws_caption);
    setContentView(R.layout.activity_main);

    ((TextView) findViewById(R.id.caption_text))
            .setText("Preparing the application");

    // Check if user has given permission to record audio
    int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
        return;
    }
    // Recognizer initialization is a time-consuming and it involves IO,
    // so we execute it in async task
    new SetupTask(this).execute();
}

private static class SetupTask extends AsyncTask<Void, Integer, Exception> {
    WeakReference<MainActivity> activityReference;
    SetupTask(MainActivity activity) {
        this.activityReference = new WeakReference<>(activity);
    }

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

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println(values[0]);
    }

    @Override
    protected Exception doInBackground(Void... params) {
        try {
            Assets assets = new Assets(activityReference.get());
            File assetDir = assets.syncAssets();
            activityReference.get().setupRecognizer(assetDir);
        } catch (IOException e) {
            return e;
        }
        return null;
    }
    @Override
    protected void onPostExecute(Exception result) {
        if (result != null) {
            ((TextView) activityReference.get().findViewById(R.id.caption_text))
                    .setText("Failed to init recognizer " + result);
        } else {
            activityReference.get().switchSearch(KWS_SEARCH);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull  int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Recognizer initialization is a time-consuming and it involves IO,
            // so we execute it in async task
            new SetupTask(this).execute();
        } else {
            finish();
        }
    }
}

@Override
public void onDestroy() {
    super.onDestroy();

    if (recognizer != null) {
        recognizer.cancel();
        recognizer.shutdown();
    }
}

/**
 * In partial result we get quick updates about current hypothesis. In
 * keyword spotting mode we can react here, in other modes we need to wait
 * for final result in onResult.
 */
@Override
public void onPartialResult(Hypothesis hypothesis) {
    if (hypothesis == null)
        return;

    String text = hypothesis.getHypstr();
    if (text.equals(KEYPHRASE)) {
        recognizer.stop();
        Intent intent = new Intent(this, ListenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity ( intent );
        recognizer.cancel();
        recognizer.shutdown();
        finish();
    }

}

/**
 * This callback is called when we stop the recognizer.
 */
@Override
public void onResult(Hypothesis hypothesis) {
    ((TextView) findViewById(R.id.result_text)).setText("");
    if (hypothesis != null) {

    }
}

@Override
public void onBeginningOfSpeech() {
}

/**
 * We stop recognizer here to get a final result
 */
@Override
public void onEndOfSpeech() {
    if (!recognizer.getSearchName().equals(KWS_SEARCH))
        switchSearch(KWS_SEARCH);
}

private void switchSearch(String searchName) {
    recognizer.stop();

    // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
    if (searchName.equals(KWS_SEARCH))
        recognizer.startListening(searchName);
    else
        recognizer.startListening(searchName, 1000);

    String caption = getResources().getString(captions.get(searchName));
    ((TextView) findViewById(R.id.caption_text)).setText(caption);

}

private void setupRecognizer(File assetsDir) throws IOException {
    // The recognizer can be configured to perform multiple searches
    // of different kind and switch between them

    recognizer = SpeechRecognizerSetup.defaultSetup()
            .setAcousticModel(new File(assetsDir, "en-us-ptm"))
            .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
            .getRecognizer();
    recognizer.addListener(this);

    /* In your application you might not need to add all those searches.
      They are added here for demonstration. You can leave just one.
     */

    // Create keyword-activation search.
    recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);

}

@Override
public void onError(Exception error) {
    ((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}

@Override
public void onTimeout() {
    switchSearch(KWS_SEARCH);
}
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView
    android:id="@+id/result_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/darker_gray"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/caption_text"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/caption_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="481dp"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:typeface="sans"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ProgressBar
    android:id="@+id/pbar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="167dp"
    tools:layout_editor_absoluteY="258dp" />

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:2)

您忘记在setContentView(R.layout.layoutWithProgressbar)

之前添加pb = (ProgressBar) findViewById(R.id.pbar);
public class MainActivity extends Activity implements
    RecognitionListener {

    ProgressBar pb;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        setContentView(R.layout.layoutWithProgressbar);
        //^^^^^^^^^^^^^^^^^^^
        // without this, there is no layout or view hierarchy
        // attached with the MainActivity
        // or probably setContentView(R.layout.main_activity);
        pb = (ProgressBar) findViewById(R.id.pbar);
        //pb.setVisibility(View.INVISIBLE);
        pb.setVisibility(View.GONE);

    }
}

另一个问题是,您正在将布局重新设置为同一个新状态

setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.result_text);

pb = (ProgressBar) findViewById(R.id.pbar);
pb.setVisibility(View.GONE);
System.out.println(pb.getVisibility());

captions = new HashMap<>();
captions.put(KWS_SEARCH, R.string.kws_caption);
//setContentView(R.layout.activity_main); remove this