簡體   English   中英

在此Gridview中顯示錯誤java.lang.NullPointerException

[英]In this Gridview show error java.lang.NullPointerException

我正在嘗試從GridView中的jsonwebservice設置圖像和文本,但顯示此錯誤

LogCate

錯誤記錄

AudioCategoty.Java

public class AudioCategory extends AppCompatActivity {
Toolbar toolbar_home;
//  ImageView imgarrorback,imghomeicon;

static final String TAG = AudioCategory.class.getSimpleName();
static String URL = "http://eonion.in/vimalsagarji/audio/getallcategory";
static String ImgURL="http://eonion.in/vimalsagarji/static/audiocategory/";
ArrayList<String> listName;
ArrayList<String> listIcon;
ProgressDialog pd;
String strImageUrl="";
static Bitmap bitmap=null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_audio_category);
    toolbar_home = (Toolbar) findViewById(R.id.toolbar_audio);
    setSupportActionBar(toolbar_home);

    JsonTask jsonTask = new JsonTask();
    jsonTask.execute(URL,ImgURL);


}


private class JsonTask extends AsyncTask<String,String,String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(AudioCategory.this);
        pd.setMessage("Please Wait");
        pd.setCancelable(false);
        pd.setIndeterminate(false);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String strUrl=params[0];
        String ImageURL=params[1];
        try{
            JSONObject jsonObject=JSONParser.getJsonFromUrl(strUrl);
            for (int i=0; i<jsonObject.length()  ;i++){
                JSONArray array=jsonObject.getJSONArray("data");
                for (int j=0;j<array.length();j++){
                    JSONObject object=array.getJSONObject(j);
                    String strName=object.getString("Name");
                    String strCategoryIcon=object.getString("CategoryIcon");
                    strImageUrl=ImageURL+strCategoryIcon;
                    String strImagename=strImageUrl.substring(strImageUrl.lastIndexOf("/")+1);
                    downloadIcon(strImageUrl,strImagename);
                    listName.add(strName);
                    listIcon.add(strCategoryIcon);
                    Log.d(TAG, "list Id data:" + listName);
                    Log.d(TAG, "list Id data:" + listIcon);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (pd != null) {
            pd.dismiss();
        }
         GridView gridView = (GridView)findViewById(R.id.grid_audio);
        if (gridView != null) {
            CustomAdpter adpter = new CustomAdpter(getApplicationContext(), R.layout.custom_audio_gridview, listName);
            gridView.setAdapter(adpter);

        }
        /*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               *//* String strlitemTitle=listTitle.toString();
                String strlistDescription=listDescription.toString();
                String strlistAddress=listAdrees.toString();
                String strlistDate=listDate.toString();*//*

                String strlitemTitle = (String) ((TextView) view.findViewById(R.id.txtTitle)).getText();
                String strlistDescription = (String) ((TextView) view.findViewById(R.id.txtDescription)).getText();
                String strlistDate = (String) ((TextView) view.findViewById(R.id.txtDate)).getText();
                Intent intent = new Intent(getApplicationContext(), ThisMonthInformation_SubActivity.class);
                intent.putExtra("listTitle", strlitemTitle);
                intent.putExtra("listDescription", strlistDescription);
                intent.putExtra("listDate", strlistDate);
                startActivity(intent);
            }
        });*/
    }
}

private void downloadIcon(String strImageUrl, String strImagename) {
    File fileWithMyDir = getApplicationContext().getFilesDir();
    try {
        java.net.URL url = new URL(strImageUrl);
        File file = new File(fileWithMyDir.getAbsolutePath() + "/" + strImagename);
        System.out.println("image path from service" + fileWithMyDir.getAbsolutePath() + "/" + strImagename);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);

        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();

    }
}


public class CustomAdpter extends ArrayAdapter<String> {

    List<String> items;
    Context context;
    int resource;

    public CustomAdpter(Context context, int resource, List<String> items) {
        super(context, resource, items);
        this.context = context;
        this.resource = resource;
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(resource, null, false);

            //holder.txt_ID = (TextView) convertView.findViewById(R.id.txtID);
            holder.grid_txtTitle = (TextView) convertView.findViewById(R.id.grid_txtTitle);
            holder.grid_img = (ImageView) convertView.findViewById(R.id.grid_img);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // holder.txt_ID.setText(items.get(position));
        holder.grid_txtTitle.setText(items.get(position));
        String path=getFinalFilePath(listIcon.get(position));
        bitmap= BitmapFactory.decodeFile(path);
        holder.grid_img.setImageBitmap(bitmap);

        return convertView;

    }

    private String getFinalFilePath(String urlpath) {
        try {
            File fileWithinMyDir = getApplicationContext().getFilesDir();
            String path = fileWithinMyDir.getAbsolutePath();
            String ImageName = urlpath.substring(urlpath.lastIndexOf("/") + 1);
            String FinalPath = path + "/" + ImageName;
            return FinalPath;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private class ViewHolder {
        TextView grid_txtTitle;
        ImageView grid_img;

    }
}
}

activity.xml

<RelativeLayout
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"
android:background="@color/colorTabBackground"
tools:context="com.vimalsagarji.vimalsagarjiapp.AudioCategory">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include
        android:id="@+id/toolbar_audio"
        layout="@layout/toolbar_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etAudioCategory"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/toolbar_audio"
        android:hint="Audio Category"
        android:padding="10dp"
        android:textColorHint="@color/colorPrimary"/>

    <ImageView
        android:id="@+id/imgSerch"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/toolbar_audio"
        android:layout_marginTop="7dp"
        android:src="@drawable/search"/>

    <View
        android:id="@+id/viewline"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/etAudioCategory"
        android:layout_marginTop="-7dp"
        android:background="@color/colorPrimary"/>


    <GridView
        android:id="@+id/grid_audio"
        android:layout_below="@id/viewline"
        android:layout_width="match_parent"
        android:numColumns="3"
        android:layout_height="match_parent"></GridView>
</RelativeLayout>

custom_grid_item.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="120dp"
    android:background="@drawable/corner_event"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/grid_img"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@android:drawable/ic_menu_gallery"/>
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    <TextView
        android:id="@+id/grid_txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="170dp"
        android:textSize="14sp"
        android:textColor="@color/colorTabColor"
        android:text="Title"/>

</RelativeLayout>

上面的代碼在我的應用程序中實現,但是在嘗試運行該應用程序時顯示錯誤,請顯示輸出幫助我。

您尚未初始化listName 是空的

您的CustomAdapter調用super(context, resource, items); 不允許將null作為項目傳遞。 因為ArrayAdapter.getCount()不會為項目檢查null。

ArrayAdapter的源代碼:

public int getCount() {
    return mObjects.size();
}
  CustomAdpter adpter = new CustomAdpter(getApplicationContext(), R.layout.custom_audio_gridview, listName);

而是使用:

  CustomAdpter adpter = new CustomAdpter(AudioCategory.this, R.layout.custom_audio_gridview, listName);

還實施:

適配器內部的getCount方法。

試試這個... ArrayList<String> listName=new ArrayList<String>(); 在AsyncTask方法內部。

     private class JsonTask extends AsyncTask<String,String,String> {  
       ArrayList<String> listName=new ArrayList<String>();

            @Override
            protected void onPreExecute() {}
         @Override
            protected String doInBackground(String... params) {}
           @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM