My Custom ListView display nothing - java

I am newbie in android. I want to create a custom listview arrayadapter. I have followed some tutorial but my emulator shows nothing for the Custom ListView. Can anyone help me figure out where is wrong with my code? Thanks in advance.
Here is my custom_listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customListView" />
</LinearLayout>
This is my custom_listview_row.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"
android:gravity="center_vertical"
android:minHeight="64dp">
<!-- <ImageView
android:id="#+id/clv_imageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:contentDescription="#string/empty"
android:layout_alignParentLeft="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/> -->
<TextView
android:id="#+id/clv_textView2"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="#string/tv_definition"
android:textIsSelectable="true" />
<TextView
android:id="#+id/clv_textView"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:text="#string/tv_word"
android:textIsSelectable="true" />
</RelativeLayout>
Here is my MyPerformanceArrayAdapter.java
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyPerformanceArrayAdapter extends ArrayAdapter<DefinitionObject>{
private List<DefinitionObject> entries;
private Activity activity;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId, List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_listview_row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.clv_textView);
holder.item2 = (TextView) v.findViewById(R.id.clv_textView2);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final DefinitionObject custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getWord());
holder.item2.setText(custom.getFav());
}
return v;
}
}
and lastly, this is my Activity named TempCLV.java
package com.example.myidictionary;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
public class TempCLV extends Activity {
private MySQLiteDefinitionHelper db;
String tblName = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
}
public void refresh()
{
db = new MySQLiteDefinitionHelper(this);
final List<DefinitionObject> values = db.getAllWords(tblName);
ListView mylist = (ListView)findViewById(R.id.customListView);
MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, R.id.customListView, values);
mylist.setAdapter(adapter);
}
}

You need to call refresh in onCreate since you are setting the adapter to list view there.
Make sure your values has some data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
refresh();
}
Also you can move the inflater initialization to the constructor of adapter class. No need to initialize in getView
LayoutInflater vi;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId,List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
vi =(LayoutInflater)a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

Please call refresh method at least for first time to set the the adapter in your MainActivity' onCreate method..

Related

I get the error java.lang.NullPointerException when implementing Adapters

When I run the code I get following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at com.example.android.quakereport.EarthquakeAdapter.getView(EarthquakeAdapter.java:28)
Here is the code from EarthquakeAdapter.java which implements the adapter
package com.example.android.quakereport;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class EarthquakeAdapter extends ArrayAdapter<Earthquake>{
public EarthquakeAdapter(Context context, List<Earthquake> earthquakes) {
super(context, 0, earthquakes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView != null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.earthquake_list_item, parent, false);
}
Earthquake currentEarthquake = getItem(position);
TextView magnitudeView = (TextView) listItemView.findViewById(R.id.magnitude);
magnitudeView.setText(currentEarthquake.getMagnitude());
TextView locationView = (TextView) listItemView.findViewById(R.id.location);
locationView.setText(currentEarthquake.getLocation());
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
dateView.setText(currentEarthquake.getDate());
return listItemView;
}
}
Here is code of Earthquack.java which implements datastructure required by listview.
package com.example.android.quakereport;
public class Earthquake {
private String mMagnitude;
private String mLocation;
private String mDate;
public Earthquake(String magnitude, String location, String date){
mMagnitude = magnitude;
mLocation = location;
mDate = date;
}
public String getMagnitude(){ return mMagnitude;}
public String getLocation(){ return mLocation;}
public String getDate(){ return mDate;}
}
Here is code of EarthquackActivity.java is the equivalent to mainActivity.java
package com.example.android.quakereport;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class EarthquakeActivity extends AppCompatActivity {
public static final String LOG_TAG = EarthquakeActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
// Create a fake list of earthquake locations.
ArrayList<Earthquake> earthquakes = new ArrayList<>();
earthquakes.add(new Earthquake("8.9", "San Francisco", "Feb 2,2010"));
earthquakes.add(new Earthquake("8.2", "Paris", "March 5,2011"));
earthquakes.add(new Earthquake("8.1","Cape Town","May 22,2013"));
earthquakes.add(new Earthquake("9.9","Italy","Dec 4,2013"));
earthquakes.add(new Earthquake("5.9","India","Jan 12,2012"));
earthquakes.add(new Earthquake("7.9","New york","June 5,2015"));
earthquakes.add(new Earthquake("3.9","Germany","July 1,2012"));
// Find a reference to the {#link ListView} in the layout
ListView earthquakeListView = (ListView) findViewById(R.id.weather_list);
EarthquakeAdapter adapter = new EarthquakeAdapter(this, earthquakes);
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(adapter);
}
}
Code of earthquake_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for a list of earthquakes -->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/weather_list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And code for earthquake_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="#+id/magnitude"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="8.9"/>
<TextView
android:id="#+id/location"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="San Francisco, CA"/>
<TextView
android:id="#+id/date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="March 6, 2010"/>
</LinearLayout>
Thanks.
It might be the crashing when your convertview inside getView method is null. Then it will skip the if(listItemView != null) condition and no layout will be inflated hence, NPE will occur.
So try handling the case when its null & inflating the proper layout according to your use case
Replace if(listItemView != null) with if(listItemView == null)

