Android: Audio is Playing but I am unable to hear - android

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());

Related

Hide Buttons from ListView based on UserType

I have a login page, when the user login it will redirect him to ListViewAct which contain image, buttons,and textviews.
After the redirection i created an if condition to check for the usertype logged in either is an admin or normal user.
I have three buttons (Add,edit,delete) i want to hide those buttons from the normal user.
I've tried to setvisibility for those buttons to GONE but as result while debugging nothing happens and the buttons still appearing for the normal user.
MainAct code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btn_add,btn_edit,btn_delete=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String username = intent.getStringExtra("Username");
String password = intent.getStringExtra("Password");
btn_add = findViewById(R.id.btn_add);
btn_edit = findViewById(R.id.btn_edit);
btn_delete = findViewById(R.id.btn_delete);
if(username.equals("admin") && password.equals("admin")){
Log.d(TAG, "onCreate: Started.");
ListView listView = (ListView) findViewById(R.id.li_view);
ArrayList<PersonInfo> students = new ArrayList<>();
students.add(new PersonInfo(android.R.drawable.btn_star, "test", "03/27/1998"));
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students);
listView.setAdapter(studentsListAdapter);
}
else if (username.equals("user") && password.equals("user"))
{
ListView listView = (ListView) findViewById(R.id.li_view);
ArrayList<PersonInfo> students = new ArrayList<>();
students.add(new PersonInfo(android.R.drawable.btn_star, "test", "03/27/1998"));
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students);
listView.setAdapter(studentsListAdapter);
if (btn_add != null && btn_edit !=null && btn_delete !=null){
btn_add.setVisibility(View.GONE);
btn_edit.setVisibility(View.GONE);
btn_delete.setVisibility(View.GONE);
}
}
}
}
ListAdapter code:
public class StudentsListAdapter extends ArrayAdapter<PersonInfo> {
private Context contxt;
private int rsrc;
private List<PersonInfo> persons;
public StudentsListAdapter( Context context, int resource, List<PersonInfo> _persons) {
super(context, resource, _persons);
contxt = context;
rsrc = resource;
persons=_persons;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(contxt);
View view = inflater.inflate(rsrc, null,false);
ImageView imageView = view.findViewById(R.id.imgP);
TextView pName = view.findViewById(R.id.txtView2);
TextView pBirthday = view.findViewById(R.id.txtView3);
PersonInfo p = persons.get(position);
imageView.setImageDrawable(contxt.getResources().getDrawable(p.getImage()));
pBirthday.setText(p.getBirthday());
pName.setText(p.getName());
return view;
}
}
ListView 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:padding="15dp"
android:layout_height="match_parent"
android:weightSum="100" >
<ImageView
android:id="#+id/imgP"
android:layout_width="399dp"
android:layout_height="150dp"
android:layout_weight="66.6" />
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="33.3">
<TextView
android:gravity="center"
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/txtView2"/>
<TextView
android:id="#+id/txtView3"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#+id/txtView2"
android:gravity="center"
android:text="TextView3" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<Button
android:id="#+id/btn_add"
android:layout_width="69dp"
android:layout_height="wrap_content"
android:layout_below="#+id/txtView3"
android:layout_marginRight="20dp"
android:text="ADD" />
<Button
android:layout_width="69dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/btn_add"
android:layout_below="#id/txtView3"
android:id="#+id/btn_edit"
android:text="edit"/>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/btn_edit"
android:layout_below="#+id/txtView3"
android:id="#+id/btn_delete"
android:text="Delete"/>
</RelativeLayout>
</LinearLayout>
Mainact XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<ListView
android:id="#+id/li_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
tools:layout_algignParentStart="true" />
</androidx.constraintlayout.widget.ConstraintLayout>
PersonInfo Class:
public class PersonInfo {
private int image;
private String name;
private String birthday;
public PersonInfo(int image, String name, String birthday) {
this.image = image;
this.name = name;
this.birthday = birthday;
}
public String getName(){
return name;
}
public int getImage() {
return image;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
I didn't make any changes for the buttons on the ListAdapter.
What i am doing wrong?
Any help will be greatly appreciated.
Thank you!
According your xml your buttons are inside ListView's item. So, you have to handle it inside adapter not in fragment. Check below:
public class StudentsListAdapter extends ArrayAdapter<PersonInfo> {
private Context contxt;
private int rsrc;
private List<PersonInfo> persons;
private boolean isAdmin;
public StudentsListAdapter( Context context, int resource, List<PersonInfo> _persons, boolean _isAadmin) {
super(context, resource, _persons);
contxt = context;
rsrc = resource;
persons=_persons;
isAdmin = _isAadmin;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(contxt);
View view = inflater.inflate(rsrc, null,false);
ImageView imageView = view.findViewById(R.id.imgP);
TextView pName = view.findViewById(R.id.txtView2);
TextView pBirthday = view.findViewById(R.id.txtView3);
Button btn_add = view.findViewById(R.id.btn_add);
Button btn_edit = view.findViewById(R.id.btn_edit);
Button btn_delete = view.findViewById(R.id.btn_delete);
if(isAdmin) {
btn_add.setVisibility(View.VISIBLE);
btn_edit.setVisibility(View.VISIBLE);
btn_delete.setVisibility(View.VISIBLE);
} else {
btn_add.setVisibility(View.GONE);
btn_edit.setVisibility(View.GONE);
btn_delete.setVisibility(View.GONE);
}
PersonInfo p = persons.get(position);
imageView.setImageDrawable(contxt.getResources().getDrawable(p.getImage()));
pBirthday.setText(p.getBirthday());
pName.setText(p.getName());
return view;
}
}
Then modify your fragment to call adapter like below:
ListView listView = (ListView) findViewById(R.id.li_view);
ArrayList<PersonInfo> students = new ArrayList<>();
students.add(new PersonInfo(android.R.drawable.btn_star, "test", "03/27/1998"));
if(username.equals("admin") && password.equals("admin")){
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students, true); // true -> admin user
} else if (username.equals("user") && password.equals("user")) {
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students, false); // false -> normal user
}
listView.setAdapter(studentsListAdapter);
you declared private Button btn_add,btn_edit,btn_delete=null; remove null from there.
and make private Button btn_add,btn_edit,btn_delete;` then try run project let me know this answer helped you.

i have array of objects. i want to display its elements in a listview

i have array of objects carts containing itemname and price. Array is coming correctly from sqlite database. i want to display it in a listview. But in a listview it is only showing the package name not itemname and price. I think problem is in this line "ListAdapter buckysAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, carts); "of Main2Activity.java
Below is my code please guide me.It is very important for me
Main2Activity.java
public class Main2Activity extends Activity {
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
final int position = intent.getIntExtra("history",1);
Log.i("positin","position = "+String.valueOf(position));
dbHandler = new MyDBHandler(this,null,null,6);
Cart[] carts = dbHandler.databaseToArray(position);
for (Cart c : carts)
Log.i("jhnbvb1","item1 = "+c.getItemname()+" price1 = "+c.getPrice());
ListAdapter buckysAdapter = new ArrayAdapter<Cart>(this, android.R.layout.simple_list_item_1, carts);
ListView buckysListView = (ListView) findViewById(R.id.buckysListView2);
buckysListView.setAdapter(buckysAdapter);
}}
CustomAdapter2.java
public class CustomAdapter2 extends ArrayAdapter<Cart> {
public CustomAdapter2(Context context, Cart[] foods) {
super(context, R.layout.custom_row2 ,foods);
}
#Override
public Cart getItem(int position) {
return super.getItem(position);
}
#Override
public int getPosition(Cart item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater buckysInflater = LayoutInflater.from(getContext());
View customView = buckysInflater.inflate(R.layout.custom_row2, parent, false);
Cart singleFoodItem = getItem(position);
String name = singleFoodItem.getItemname();
String price = singleFoodItem.getPrice();
Log.i("rtyiykj","item2 = "+name+" price2 = "+price);
TextView buckysText = (TextView) customView.findViewById(R.id.buckysText2);
TextView buckysText1 = (TextView) customView.findViewById(R.id.buckysText3);
buckysText.setText(name);
buckysText1.setText(price);
return customView;
}}
custom_row2.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">
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText2"
android:layout_margin="5dp" />
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText3"
android:layout_margin="5dp" />
activity_main2.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Main2Activity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/buckysListView2"></ListView>
cart.java
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public Cart() {}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}}
You use standard ArrayAdapter instead of that one created by you. It should be
CustomAdapter2<Cart> buckysAdapter = new CustomAdapter2<Cart>(this, carts);
And array adapter itself should be modified:
public class CustomAdapter2 extends ArrayAdapter<Cart> {
private final List<Object> foods;
public CustomAdapter2(Context context, List<Cart> foods) {
super(context, 0);
this.foods = foods;
}
#Override
public int getCount() {
return foods.size();
}
#Override
public Cart getItem(int position) {
return foods.get(position);
}
//your getView
}

how to call another activity on clicking a listview

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

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 - ArrayList<Integer> not displaying properly in custom listVIew

I have a custom listView with three textViews. The data comes from a class with three ArrayLists, two of which are strings and the last one is an Integer. I have no problems populating and adding items to the list as I saw that when I displayed the ArrayList values on logCat via log.d, all three ArrayLists had their respectful items.
It seems to me that there is something wrong with the way I display data.
Here are the files:
list_row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="221dp"
android:layout_toLeftOf="#+id/quantity"
android:text="unit" />
</RelativeLayout>
Here is the part in my activity_order_form.xml that has the listView element.
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayout2"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewVariantB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="94dp"
android:text="Variant"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="123dp"
android:text="Unit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewProductOrder"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewVariantB" >
</ListView>
</RelativeLayout>
Here is the class where the ArrayList are stored.
public class CurrentOrderClass {
private String productName;
//ArrayLists
private ArrayList<String> variantArray = new ArrayList<String>();
private ArrayList<String> unitArray = new ArrayList<String>();
private ArrayList<Integer> quantityArray = new ArrayList<Integer>();
//TODO ArrayList functions
public ArrayList<String> getUnitArray() {
return unitArray;
}
public void setUnitArray(ArrayList<String> unitArray) {
this.unitArray = unitArray;
}
public void addToUnitArray(String unit){
this.unitArray.add(unit);
}
public ArrayList<Integer> getQuantityArray() {
return quantityArray;
}
public void setQuantityArray(ArrayList<Integer> quantityArray) {
this.quantityArray = quantityArray;
}
public void addToQuantityArray(int quantity){
this.quantityArray.add(quantity);
}
public ArrayList<String> getVariantArray() {
return variantArray;
}
public void setVariantArray(ArrayList<String> variantArray) {
this.variantArray = variantArray;
}
public void addToVariantArray(String variantArray){
this.variantArray.add(variantArray);
}
}
Here is the CustomListAdapter.java file
public class CustomListAdapter extends BaseAdapter {
private ArrayList<CurrentOrderClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void setListData(ArrayList<CurrentOrderClass> data){
listData = data;
}
}
This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView.
public class OrderForm extends Activity {
public TextView tv;
private int variantPosition;
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
tv = (TextView)findViewById(R.id.textViewProduct);
//set variants here
popolateItem();
//set current order listview here
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
if(currentOrder.getQuantityArray().size() > 10){
loopUntil = currentOrder.getQuantityArray().size();
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray();
currentOrder.getUnitArray();
currentOrder.getVariantArray();
results.add(currentOrder);
}
}
else{
loopUntil = 10;
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray().add(i);
currentOrder.getUnitArray().add("Sample text here." + i);
currentOrder.getVariantArray().add("Another sample text here" + i);
results.add(currentOrder);
}
}
return results;
}
}
When I execute a Log.d statement to display the contents of my ArrayLists, it shows that my quantityArray has elements [0, 1, 2, 3, 4, 5, 6, 7, 9].
I know I can just convert quantityArray to an ArrayList from an ArayList, but I don't want to do that.
I think there's something wrong with my CustomListAdapter.
Any thoughts?
There is no where that you actually set the view, as in, it doesn't do anything, if convertView is null, you can't call any methods of it, convertView, if its is not null, will be ViewHolder in your context, what you need to do is have an object which is extending some type of view, instantiate it, give it methods to set the values, things like that.
For example here is what I use in an adapter that displays simple messages:
public class MessageView extends RelativeLayout {
private TextView mBody;
private String mBodyString = "";
private boolean mDrawn = false;
private boolean mLocal = false;
public MessageView(Context context) {
super(context);
this.drawView();
}
public MessageView(Context context, String body) {
super(context);
mBodyString = body;
this.drawView();
}
public MessageView(Context context, String body, boolean local) {
super(context);
mBodyString = body;
mLocal = local;
this.drawView();
}
private void drawView() {
if (mDrawn)
return;
mDrawn = true;
this.removeAllViews();
LayoutInflater li = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if(mLocal){
this.addView(li.inflate(R.layout.list_item_message_device, this, false),
params);
}else{
this.addView(li.inflate(R.layout.list_item_message_remote, this, false),
params);
}
mBody = (TextView) this.findViewById(R.id.tMessage);
mBody.setText(mBodyString);
}
public void setLocal(){
this.setLocal(true);
}
public void setLocal(boolean local){
mLocal = local;
mDrawn = false;
this.drawView();
}
public void setMessage(String body){
mBodyString = body;
mBody.setText(mBodyString);
}
}
I got it.
I changed
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
to
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityArray().get(position)));

Categories

Resources