在这个Gridview中显示错误java.lang.NullPointerException

时间:2016-01-23 06:53:44

标签: java android

我正在尝试从gridview中的jsonwebservice设置图像和文本,但显示此错误

LogCate

Error Log

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>

上面的代码是在我的应用程序中实现的,但是当尝试运行应用程序时,显示错误显示请帮助我输出。

3 个答案:

答案 0 :(得分:1)

您尚未初始化listName。它是空的。

您的CustomAdapter来电super(context, resource, items);。不允许将null作为项传递。因为ArrayAdapter.getCount()不检查项目的空值。

ArrayAdapter的源代码:

public int getCount() {
    return mObjects.size();
}

答案 1 :(得分:0)

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

改为使用:

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

同时实施:

适配器内的

getCount方法。

答案 2 :(得分:0)

试试这个...... 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); } } 在AsyncTask方法中。

module aaa

contains

integer*4 function print_ptr_arr_1( ptr )

    implicit none

    integer*4, intent(in), pointer :: ptr(:)

    print *, 'as pointer'
    print *, size(ptr)
    print '(10i3)', ptr
    print *

end function print_ptr_arr_1

integer*4 function print_ptr_arr_2( ptr )

    implicit none

    integer*4, intent(in), target :: ptr(:)

    print *, 'as target'
    print *, size(ptr)
    print '(10i3)', ptr
    print *

end function print_ptr_arr_2

integer*4 function print_ptr_arr_3( ptr )

    implicit none

    integer*4, intent(in) :: ptr(:)

    print *, 'as assumed shape array'
    print *, size(ptr)
    print '(10i3)', ptr
    print *

end function print_ptr_arr_3

end module aaa