0

I have little loading screen which has TextField, when loading screen is created it launches new Thread. That thread has 3 things to do, 1) Create new object to scanning class and run it's scanning method 2)in scanning method were it gets tricky it should update status with setStatus and latter call method updateWidget but it returns "android.view.View android.view.Window.findViewById(int)' on a null object reference" and 3) return all packages using setPackages. So how can I reach widget from thread, also extra question about part 3 which I mentioned is that right way to do ?

public class LoadingScreen extends Activity  {
private String status="";
List<ApplicationInfo> packages;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.loadingscreen_layout);
    updateWidget();

    try {
        startLoadingScreen();
    }catch (Exception e){
        Log.e("Scanner","Scanner",e);
    }

}

public void startLoadingScreen(){

    new Thread(new Runnable() {
        @Override
        public void run() {

            Scanner scanner = new Scanner();
            setPackages(scanner.Scan());
            changeIntent();
            finish();

        }
    });

}

public void setStatus(String status) {
    this.status = status;
}
void updateWidget(){
    TextView scanStatus  =  findViewById(R.id.statusView);
    scanStatus.setText(status);
}
private void changeIntent(){
    Intent intent = new Intent(this,DisplayClass.class);
    startActivity(intent);
}

public void setPackages(List<ApplicationInfo> packages) {
    this.packages = packages;
}

}

Scanning Class

public class Scanner extends Activity{
private LoadingScreen loadingScreen = new LoadingScreen();
List <android.content.pm.ApplicationInfo> Scan(){
    loadingScreen.setStatus("Scanning");
    loadingScreen.updateWidget();
    final PackageManager pm = getPackageManager();
    //get a list of installed apps.
    List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
    return packages;

}

}
Gerard
  • 13
  • 4

1 Answers1

0

In your new thread run() method you can try to update ui by using runOnUiThread

try {
    Activity_name.this.runOnUiThread(new Runnable() {
     @Override
           public void run() {
                            //update ui views
                            btn.setText("some_text");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

Alternatively you can use AsyncTask class to update ui elements from non ui thread.

ruben
  • 1,745
  • 5
  • 25
  • 47