简体   繁体   中英

In this Gridview show error java.lang.NullPointerException

I am trying the set the image and text from the jsonwebservice in the gridview but show the this error

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>

This above code is implemented in my app but when try the run application that time show the error show pls help me for the output.

You haven't initialize the listName . It's null.

Your CustomAdapter calls super(context, resource, items); . It's not allow to pass null as items. Because ArrayAdapter.getCount() doesn't check null for items.

source code from ArrayAdapter:

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

Instead use :

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

Also implement:

getCount method inside adapter.

Try this... ArrayList<String> listName=new ArrayList<String>(); inside of AsyncTask method.

     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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM