2013-07-31 2 views
0

Я пытаюсь добавить текст ниже моего изображения в режиме сетки. Я получаю ошибку исключения Null point.Текст под изображением в GridView

Ниже приведен файл макета:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:gravity="center_horizontal" 
    android:background="#000080"> 

    <imageview android:id="@+id/grid_item_image" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </imageview> 

    <textview android:id="@+id/grid_item_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="TextView" 
     android:gravity="center_horizontal" 
     android:textColor="#000000"> 
    </textview> 

</LinearLayout> 

Класс ImageAdapter имеет код ниже:

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.GridView; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class ImageAdapter extends BaseAdapter { 
    Context mContext; 
    private LayoutInflater mInflater; 

    // Keep all Images in array 
    public Integer[] mThumbIds = { 
      R.drawable.image1, R.drawable.image2, 
      R.drawable.image6, R.drawable.image3, 
      R.drawable.image5, R.drawable.image4 



    }; 

    // Constructor 
    public ImageAdapter(Context c){ 
     mContext = c; 
     mInflater = LayoutInflater.from(c); 
    } 

    public ImageAdapter(Residential residential) { 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public int getCount() { 
     return mThumbIds.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     return mThumbIds[position]; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View MyView = convertView; 

     if (convertView == null) 
     { 

     convertView = mInflater.inflate(R.layout.grid_item, 
        parent,false); 

     TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text); 
     tv.setText("Item"); 

     ImageView imageView = (ImageView)MyView.findViewById(R.id.grid_item_image); 

     //ImageView imageView = new ImageView(mContext); 
     imageView.setImageResource(mThumbIds[position]); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     imageView.setLayoutParams(new GridView.LayoutParams(190, 100)); 
     } 
     return MyView; 
    } 

} 

Это бросание нулевую ошибку исключения на уровне ниже линии:

convertView = mInflater.inflate(R.layout.grid_item, 
        parent,false); 

Я попытался с предлагается различный вариант, но все дают одинаковые результаты

LayoutInflater li = ((Activity) mContext).getLayoutInflater(); 

LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

Пожалуйста, предложите, как это решить. Благодарю.

+0

вывесить трассировки стека. также инициализировать 'TextView tv = (TextView) convertView.findViewById (R.id.grid_item_text);' и возвращать 'convertView'. Также используйте держатель вида http://developer.android.com/training/improving-layouts/smooth-scrolling.html – Raghunandan

+0

Что такое 'Residential'? – RobinHood

+0

@RobinHood: Жилой файл представляет собой файл gridview xml. – Gaurav

ответ

1

Из вашего комментария вы сказали

Residential is the gridview xml file 

Так используйте

convertView = mInflater.inflate(R.layout.resedential, 
       parent,false); 

использовать также convertview инициализировать свои взгляды

TextView tv = (TextView)convertView.findViewById(R.id.grid_item_text); 

и return convertView.

Вы также должны рассмотреть возможность использования ViewHolder.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

Используйте ViewHolder

static class ViewHolder 
{ 
     TextView textview; 
     ImageView imageView; 
} 

В getView

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

    ViewHolder vh; 

    if (convertView == null) 
    { 
    vh = new ViewHolder(); 
    convertView = mInflater.inflate(R.layout.resedential, 
       parent,false); 
    vh.tv = (TextView)convertView.findViewById(R.id.grid_item_text) 
    vh.imageView = (ImageView)convertView.findViewById(R.id.grid_item_image); 
    convertView.setTag(vh); 
    } 
    else 
    { 
    vh = (ViewHolder) convertView.getTag(); 
    }  
    vh.tv.setText("Item"); 
    vh.imageView.setImageResource(mThumbIds[position]); 
    vh.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    vh.imageView.setLayoutParams(new GridView.LayoutParams(190, 100)); 

    return convertView; 
} 
+0

использовать держатель для просмотра, дать вышеприведенную попытку. – Raghunandan

0

Поскольку MyView указывает на convertView, который может быть нулевым, но после присвоения нового представления вы не обновили MyView с помощью нового convertView.

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View MyView = convertView; 

     if (convertView == null) 
     { 

     convertView = mInflater.inflate(R.layout.grid_item, 
        parent,false); 
MyView = convertView; 
     TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text); 
     tv.setText("Item"); 

     ImageView imageView = (ImageView)MyView.findViewById(R.id.grid_item_image); 

     //ImageView imageView = new ImageView(mContext); 
     imageView.setImageResource(mThumbIds[position]); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     imageView.setLayoutParams(new GridView.LayoutParams(190, 100)); 
     } 
     return MyView; 
    } 
+0

Спасибо. Пробовал, как предложил, но все тот же вопрос. – Gaurav

+0

На какой линии вы получаете NullPointException –

0

Вот как надуть работы:

static View inflate(Context context, int resource, ViewGroup root) 
Inflate a view from an XML resource. 

Так вы передаете неправильный Params ..

так

convertView= mInflater.inflate(getBaseContext(),R.layout.grid_item,parent); 
+0

Спасибо. Я изменил параметры, но он дает «Метод getBaseContext() не определен для ошибки типа ImageAdapter. – Gaurav

+1

не думаю, что это проблема http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup, boolean). проверьте документы – Raghunandan

+0

@ Raghunandan PLS поможет мне в этом коде http://stackoverflow.com/questions/22986878/android-json-is-not-able-to-retrieve-any-files-from-mysql-database-it- is-empty/22987428? noredirect = 1 # 22987428 –