java.lang.ClassCastException:java.util.HashMap无法强制转换为android.content.pm.PackageInfo

时间:2017-05-04 04:25:09

标签: java android

我有从json解析器在哈希映射中排序的应用程序列表。当我尝试查看应用程序信息onClick时,它崩溃了这里的代码

请记住,我有其他应用类别的其他列表视图

public class iqa extends Fragment {       

ListView communication;
ArrayList<HashMap<String, String>> communicationlist = new ArrayList<HashMap<String, String>>();

 public class now extends AsyncTask <HttpURLConnection, Void,Void> implements AdapterView.OnItemClickListener {

//returns app name using package name as input 
public String appName(String pack){
        String Name = null;

        try{
            PackageManager packManager = getContext().getPackageManager();
            ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(pack, 0);
            Name = packManager.getApplicationLabel(app).toString();
        }
        catch(Exception e){
            e.printStackTrace();
        }

        return Name;
    }


private void getAppCategories() throws IOException, JSONException
    {

        BufferedReader bufferedReader = null;
        HttpURLConnection urlConnection = null;
        BufferedWriter bufferedWriter = null;

        StringBuilder result = new StringBuilder();

        //Create JSON object to send to webservice
        JSONObject jsonObjectSend = new JSONObject();
        JSONArray jsonArrayPakages = new JSONArray();
        PackageManager packageManager;
        List<ResolveInfo> listApps; //this list store all app in device

        try {
            packageManager = getActivity().getPackageManager();
            Intent filterApp = new Intent(Intent.ACTION_MAIN);
            filterApp.addCategory(Intent.CATEGORY_LAUNCHER);
            listApps = packageManager.queryIntentActivities(filterApp, PackageManager.GET_META_DATA);

            for (ResolveInfo app : listApps){
                jsonArrayPakages.put(app.activityInfo.packageName.trim());
            }

            jsonObjectSend.put("packages", jsonArrayPakages);

            Log.d("json", jsonObjectSend.toString());

            URL url = new URL("http://getdatafor.appspot.com/data?key=53972606b926d38191a5446fdff89e377873d767fabedf6d");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(30000); /* milliseconds */
            urlConnection.setReadTimeout(30000); /* milliseconds */
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application-json");
            urlConnection.setDoOutput(true); /* allow output to send data */
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter =  new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(jsonObjectSend.toString());
            bufferedWriter.flush();

            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //Read data
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

        /*Parse JSON**********************************************************************************/


            JSONObject jsonObjectResult = new JSONObject(result.toString().trim());
            JSONArray jsonArrayApps = jsonObjectResult.getJSONArray("apps");
            for (int j = 0; j < jsonArrayApps.length(); j++) {

                JSONObject jsonObjectApp = jsonArrayApps.getJSONObject(j);

                String packageName = jsonObjectApp.getString("package").trim();
                String cate = jsonObjectApp.getString("category").trim();

                Log.d("result", (j + 1) + "---> : " + packageName + "---" + cate);
                HashMap<String, String> communicationmap = new HashMap<String, String>();
                String Communication = "Communication";

                String ca = e.getString("category").trim();
                String vit = e.getString("package").trim();
                String va = appName(vit);

                if (ca.equals(Communication) || ca.equals(Social) || ca.equals(dat))
                {
                    boolean communicexist = communicationmap.containsValue(va);

                    if (communicexist == false)
                    {
                        communicationmap.put("Name", va);
                        communicationmap.put("cate", ca);
                        communicationlist.add(communicationmap);
                    }
                    else
                    {
                        cmap.put("Name", va);
                        cmap.put("cate", ca);
                    }
                }
                 finally {
                 if (bufferedReader != null) {
                 bufferedReader.close();
                 }
                if (bufferedWriter != null) {
                bufferedWriter.close();
                }
                if (urlConnection != null) {
                urlConnection.disconnect();
                }
               }
            }
    @Override
    protected Void doInBackground(HttpURLConnection... params) {
        try {
            getAppCategories();
        } catch (IOException e) {
            Log.d("tag", "Net work error: " + e.getMessage(), e);
        } catch (JSONException e) {
            Log.d("tag", "JSON is not valid:  " + e.getMessage(), e);
        }
        return null;
    }
@Override
    protected void onPostExecute(Void aVoid) {

        // Keys used in Hashmap
        String[] from = { "Name","cate" };

        // Ids of views in listview_layout
       int[] to = { R.id.packa,R.id.catego};

       ListAdapter communicationadapter = new SimpleAdapter(getActivity().getBaseContext(), communicationlist,R.layout.lay,from,to);
        communication.setAdapter(communicationadapter);
        communication.setOnItemClickListener(this);
        Utility.setListViewHeightBasedOnChildren(communication);

        super.onPostExecute(aVoid);
    }

 @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //THIS IS WHERE THE ERROR STARTS
            PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
            AppData appData = (AppData) getActivity().getApplicationContext();
            appData.setPackageInfo(packageInfo);


        try {
            Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
            startActivity(appInfo);
        }

        catch (Exception e)
        {
            Log.e(TAG, "error in intent");
        }
    }
}

OnItemClick适配器是错误开始的地方

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
            AppData appData = (AppData) getActivity().getApplicationContext();
            appData.setPackageInfo(packageInfo);


