how to call another activity on clicking a listview - android

Listing all the songs read form external storage. On clicking a song it should go to SecondActivity.java
MainActivity.java
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.example.shubham.hymnattune";
private List peers = new ArrayList();
private MainActivity.MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra(EXTRA_MESSAGE,currentFile);
startActivity(intent);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long duratioInMs = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) duratioInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
};
Receive the song selected in MainActivity.java and play it.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
//private MainActivity.MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekBar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
// private final IntentFilter intentFilter = new IntentFilter();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
selectedFile = (TextView) (findViewById(R.id.selectedfile));
seekBar = (SeekBar) (findViewById(R.id.seekbar));
playButton = (ImageButton) (findViewById(R.id.play));
prevButton = (ImageButton) (findViewById(R.id.prev));
nextButton = (ImageButton) (findViewById(R.id.next));
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekBar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
playButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
}
Intent intent=getIntent();
currentFile=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
startPlay(currentFile);
}
This is my main layout file. containing a list of songs from external storage.
activity_main.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: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"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
</LinearLayout>
This is my xml file of second activity which is used for playing a song.
second.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: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"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.SecondActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:background="#android:drawable/screen_background_light"
android:id="#+id/linear2"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/selectedfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No File Selected"
android:textColor="#android:color/black" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>

try this
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);
}
});

I have used a code inside my adaptor class to implement on item click.. Check this code
public class LazyAdapter extends BaseAdapter {
private VideoActivity mainactivity;
private String[] result,imageId,title;
private static LayoutInflater inflater=null;
Context context;
public LazyAdapter(VideoActivity mainactivity, String[] videourls, String[] imgurls, String [] explist) {
context = mainactivity;
result = videourls;
imageId=imgurls;
title = explist;
inflater = (LayoutInflater)mainactivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(mainactivity.getApplicationContext());
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.listview, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
Glide.with(context)
.load(imageId[position])
.into(holder.img);
holder.tv.setText(title[position]);
// imageLoader.DisplayImage(result[position], holder.img);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+title[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, VideoActivity2.class);
intent.putExtra("imgid",title[position]);
intent.putExtra("videourl",result[position]);
context.startActivity(intent);
}
});
return rowView;
}
}
In this code I also have added a code to pass data on clicking each item in the list view.. Hope this one helps you

Related

Android: Audio is Playing but I am unable to hear