How to add the ListView element to be referenced in the individual Activity files

The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.

Why isn't async stopping from recreating listview?

Wasn't really sure how to ask this but...
My code is meant to generate ListView input on a button click.
When I click the button it should .execute() an Async which takes a list of items and adds them to an ArrayList< HashMap < String, String > > with a custom adapter.
The problem is, when I press the button, it generates the list and adds it to the ListView, however, instead of going... 1, 2, 3, 4, 5, ....20 it goes in a random order. 1, 2, 5, 1, 3, 0, 6, 7, 8, 3, 1 ...
And if I scroll up or down the ListView it changes.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/bLoadData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Load api data" />
<ListView
android:id="#+id/lvMovies"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/bLoadData"
android:background="#efefef" />
</RelativeLayout>
results_layout.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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:id="#+id/ivPosters"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/place_holder_img"/>
<TextView
android:id="#+id/results_layout_tv_movie_name"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingStart="20dp"
android:paddingTop="10dp"
android:text="hellow"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
MainActivity.class:
package com.example.zdroa.testinggrounds;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
static ArrayList<HashMap<String, String>> posters;
ListView listView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvMovies);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println(posters.get(position).values().toString());
}
});
button = (Button) findViewById(R.id.bLoadData);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posters = new ArrayList<>();
ImageLoadTask ilt = new ImageLoadTask();
ilt.execute();
}
});
}
private class ImageLoadTask extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
posters = getPathFromAPI();
return posters;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
SearchAdapter adapter = new SearchAdapter(MainActivity.this, result);
listView.setAdapter(adapter);
}
private ArrayList<HashMap<String, String>> getPathFromAPI() {
String moviePaths[] = new String[10];
for (int i = 0; i < moviePaths.length; i++) {
HashMap<String, String> map = new HashMap<>();
String s = "path";
map.put(s, s + "_" + i);
moviePaths[i] = "path_" + i;
posters.add(map);
}
return posters;
}
}
}
SearchAdapter.class:
package com.example.zdroa.testinggrounds;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
public class SearchAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String, String>> array;
private ImageView imageView;
private TextView textView;
SearchAdapter(Context context, ArrayList<HashMap<String, String>> paths) {
mContext = context;
array = paths;
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.results_layout, null);
imageView = (ImageView) convertView.findViewById(R.id.ivPosters);
textView = (TextView) convertView.findViewById(R.id.results_layout_tv_movie_name);
}
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.place_holder_img);
String link_end = array.get(position).values().toString();
Picasso.with(mContext)
.load("http://image.tmdb.org/t/p/w185" + link_end)
// .resize(width, (int) (width * 1.5))
.placeholder(drawable)
.into(imageView);
textView.setText(position+"");
return convertView;
}
}
Your imageview and textview references are only set when the convertview is null...move those lines out of the parenthesis.
in onPost in Asyntask class
after creating and setting the adapter for listview
make the list that you're using in list view
list=new ArrayList<>();