        try {
            Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
            startActivity(appInfo);
        }

        catch (Exception e)
        {
            Log.e(TAG, "error in intent");
        }
    }

实施后,就像这样

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        HashMap<String,String> clickedItem = (HashMap<String, String>) parent.getItemAtPosition(position);
        String packageName = clickedItem.get("package");

        try {
            PackageManager packManager = getContext().getPackageManager();
            ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(packageName, 0);
            String appName = packManager.getApplicationLabel(app).toString();
            PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
            AppData appData = (AppData) getActivity().getApplicationContext();
            appData.setPackageInfo(packageInfo);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        try {
            Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
            startActivity(appInfo);
        }

        catch (Exception e)
        {
            Log.e(TAG, "error in intent");
        }
    }

我收到以下错误

FATAL EXCEPTION: main
              Process: com.finalyearstudentvitus.splash, PID: 25698
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finalyearstudentvitus.splash/com.finalyearstudentvitus.splash.permdisabled}: java.lang.NullPointerException: Attempt to read from field 'android.content.pm.ApplicationInfo android.content.pm.PackageInfo.applicationInfo' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                  at android.os.Handler.dispatchMessage(Handler.java:110)
                  at android.os.Looper.loop(Looper.java:203)
                  at android.app.ActivityThread.main(ActivityThread.java:6251)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
               Caused by: java.lang.NullPointerException: Attempt to read from field 'android.content.pm.ApplicationInfo android.content.pm.PackageInfo.applicationInfo' on a null object reference
                  at com.finalyearstudentvitus.splash.permdisabled.setValues(permdisabled.java:44)
                  at com.finalyearstudentvitus.splash.permdisabled.onCreate(permdisabled.java:31)
                  at android.app.Activity.performCreate(Activity.java:6686)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
                  at android.os.Handler.dispatchMessage(Handler.java:110) 
                  at android.os.Looper.loop(Looper.java:203) 
                  at android.app.ActivityThread.main(ActivityThread.java:6251) 
                  at java.lang.reflect.Method.invoke(Native Method)

以下是permdisabled.java类

public class permdisabled extends Activity {
TextView appLabel, packageName;
TextView req_permission, diss_perission;
PackageInfo packageInfo;
String pass;



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

    findViewsById();

    AppData appData = (AppData) getApplicationContext();
    packageInfo = appData.getPackageInfo();

    setValues();
}

private void findViewsById() {
    appLabel = (TextView) findViewById(R.id.appplabel);
    packageName = (TextView) findViewById(R.id.packagee_name);
    req_permission = (TextView) findViewById(R.id.req_permissionn);
    diss_perission = (TextView) findViewById(R.id.diss_permissionn);
}

private void setValues()
{
    // APP name  ERROR STARTS HERE
    appLabel.setText(getPackageManager().getApplicationLabel(
            packageInfo.applicationInfo));

    // package name
    packageName.setText(packageInfo.packageName);

    // uses-permission
    if (packageInfo.requestedPermissions != null) {
        req_permission.setText(getPermissions(packageInfo.requestedPermissions));
        pass = req_permission.toString();
    }
    else {
        req_permission.setText("-");
    }
}

// Convert string array to comma separated string
private String getPermissions(String[] requestedPermissions) {
    String permission = "";
    for (int i = 0; i < requestedPermissions.length; i++) {
        permission = permission + requestedPermissions[i] + ",\n";
    }
    return permission;
}

}

1 个答案:

答案 0 :(得分:1)

尝试实施以下内容:

// Modify your HashMap like this
if (communicexist == false)
                    {
                        communicationmap.put("package", vit);
                        communicationmap.put("cate", ca);
                        communicationlist.add(communicationmap);
                    }
                    else
                    {
                        cmap.put("package", vit);
                        cmap.put("cate", ca);
                    }

然后在onItemClick,

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      HashMap<String,String> clickedItem = parent.getItemAtPosition(position);
      String packageName = clickedItem.get("package");

        try{
        PackageManager packManager = getContext().getPackageManager();
        ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(packageName , 0);
        String appName = packManager.getApplicationLabel(app).toString();
 AppData appData = (AppData) getActivity().getApplicationContext();
            appData.setPackageInfo(packageInfo); 
    }
    catch(Exception e){
        e.printStackTrace();
    }




    try {
        Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
        startActivity(appInfo);
    }

    catch (Exception e)
    {
        Log.e(TAG, "error in intent");
    }
}