I am taking a course on Udacity and building an app.
Question - Audio is Playing but I am unable to hear??
I came to know the audio is playing when I log the information in the WordAdapter.java file
Files are mentioned below -
NumbersActivity.java
package com.example.miwok;
{VARIOUS IMPORT SATEMENTS}
public class NumbersActivity extends AppCompatActivity {
private MediaPlayer audio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word("One", "lutti", R.drawable.number_one, R.raw.number_one));
words.add(new Word("Two", "ottiko", R.drawable.number_two, R.raw.number_two));
words.add(new Word("Three", "tolookosu", R.drawable.number_three, R.raw.number_three));
WordAdapter itemsAdapter = new WordAdapter(this, words, R.color.category_numbers);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);
}
}
Word.java (Class)
package com.example.miwok;
public class Word {
private String mEnglishWord;
private String mMiwokWord;
private int mImageResourceId = NO_IMAGE_PROVIDED;
private int mAudioResourceId;
private static final int NO_IMAGE_PROVIDED = -1;
public Word(String englishTranslation, String miwokTranslation, int imageResourceId, int audioResourceId) {
mEnglishWord = englishTranslation;
mMiwokWord = miwokTranslation;
mImageResourceId = imageResourceId;
mAudioResourceId = audioResourceId;
}
public Word(String englishTranslation, String miwokTranslation, int audioResourceId) {
mEnglishWord = englishTranslation;
mMiwokWord = miwokTranslation;
mAudioResourceId = audioResourceId;
}
public String getEnglishWord() {
return mEnglishWord;
}
public String getMiwokWord() {
return mMiwokWord;
}
public int getImageResourceId() {
return mImageResourceId;
}
public int getAudioResourceId(){ return mAudioResourceId; }
public boolean hasImage(){
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
WordAdapter.java (Class)
package com.example.miwok;
{VARIOUS IMPORT SATEMENTS}
public class WordAdapter extends ArrayAdapter {
private int mBackgroundColour;
private MediaPlayer audio;
public WordAdapter(Activity context, ArrayList<Word> words, int colour){
super(context, 0, words);
mBackgroundColour = colour;
}
#Override
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);
}
Word currentWord = (Word) getItem(position);
LinearLayout word_item = (LinearLayout) listItemView.findViewById(R.id.word_item);
TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_word);
TextView englishTextView = (TextView) listItemView.findViewById(R.id.english_word);
ImageView wordImageView = (ImageView) listItemView.findViewById(R.id.word_image);
if (currentWord.hasImage()){
wordImageView.setImageResource(currentWord.getImageResourceId());
wordImageView.setVisibility(View.VISIBLE);
}else{
wordImageView.setVisibility(View.GONE);
}
miwokTextView.setText(currentWord.getMiwokWord());
englishTextView.setText(currentWord.getEnglishWord());
View text_container = listItemView.findViewById(R.id.word_container);
int color = ContextCompat.getColor(getContext(), mBackgroundColour);
text_container.setBackgroundColor(color);
word_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Hi", Toast.LENGTH_LONG).show();
audio = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
audio.start();
Log.i("isplaying", String.valueOf(audio.isPlaying()));
}
});
return listItemView;
}
}
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="88dp"
android:id="#+id/word_item">
<ImageView
android:id="#+id/word_image"
android:layout_width="88dp"
android:layout_height="88dp"
android:background="#color/tan_background"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/word_container"
android:paddingLeft="16dp">
<TextView
android:id="#+id/miwok_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:layout_weight="1"
android:gravity="bottom"
android:textColor="#color/white"
tools:text="miwok" />
<TextView
android:id="#+id/english_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_weight="1"
android:gravity="top"
android:textColor="#color/white"
tools:text="english"/>
</LinearLayout>
</LinearLayout>
Again - Audio is Playing but I am unable to hear.
try change WordAdapter.java (Class) audio = MediaPlayer.create(getContext(), currentWord.getAudioResourceId()); to audio = MediaPlayer.create(getContext().getApplicationContext(), currentWord.getAudioResourceId());

application crashes when trying work with custom list adapter, cant find the error

I'm trying to create simple list of Objects which i created
the objects are ShopListItem, this is the code of the class:
public class ShopListItem {
private String name;
private double price;
public ShopListItem(String name , double price)
{
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
}
this is the ArrayAdatpter class:
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
public shopItemAdapter(Context context, ArrayList<ShopListItem> items){
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ShopListItem item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shop_item_row, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.itemName);
TextView price = (TextView) convertView.findViewById(R.id.itemPrice);
name.setText(item.getName());
price.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
and this is my activity which is supposed to display this list:
public class check extends Activity {
ListView items = (ListView)findViewById(R.id.items);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , list);
items.setAdapter(adapter);
}
}
I open the activity from another activity when user clicks a button, this is the on click method:
public void openList(View view){
Intent intent = new Intent(HomeActivity.this , check.class);
this.startActivity(intent);
}
shop_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF9F9F9"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/itemName"
android:layout_weight="0.61"
android:layout_margin="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/itemPrice"
android:layout_margin="5dp" />
</LinearLayout>
and content_check.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="atoa.roomates.QA"
tools:showIn="#layout/activity_q">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/items"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
thank you!
You are accessing view ListView items = (ListView)findViewById(R.id.items); before onCreate(). So move that line in onCreate method after setContentView().
initialize your list in setContentView instead of top
like following
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_demo);
items = (ListView) findViewById(R.id.items);
after change this work fine.
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
private Context mContext;
private List<ShopListItem> mListShop;
public shopItemAdapter(Context context, int resource, ArrayList<ShopListItem> items){
super(context, resource, items);
this.mContext= context;
this.mListShop = items;
}
#Override
public int getCount() {
return mListShop.size();
}
#Override
public ShopListItem getItem(int position) {
return mListShop.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.shop_item_row, null);
holder = new ViewHolder();
holder.mTextPrice = (TextView) view.findViewById(R.id.itemPrice);
holder.mTextName = (TextView) view.findViewById(R.id.itemName);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ShopListItem item = getItem(position);
holder.mTextName.setText(item.getName());
holder.mTextPrice.setText(item.getPrice());
return view;
}
public class ViewHolder {
public TextView mTextPrice;
public TextView mTextName;
}
}
In your Activity
public class check extends Activity {
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView)findViewById(R.id.items);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , R.layout.shop_item_row, list);
items.setAdapter(adapter);
}
}
Try it!!!!

