I tried to use a ListView with a BaseAdapter. I had a java.lang.NullPointerException on this line:
titolo.setText(getResources().getString(R.string.nome_cognome_utente, p.nome));
Where I'm doing wrong?
This is my main activity:
public class ListaUtenti extends Activity {
private ListView listView;
private ListAdapter adapter;
private List<Persona> persona = new LinkedList<Persona>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_utenti);
listView = (ListView)findViewById(R.id.listaUtenti);
adapter = new BaseAdapter() {
#Override
public int getCount() {
return persona.size();
}
#Override
public Persona getItem(int position) {
return persona.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
if(view == null){
view = getLayoutInflater().inflate(R.layout.list_item_persona, null);
}
final TextView titolo = (TextView)findViewById(R.id.firstLine);
final TextView descrizione = (TextView)findViewById(R.id.secondLine);
final Persona p = getItem(position);
titolo.setText(getResources().getString(R.string.nome_cognome_utente, p.nome));
descrizione.setText(getResources().getString(R.string.descrizione, p.cognome));
return view;
}
};
listView.setAdapter(adapter);
}
#Override
protected void onStart(){
super.onStart();
persona.clear();
persona.add(new Persona("nome1","cognome1"));
persona.add(new Persona("nome2","cognome2"));
persona.add(new Persona("nome3","cognome3"));
listView.setAdapter(adapter);
}
}
This is the ListView in the xml file activity_lista_utenti:
<ListView
android:id="#+id/listaUtenti"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:listitem="#android:layout/simple_list_item_1" />
This is the xml file list_item_persona:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="5dp"
android:src="#drawable/ic_contact_picture"
android:contentDescription="#string/immagine_profilo" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:background="#color/yellow2"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:gravity="center_vertical"
android:textSize="20sp" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:background="#color/yellow"
android:layout_height="20dp"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:gravity="center_vertical"
android:textSize="15sp" />
</RelativeLayout>
Get textview from view's findViewById,i.e.
Change
final TextView titolo = (TextView)findViewById(R.id.firstLine);
final TextView descrizione = (TextView)findViewById(R.id.secondLine);
to
final TextView titolo = (TextView)view.findViewById(R.id.firstLine);
final TextView descrizione = (TextView)view.findViewById(R.id.secondLine);
Since they are part of list_item_persona view.
Related
I am new here so please bear with my naivety. I am working on a music player that will display a menu on clicking 'dots' buttton(given in code below) in listview item. Inside the menu there will be a button to delete. The listview is getting populated by a custom adapter. Here is the code of adapter...
private class hashmapAdapter extends BaseAdapter implements Filterable {
HashMap<Integer, NowPlayingActivity.Details> NewDetails = new HashMap<>();
private hashmapAdapter(HashMap<Integer, NowPlayingActivity.Details> hashMap) {
if(NewDetails.size()==0) {
NewDetails.putAll(hashMap);
}
}
#Override
public int getCount() {
return NewDetails.size();
}
#Override
public Object getItem(int position) {
return NewDetails.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View result;
if(convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_item,parent,false);
} else {
result = convertView;
}
((TextView)result.findViewById(R.id.Name)).setText(NewDetails.get(position).getName());
((TextView)result.findViewById(R.id.artist)).setText(NewDetails.get(position).getArtist());
((TextView)result.findViewById(R.id.duration)).setText(NewDetails.get(position).getDuration()+" || ");
dots = (Button)result.findViewById(R.id.dots);
dots.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (TextView)result.findViewById(R.id.Name);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View popup_view = inflater.inflate(R.layout.option_layout,null);
RelativeLayout item = (RelativeLayout) popup_view.findViewById(R.id.popup);
final float width= (getResources().getDimension(R.dimen.width_entry_in_dp));
final float height= getResources().getDimension(R.dimen.height_entry_in_dp);
final PopupWindow popupWindow = new PopupWindow(popup_view,Math.round(width),Math.round(height),true);
popupWindow.showAtLocation(item, Gravity.END, 0, 0);
popupWindow.showAsDropDown(dots);
play_next_btn = (Button)popup_view.findViewById(R.id.play_next);
add_to_playlist = (Button)popup_view.findViewById(R.id.add_to_playlist);
share = (Button)popup_view.findViewById(R.id.share);
delete = (Button)popup_view.findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<NewDetails.size();i++) {
if(NewDetails.get(i).getName().equals(name.getText().toString())) {
for(int j=0;j<hashMap.size();j++) {
if(hashMap.get(j).getName().equals(name.getText().toString())) {
if (true) {
NewDetails.remove(i);
hashMap.remove(j);
}
}
}
}
}
populate1(NewDetails);
popupWindow.dismiss();
}
});
}
});
return result;}
Now the problem is that after deleting element when i call populate1(NewDetails), it gives a null pointer exception on NewDetails.get(position).getName(). So on repopulating listview i am getting NPE error. Following is the populate1() function code...
public void populate1(HashMap<Integer,NowPlayingActivity.Details> hashMap) {
adapter = new hashmapAdapter(hashMap);
library.setAdapter(adapter);
adapter.notifyDataSetChanged();
library.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
name = (TextView)view.findViewById(R.id.Name);
String SongName = name.getText().toString();
Intent intent = new Intent(getApplicationContext(),NowPlayingActivity.class);
intent.putExtra("SongName",SongName);
setResult(555,intent);
finish();
}
});
}
I have already tried notifydatasetchanged() and listview.invalidateviews(), both didnt work. File is getting deleted but the adapter is not refreshing the list to remove element. Here is the xml layout of single_item for listview....`
`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="70dp"
android:paddingRight="8dp"
android:paddingEnd="8dp"
android:background="#drawable/element_shape_list"
android:descendantFocusability="blocksDescendants">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/v1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/v11"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/art_work"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_launcher"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"/>
<TextView
android:id="#+id/Name"
android:textSize="17sp"
android:textColor="#000"
android:textStyle="bold"
android:gravity="bottom"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:layout_toRightOf="#id/art_work"
android:layout_toEndOf="#+id/art_work"
android:singleLine="true"
/>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#+id/art_work"
android:layout_toEndOf="#id/art_work"
android:layout_below="#id/Name">
<TextView
android:id="#+id/duration"
android:textSize="12sp"
android:textColor="#000"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_height="20dp"
android:singleLine="true"
android:gravity="clip_horizontal"
android:ellipsize="end"/>
<TextView
android:id="#+id/artist"
android:textSize="12sp"
android:textColor="#000"
android:layout_toRightOf="#+id/duration"
android:layout_toEndOf="#+id/duration"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:gravity="fill_horizontal"
android:layout_height="20dp"
android:singleLine="true" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent">
<Button
android:id="#+id/dots"
android:layout_width="40dp"
android:textStyle="bold"
android:background="?android:attr/selectableItemBackground"
android:layout_height="70dp"
android:text="#string/vertical_ellipsis"
android:textSize="25sp" />
</FrameLayout>
</RelativeLayout>
I want to fill Listview but But Repeat only imgLike,imgComments,txtLikeUnlike and txtComments from all Items. Because I using array for imgLike,imgComments,txtLikeUnlike and txtComments for get (fetch)selected Position. what is mistake in my code please guide me.
My code,
/** Adapter Class */
public class Adapter1 extends BaseAdapter {
ImageView imgImage = null,imgUnlike[] = null, imgLike[] = null,imgComments[] = null, imgShare[] = null;
TextView txtId = null,txtLikeUnlike[] = null, txtComments[] = null;
public ArrayList<HashMap<String, String>> arr = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getData = new HashMap<String, String>();
public Adapter1(Context context,
ArrayList<HashMap<String, String>> arr) {
this.context = context;
this.arr = arr;
layoutInflater = LayoutInflater.from(context);
this.imgUnlike = new ImageView[arr.size()];
this.imgLike = new ImageView[arr.size()];
this.imgComments = new ImageView[arr.size()];
this.imgShare = new ImageView[arr.size()];
this.txtLikeUnlike = new TextView[arr.size()];
this.txtComments = new TextView[arr.size()];
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return arr.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(R.layout.list_item, parent,
false);
} else {
row = convertView;
}
/** Initialize Widgets */
/** Imageview */
imgImage = (ImageView) row
.findViewById(R.id.imgImage);
imgUnlike[position] = (ImageView) row
.findViewById(R.id.imgUnlike);
imgLike[position] = (ImageView) row
.findViewById(R.id.imgLike);
imgComments[position] = (ImageView) row
.findViewById(R.id.imgComments);
imgShare[position] = (ImageView) row
.findViewById(R.id.imgShare);
/** TextView */
txttId = (TextView) row
.findViewById(R.id.txtId);
txtLikeUnlike[position] = (TextView) row
.findViewById(R.id.txtLikeUnlike);
txtComments[position] = (TextView) row
.findViewById(R.id.txtComments);
getData = arr.get(position);
txtId.setText(getData.get(Fragment1.TAG_ID));
imgUnlike[position]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgUnlike[position]
.setVisibility(View.INVISIBLE);
imgLike[position]
.setVisibility(View.VISIBLE);
getCurrentPosition = position;
}
});
imgLike[position].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgNewsFeedLike[position].setVisibility(View.INVISIBLE);
imgNewsFeedUnlike[position].setVisibility(View.VISIBLE);
}
});
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
Detail.class);
startActivity(intent);
}
});
return row;
}
xml file is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/masterLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/five_dp" >
<ImageView
android:id="#+id/imgImage"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_below="#+id/imgBlueStrip"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:background="#null"
android:contentDescription="#string/content_description"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imgImage"
android:background="#drawable/strip"
android:baselineAligned="false"
android:gravity="center_vertical"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/imgUnlike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:contentDescription="#string/content_description"
android:src="#drawable/unlike" />
<ImageView
android:id="#+id/imgLike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="#string/content_description"
android:src="#drawable/like"
android:visibility="invisible" />
<TextView
android:id="#+id/txtLikeUnlike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="2dp"
android:layout_toRightOf="#+id/imgUnlike"
android:background="#drawable/get_notification_bg"
android:gravity="center"
android:padding="2dp"
android:textColor="#color/white"
android:textSize="10sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/imgComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:contentDescription="#string/content_description"
android:src="#drawable/comments" />
<TextView
android:id="#+id/txtComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/imgComments"
android:background="#drawable/get_"
android:gravity="center"
android:padding="2dp"
android:textColor="#android:color/white"
android:textSize="10sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/imgShare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:contentDescription="#string/content_description"
android:src="#drawable/share" />
</RelativeLayout>
</LinearLayout>
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:text="id" />
<ImageView
android:id="#+id/imgBlueStrip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtId"
android:contentDescription="#string/content_description"
android:src="#drawable/blue_strip" />
</RelativeLayout>
My Layout Display Like this,
listView.setAdapter() is crashing my program. Anyone have any idea why the crash might be happening?
Logcat error:
AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
Activity:
public class SavedVideosFragment extends Fragment {
View rootview;
MySQLiteHelper mydb;
private SavedVideoAdapter mSavedVideoAdapter;
ListView listView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.saved_video_fragment_layout,container,false);
getSavedVideo();
listView = (ListView)rootview.findViewById(R.id.savedVideoListView);
return rootview;
}
public void getSavedVideo() {
mydb = new MySQLiteHelper(getActivity());
ArrayList savedVideoIDs = mydb.getAllSavedVideo();
mSavedVideoAdapter = new SavedVideoAdapter(getActivity(), savedVideoIDs, mydb);
listView.setAdapter(mSavedVideoAdapter);
}
}
Adapter:
public class SavedVideoAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Object> mData = new ArrayList<Object>();
MySQLiteHelper mydb;
private LayoutInflater mInflater;
public SavedVideoAdapter(Context context, ArrayList<Object> data, MySQLiteHelper database) {
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mData = data;
mydb = database;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
Object obj = mData.get(position);
return "";
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Cursor res = res = mydb.getData((Integer)mData.get(position));
convertView = mInflater.inflate(R.layout.saved_video_adapter, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
TextView activity = (TextView) convertView.findViewById(R.id.activity);
TextView activityDate = (TextView) convertView.findViewById(R.id.activityDate);
ImageView cancel = (ImageView) convertView.findViewById(R.id.x);
activity.setText(res.getColumnIndex("title"));
return convertView;
}
}
ListView XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/savedVideoListView"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Adapter Layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:src="#drawable/ic_launcher" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#id/thumbnail">
<TextView
android:id="#+id/activity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp" />
<TextView
android:id="#+id/activityDate"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_below="#+id/activity"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="?android:attr/listPreferredItemHeight"
android:layout_height="fill_parent"
android:layout_alignParentRight="true">
<ImageView
android:id="#+id/x"
android:layout_width="?android:attr/listPreferredItemHeight"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:src="#drawable/x" />
</RelativeLayout>
</RelativeLayout>
AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException
Because listView is not initialized.
Call getSavedVideo() method after initializing listView :
listView = (ListView)rootview.findViewById(R.id.savedVideoListView);
getSavedVideo();
I have a model class. Now from my activity i want to set the values in model class & show them in gridview using my custom adapter. After that i need to store the object in a variable(class type) from gridview's onItemClick. I have done the below codes. But its not working. Where did i go wrong?
activity_country.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CountryActivity" >
<TextView
android:id="#+id/nTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="26dp"
android:text="Name" />
<TextView
android:id="#+id/aTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nTextView"
android:layout_below="#+id/nTextView"
android:layout_marginTop="24dp"
android:text="About" />
<EditText
android:id="#+id/CountryNameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/nTextView"
android:layout_alignBottom="#+id/nTextView"
android:layout_marginLeft="48dp"
android:layout_toRightOf="#+id/nTextView"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/CountryAboutEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryNameEditText"
android:layout_alignTop="#+id/aTextView"
android:ems="10" />
<Button
android:id="#+id/saveCountryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryAboutEditText"
android:layout_below="#+id/CountryAboutEditText"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:text="Save"
android:onClick="saveCountry"
/>
<GridView
android:id="#+id/countryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/saveCountryButton"
android:layout_centerHorizontal="true"
android:numColumns="2">
</GridView>
</RelativeLayout>
CountryActivity.java
public class CountryActivity extends Activity
{
ArrayList<Country> countries = new ArrayList<Country>();
Country aCountry;
EditText CountryNameTxtBox;
EditText CountryAboutTxtBox;
GridView countrygGridView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country);
// Show the Up button in the action bar.
setupActionBar();
CountryNameTxtBox = (EditText)findViewById(R.id.CountryNameEditText);
CountryAboutTxtBox = (EditText)findViewById(R.id.CountryAboutEditText);
countrygGridView = (GridView)findViewById(R.id.countryGridView);
}
public void saveCountry(View view)
{
String txtName = CountryNameTxtBox.getText().toString();
String txtAbout = CountryAboutTxtBox.getText().toString();
showGrid();
}
public void showGrid()
{
/*
ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(this,android.R.layout.simple_list_item_1, countries);
countrygGridView.setAdapter(adapter);
*/
countrygGridView.setAdapter(new myAdapter(this,countries));
countrygGridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
for(Country mCountry: countries)
{
if(countries.contains(aCountry))
{
Toast.makeText(CountryActivity.this,countries.get(position).getName(), 2000).show();
}
}
}
});
}
countrygrid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
</LinearLayout>
myAdapter.java
public class myAdapter extends BaseAdapter
{
Context mycontext;
ArrayList<Country> countries;
public myAdapter(Context c, ArrayList<Country> obj)
{
this.mycontext=c;
this.countries = obj;
}
public int getCount() {
// TODO Auto-generated method stub
return countries.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return countries.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertview, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if(convertview==null)
{
gridView =new View(mycontext);
gridView =inflater.inflate(R.layout.countrygrid, null);
TextView txtvw1 = (TextView) gridView.findViewById(R.id.label1);
txtvw1.setText(countries.get(position).getName());
TextView txtvw2 = (TextView) gridView.findViewById(R.id.label2);
txtvw2.setText(countries.get(position).getAbout());
}
else
{
gridView = (View) convertview;
}
return gridView;
}
}
*Its showing error in countryActivity.java- when i am trying to set the adapter inside showGrid() *
countrygGridView.setAdapter(new myAdapter(this,countries));
public class myAdapter
{
does not extend anything
It should be
public class myAdapter extends BaseAdapter //orArrayAdapter
{
If you still have a problem post the stacktrace for further help
i am trying to display image using GridView. This is the first time i using GridView, so i using the example from here and implement it to mine (i have tried the example that contained there, and it's works).
But, i have checked it many time, there's no error comes from LogCat, no Force Closed, the image didn't show. i have no idea where's the wrong part.
Here's my code:
choosepic.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg_inner">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/book_inner"
android:layout_marginTop="50dp"
/>
<ImageButton
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/home_btn"
android:background="#null"
/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/bg_arrow_btn"
android:layout_alignParentRight="true"
/>
<ImageButton
android:id="#+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/right_arrow"
android:background="#null"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_marginRight="7dp"
android:layout_marginLeft="7dp"
/>
<ImageButton
android:id="#+id/prevBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/left_arrow"
android:background="#null"
android:layout_toLeftOf="#+id/nextBtn"
android:layout_marginTop="5dp"
/>
<GridView
android:id="#+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="30dp"
android:stretchMode="columnWidth"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="70dp"
>
</GridView>
</RelativeLayout>
animalbutton.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:visibility="gone">
</TextView>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
public ImageAdapter(Activity activity,ArrayList<String> listName, ArrayList<Integer> listImage) {
super();
this.listNm = listName;
this.listAnim = listImage;
this.activity = activity;
}
public static class ViewHolder
{
public ImageView imgViewAnim;
public TextView txtViewAnim;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.animalbutton, null);
view.txtViewAnim = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewAnim = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewAnim.setText(listNm.get(position));
view.imgViewAnim.setImageResource(listAnim.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listNm.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
choosepic.java
public class choosepic extends Activity {
/** Called when the activity is first created. */
ImageAdapter mAdapter;
GridView gridView;
static final String[] animal = new String[] {
"cat", "cow","croc", "duck", "elephant", "giraffe", "lion", "moose", "mouse"};
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosepic);
gridView = (GridView) findViewById(R.id.gridView1);
prepare_list1();
mAdapter = new ImageAdapter(this,listNm, listAnim);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Toast.makeText(getApplicationContext(), mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepare_list1(){
listNm = new ArrayList<String>();
listAnim = new ArrayList<Integer>();
for (int i = 0; i < animal.length; i++) {
listNm.add(animal[i]);
listAnim.add(getResources().getIdentifier("anim_"+animal[i], "drawable", getPackageName()));
}
}
}
i need some help. i appreciate any help. thank you in advance!
i think the problem is in your getCount() that returns 0 elements
instead of that make it like this
#Override
public int getCount() {
// TODO Auto-generated method stub
return listNm.size();
}