Display Data in GridView with DataAdapter in Android

I have try the following code for displaying data from data adapter in gridview.
Following link is for GridView with DataAdapter Tutorial.
I am wanted the following output :
I have follow the tutorial and get the output as i wanted, but unfortunetly when scroll the page,
application will be closed automatically.
ERROR : "Application Failure Detected, Please Try Again"
How to resolve these problem?
code : main.xml file.
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:stretchMode="columnWidth"
android:cacheColorHint="#00000000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="2"
android:clipChildren="true"
android:horizontalSpacing="5dip"
android:verticalSpacing="5dip" />
code : MainActivity.java file.
package com.example.gridviewdata;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.GridView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new DataAdapter(this));
}
code : customgrid.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TableLayout android:id="#+id/TableLayout01"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TableRow android:id="#+id/TableRow01"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtId"
android:layout_gravity="center_horizontal" />
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtName"
android:layout_gravity="center_horizontal" />
</TableRow>
</TableLayout>
</LinearLayout>
code : DataAdapter.java file
package com.example.gridviewdata;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private String [] id = {"S001","S002","S003","S004","S005","S006","S007","S008","S009","S010","S011","S012"};
private String [] name={"Rohit","Rahul","Ravi","Amit","Arun","Anil","Kashif","Nayan","Jay","Sagar","Jairaj","Vishal"};
private LayoutInflater mInflater;
public DataAdapter(Context c)
{
mContext=c;
mInflater = LayoutInflater.from(c);
}
public int getCount()
{
return id.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.customgrid,parent,false);
holder = new ViewHolder();
holder.txtId=(TextView)convertView.findViewById(R.id.txtId);
holder.txtId.setPadding(100, 10,10 , 10);
holder.txtName=(TextView)convertView.findViewById(R.id.txtName);
holder.txtName.setPadding(100, 10, 10, 10);
if(position==0)
{
convertView.setTag(holder);
}
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtId.setText(id[position]);
holder.txtName.setText(name[position]);
return convertView;
}
static class ViewHolder
{
TextView txtId;
TextView txtName;
}
}
Give any solution for these problem.
if any other resource is available then give me an reference.
Solution :
In getView() method return all items, and i have setting the tag just in the first item,
when android calls again getView for position 1, i am try to get the tag from convertView,
but i didn't called setTag for convertView 1, then getTag returns a null object, and i am try to get the object txtName from a null object, and then the error occurs.
removing the if(position==0) then application work perfectly and give the scrolling.

ListView with Custom extended BaseAdapter not showing with SherlockFragment, need hints or suggestions

I am new to android programming and I seem to have come at a stand still for several days now. I am having trouble finding a solution to my problem and tried many different solutions without success. As the title suggests, my code runs successfully but the ListView does not show up on the selected Tabs. Any suggestions of tips would be helpful.
ItemGuide.Java ------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ItemGuide extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), LeatherTab.class, null);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), SilverTab.class, null);
}
}
LeatherTab.java --------------------------------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
TextView text = (TextView) view.findViewById(R.id.boxtest);//TextView for layout testing
text.setText("Hello");
ListView leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(getActivity())); //Custom list adapter passes Context
return view;
}
}
LeatherAdapter.java ------------------------------------------------------
package com.example.alzuni_project;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<images.length;i++) //Was originally 3
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
leatherfragment.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" >
<TextView
android:id="#+id/boxtest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCDDFF" />
<ListView
android:id="#+id/leather_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/boxtest" />
</RelativeLayout>
SingleRow.java -----------------------------------------------------
package com.example.alzuni_project;
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
single_row.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/leather_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="48dp"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/leather_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#CCCCCC" />
<TextView
android:id="#+id/leather_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/leather_icon"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_below="#+id/leather_title"
android:background="#CCDDFF" />
Your list seems empty , try this in your LeatherAdapter:
list.add(new SingleRow(titles[i],descriptions[i], images[i]));
Inside the for loop .

Categories