-2

I am new to android dev

I have made as simple app in android (for api_version greater than 23) which fetches the name of all running apps. But the app doesn't work properly. When I click the button the functionality registered in "onClickListner" is not working.

package com.sakthi.appban;

    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.pm.ApplicationInfo;
    import android.content.pm.PackageManager;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Button btn = findViewById(R.id.button);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    displayAllApps();
                }
            });
    
        }
    
        private void displayAllApps(){
            PackageManager pm = getPackageManager();
            List<ApplicationInfo> installedApplications = pm.getInstalledApplications(PackageManager.GET_META_DATA);
    
            for(ApplicationInfo application : installedApplications){
                Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
                try {
                    Thread.sleep(1000);
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Toast.makeText(this, "Task Ended", Toast.LENGTH_SHORT).show();
        }

Hope I will get help

Thanks in advance

2 Answers2

0

I think you might have seen these message in logs if you run this code you will get this error when you click on the button

Error:

java.lang.IllegalStateException: You must either set a text or a view

Here application.name may get null for some of the apps. This may cause IllegalStateException because you are passing null to a Toast.

To fix this simply add an if condition to null check like this:

if(application.name != null) {
   Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
 }

Then it should work.

Update:

You can remove this code from your code which causing ANR:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
0

The problem is that I am trying to loop in the UI thread. So the UI thread cannot handle the UI operation.. and my program crashed.More info here