Android : how to get value from assets and pass it thru array

I want to short my code length by using array.If I have 100 button or image view I have to write for 100 . I want to get value from assets folder and pass it in to array . how to use
String[] colorNames = getResources().getStringArray(R.array.colorList);
String[] animalNames = getResources().getStringArray(R.array.animalList);
Current working code :
public class Main extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag);
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
image = (ImageView) findViewById(R.id.image);
Button btn1,btn2;
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
if(key.equals("animalIntent") )
{
btn1.setText("cat");
btn2.setText("dog");
// same for 100 button ............. here i want to short my code
} else {
btn1.setText("red");
btn2.setText("blue");
}
}
public void btn1(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.cat);
// same for 100 image view ............. here i want to short my code
} else {
image.setBackgroundResource(R.drawable.red);
}
}
public void btn2(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.dog);
} else {
image.setBackgroundResource(R.drawable.blue);
}
}
To do that you should use GridView,it would be best option. try the below sample code.
Step-1 add the gridview in your drag.xml
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/edt"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
Step-2 Declare the variables and get the grid view reference.
GridView gridview;
Integer[] drawableIds = { R.drawable.poster1, R.drawable.poster2, R.drawable.poster3, R.drawable.poster4,
R.drawable.poster5 };
String[] colorNames = { "poster one", "poster two", "poster three", "poster four", "poster five" };
//In OnCreate() method add
gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new CustomGridAdapter(this, drawableIds, colorNames));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(Main.this, "" + position, Toast.LENGTH_LONG).show();
}
});
Step-3 create a class for grid adapter CustomGridAdapter.class
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private Integer[] drawableitems;
private String[] drawablelabel;
public CustomGridAdapter(Context context, Integer[] drawableitems, String[] drawablelabel) {
this.context = context;
this.drawablelabel = drawablelabel;
this.drawableitems = drawableitems;
}
#Override
public int getCount() {
return drawableitems.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
RecordHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new RecordHolder();
convertView = inflater.inflate(R.layout.grid_item, null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.grid_item_label);
holder.imageItem = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (RecordHolder) convertView.getTag();
}
holder.txtTitle.setText(drawablelabel[position]);
holder.imageItem.setImageResource(drawableitems[position]);
return convertView;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
Add custom view for grid grid_item.xml in layout folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" >
</ImageView>
<TextView
android:id="#+id/grid_item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" >
</TextView>
</LinearLayout>
Hope it will help you.

My listView shows only one record of 3

