Android无法更改imageview

时间:2018-02-07 19:26:12

标签: java android json image

我的代码可以通过drawables的名称获取图片,但由于某种原因,它无法更新。

package com.infonuascape.osrshelper.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.infonuascape.osrshelper.R;
import com.infonuascape.osrshelper.activities.MainActivity;
import com.infonuascape.osrshelper.models.Account;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class BankViewFragment extends OSRSFragment {
    private static final String TAG = "BankViewFragment";

    private static Account account;
    private ListView lv;
    private ImageView iv;
    Handler handler;

    ArrayList<HashMap<String, String>> ItemList;

    public static BankViewFragment newInstance(final Account account) {
        BankViewFragment fragment = new BankViewFragment();
        Bundle b = new Bundle();
        fragment.setArguments(b);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.bank_view, null);
        ItemList = new ArrayList<>();
        new GetItems().execute();
        lv = (ListView) view.findViewById(R.id.list);
        handler = new Handler(Looper.getMainLooper());
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        String nikas = sharedPref.getString("bankname", "null");
        return view;
    }

    public static int getResId(String resourceName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(resourceName);
            return idField.getInt(idField);
        } catch (Exception e) {
            throw new RuntimeException("No resource ID found for: "
                    + resourceName + " / " + c, e);
        }
    }

    private class GetItems extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
            String nikas = sharedpreferences.getString("bankname",  "null");
            String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "NIKAS: " + nikas);
            Log.e(TAG, "ACCOUNT: " + account);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONObject items = jsonObj.getJSONObject("bank");
                    Iterator keys = items.keys();
                    while(keys.hasNext()) {
                        String dynamicKey = (String)keys.next();
                        JSONObject line = items.getJSONObject(dynamicKey);
                        String item = line.getString("item");
                        //Integer image = getResId(item, Drawable.class);
                        final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
                        String amount = line.getString("amount");
                        Log.e(TAG, "DAIKTAS: " + item);
                        Log.e(TAG, "KIEKIS: " + amount);
                        HashMap<String, String> contact = new HashMap<>();
                        String itembank = item.replaceAll("i_", "");
                        String itembanks = itembank.replaceAll("_", " ");
                        contact.put("name", itembanks);
                        contact.put("email", amount);
                        LayoutInflater inflater = LayoutInflater.from(getContext());
                        View view = inflater.inflate(R.layout.bank_view, null);
                        lv = (ListView) view.findViewById(R.id.list);
                       // iv = (ImageView) view.findViewById(R.id.logo);
                        final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
                        handler.post(new Runnable() {
                            public void run() {
                                if(image != null) {
                                    Log.e(TAG, "kas cia jam netinka?: " + image);
                                    if(image == 0) {
                                        ims.setImageResource(R.drawable.i_noted);
                                        Log.e(TAG, "kas cia jam netinka?: " + image);
                                    } else {
                                        Log.e(TAG, "kas cia jam netinka?: " + image);
                                        ims.setImageResource(image);
                                    }
                                } else {
                                    Log.e(TAG, "null?: " + image);
                                }
                            }
                        });
                        ItemList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    };

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(),
                                "Couldn't get json from server!",
                                Toast.LENGTH_LONG).show();
                    }
                };
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
                    R.layout.list_item, new String[]{ "email","name"},
                    new int[]{R.id.email, R.id.name});
            lv.setAdapter(adapter);
        }
    }

}

错误

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.infonuascape.osrshelper, PID: 31024
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
                  at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems$1.run(BankViewFragment.java:128)
                  at android.os.Handler.handleCallback(Handler.java:815)
                  at android.os.Handler.dispatchMessage(Handler.java:104)
                  at android.os.Looper.loop(Looper.java:194)
                  at android.app.ActivityThread.main(ActivityThread.java:5637)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

问题在于,有很多项目,而且大部分都有资源,但有些人不愿意,我想跳过那些没有的人,但主要是问题是,在尝试查看银行时,应用程序崩溃了。

2 个答案:

答案 0 :(得分:1)

您无法在非UI线程中更改View 因此,为了解决您的问题,只需访问UI线程中的UI相关内容,例如在onPostExecute()

答案 1 :(得分:0)

不要这样做:除了UI线程之外,不应该在另一个线程中触及视图。

@Override protected void onPostExecute(Void result) { -->>>>> DONOT DO THIS --->>>>>lv.setAdapter(adapter); }