I have a list view which displays only one record always, I've traced my program and find that there are 3 records in my arrayList which I'm passing to the listView adapter. After tracing into getView of list view I find that It executes more that 3 times with position of 0!
I have no idea what's the problem, please help me if you can.
activity_news.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:background="#color/background"
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=".News" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/lvNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" />
</ScrollView>
</RelativeLayout>
this is row template for listView: news_row.xml
<?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="wrap_content"
android:background="#drawable/message_row_style"
android:layout_gravity="right"
android:gravity="right"
android:orientation="vertical" >
<LinearLayout
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:gravity="right"
android:background="#color/red"
/>
<TextView
android:id="#+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:background="#color/blue"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
newsAdapter.java:
public class NewsAdapter extends BaseAdapter{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#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 parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}
Do following changes in your getView
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
ViewHolder holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
convertView.setTag(holder);
}
ViewHolder hold=(ViewHolder)convertView.getTag();
News temp = list.get(position);
hold.title.setText(temp.getTitle());
hold.date.setText(temp.getsDate());
title.setOnClickListener(onClickListener);
return row;
}
add this class in your adapter file
static class ViewHolder
{
TextView title;
TextView date;
}
You should call super in the constructor of your adapter change your adapter as following:
public class NewsAdapter extends ArrayAdapter<News>{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
super(c,-1,l);//<-- **pass your item list to super**
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#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 parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}

Custom list displayed is empty

I have a donorview class which extends linearlayout which is as follows:
public class donorview extends LinearLayout {
private TextView donortext;
private String donorstr;
private ImageButton call;
private ImageButton msg;
private String donornumber;
private Context context1;
private View convertView;
public donorview(Context context, String donorname1, String donornum) {
super(context);
context1 = context;
// TODO Auto-generated constructor stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listformat, null);
convertView.setClickable(true);
donortext = (TextView) findViewById(R.id.donornametext);
call = (ImageButton) findViewById(R.id.call);
msg = (ImageButton) findViewById(R.id.msg);
System.out.println("donorname:"+donorname1);
System.out.println("donornum:"+donornum);
donortext.setText(donorname1);
System.out.println("after setting text");
donorstr = donorname1;
donornumber = donornum;
}
void onClickCall(){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + donornumber));
convertView.getContext().startActivity(callIntent);
}
public void setdonorname(String donorname12) {
donortext.setText(donorname12);
}
public String getdonorname() {
return this.donorstr;
}
}
I get a NullPoinerException as
java.lang.NullPonintereException
at com.wglxy.example.dash1.donorview.<init>(donorview.java:35)
while setting the text of the textview donortext. My XML layout of the listformat is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/linerlayout1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/donornametext" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_weight="1" android:text="a"/>
<ImageButton android:layout_width="wrap_content" android:id="#+id/call"
android:layout_height="wrap_content" android:contentDescription="#string/description_about"
android:src="#drawable/call" android:onClick="onClickCall"
android:background="#ffffff" />
<ImageButton android:layout_width="wrap_content" android:id="#+id/msg"
android:layout_height="wrap_content" android:contentDescription="#string/description_about"
android:src="#drawable/msg" android:onClick="onClickMsg"
android:background="#ffffff" />
</LinearLayout>
I dont understand what I am doing wrong. The list that is being displayed is empty. When i am printing the donorname and donornum it is being printed but the custom list displayed is empty.I have been trying to figure it out from a long time. Could anyone please help me with this?
My adapter code is as follows
public class donorAdapter extends BaseAdapter {
private Activity activity;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> nums = new ArrayList<String>();
private Context context;
private String strnum;
private String strname;
private static LayoutInflater inflater = null;
public donorAdapter(Context context, Activity a, ArrayList<String> names,
ArrayList<String> nums) {
this.context = context;
activity = a;
this.names = names;
this.nums = nums;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return names.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
donorview fv;
if (convertView == null) {
System.out.println("inside getview:"+names.get(position).toString());
strname=names.get(position).toString();
strnum=nums.get(position).toString();
System.out.println("inside getview:"+nums.get(position).toString());
fv = new donorview(context, strname,strnum);
convertView = fv;
}
else {
((donorview) convertView).setdonorname(names.get(position)
.toString());
}
convertView.setClickable(true);
convertView.setFocusable(true);
return convertView;
}
}
-Thanks in advance
You should use
donortext = (TextView)convertView.findViewById(R.id.donornametext);
and also replace your code by
convertView = inflater.inflate(R.layout.listformat, this);
Replace
findViewById
with
convertView.findViewById()
you use findViewById, when you have already set the content for the activity, in your case you did not , so you have to specify which view it has to look to get the id. You have to do the same for the rest of your views.

Categories

Resources