I am new to android please help me to play audio on list item click in fragment. I am using this code but on item click my app gets crash showing error.
I have tried the below code but my app crashes on click on item:
public class FragmentOne extends Fragment {
static MediaPlayer mediaPlaye;
int audioIndex;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_fragment_one, container, false);
ListView audioView = view.findViewById(R.id.listview1);
final ArrayList<String> audioList = new ArrayList<>();
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
final Cursor audioCursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioList.add(audioCursor.getString(audioIndex));
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
final ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),R.layout.tectcolor, audioList);
audioView.setAdapter(adapter);
audioView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Uri u = Uri.parse(audioList.get(i).toString());
mediaPlaye = MediaPlayer.create(getContext(), u);
mediaPlaye.start();
}
});
return view;
}
}
I am expecting to play audio on item click in fragment.
u must setOnclick in your Custom Adapter.
when u set onClick on your List, Android check all of your view of List and it will cause a crash.
create an adapter and override onClick in there.
have good coding...
Related
I'm trying to make an application with drawer menu and one of the option is to open an Activity with Tabs. In every fragment im trying to show listview which oparate on database. I've got problem with too much work on main thread. It is skipped 66 frames or more. I should make this operation in Async Task ? Please help find my a solution what should i do?
public class test1 extends Fragment{
private OpenHelper1 dbHelper;
private SimpleCursorAdapter dataAdapter;
public ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.trening_activity_main, container, false);
dbHelper = new OpenHelper1(this.getActivity());
dbHelper.open();
//Clean all data
dbHelper.deleteAllCountries();
//Add some data
dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
displayListView(rootView);
return rootView;
}
private void displayListView(View root) {
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[]{
OpenHelper1.KEY_NAME,
OpenHelper1.KEY_KIND
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.name,
R.id.kind,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.trening_activity1,
cursor,
columns,
to,
0);
listView = (ListView) root.findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(getActivity().getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getActivity().getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("cwiczenie ", countryCode);
startActivity(i);
}
});
EditText myFilter = (EditText) root.findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCountriesByName(constraint.toString());
}
});}
}
You can't make database operations in the Main thread (or UI thread). You have to do this in another thread using an AsyncTask. So you already have the answer yourself.
You should use a Loader, a CursorLoader to be exact. This will fetch the data from the database in a background thread. A callback method onLoadFinished will provide the cursor which you can then use to create/update your SimpleCursorAdapter.
Check out the example on the Developer site
So I have a List View that when you click on a row it opens up a new activity. In the new activity there's a checkbox. If you check the check box and then go back to the listview activity it should set a checkmark next to the list view item that was initially clicked.
Whats happening right now is when I check the checkbox and return to the listview every row has a checkmark next to it regardless of which row the checkbox was checked from.
heres my mainactivity with the listview and on click listener that starts the second checkbox activity
//fill list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int listViewItemPosition = position;
CharSequence route = routeListViewItems[position];
int imageId = (int) image.getResourceId(position, -1);
if (route.equals(routeListViewItems[position]))
{
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[position]);
intent.putExtra("imageResourceId", imageId);
intent.putExtra("routeName", routeListViewItems[position]);
intent.putExtra("listViewItemPosition", listViewItemPosition);
startActivity(intent);
}
}
}
);
}
then heres what im passing from the second activity back to the listview activity
#Override ///////for back button///////
public void onBackPressed() {
super.onBackPressed();
////////sets checkmark next to listview item//////
if (routeCheckBox.isChecked())
{
Intent check = new Intent(RouteDetails.this,MainActivity.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
check.putExtra("listViewItemPosition", listViewItemPosition);
startActivity(check);
}
}
and heres back in my listview activity where I recieve the info from my checkbox activity and set the checkmark
edited to include full adapter class
edited to include code that I found to solve my issue!
class CustomAdapter extends ArrayAdapter<CharSequence> {
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
/////////////set check mark/////////////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
int checkImageResourceId = ((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0);
int listViewItemPosition = ((Activity) getContext()).getIntent().getIntExtra("listViewItemPosition",0);
/////my solution was just setting where listviewitemposition == position in my getview method//////
if (listViewItemPosition == position)
{
checkImageView.setImageResource(checkImageResourceId);}
//////////////////////////////////////////////////
return customView;
}
thanks for any help!
The solution was I just needed use an if statement to set listviewItemPosition == position in my getView method
/////my solution was just setting where listviewitemposition == position in my getview method//////
if (listViewItemPosition == position)
{
checkImageView.setImageResource(checkImageResourceId);}
//////////////////////////////////////////////////
Im trying disable some items in listview , but cant to do it.
I have Array of booleans
private boolean[] array; //10 items all false, and some of them true
in code im trying
for(int i=0;i<array.length();i++){
if(!array[i]){
listview.getChildAt(i).setEnabled(false);
}
}
but im always got nullpointerexception on string "listview.getChildAt()"
if write like
if(listview.getChildAt(i)!=null){ //do code here }
than i see what no entrance to string "getChildAt(i).setEnabled(false)"
im little not understand about getChildAt but i was thinking its way where i can get items by position. Any one can help me how to do it?
adapter for list view
public class LevelAdapter extends ArrayAdapter<String> {
public LevelAdapter(Activity context, ArrayList<String> le, ArrayList<Integer> co, boolean[] bools) {
super(context, R.layout.listviewitem, le);
this.context = context;
this.l = le;
this.s = co;
this.boolStates = bools;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.listviewitem, null, true);
tvL = (TextView) rowView.findViewById(R.id.l);
tvC = (TextView) rowView.findViewById(R.id.s);
tvL.setText(""+l.get(position));
tvCt.setText(""+s.get(position) + "/3");
return rowView;
}
}
regards , Peter.
SOLUTION
in adapter check
if(lvl[position]==false){
rowView= inflater.inflate(R.layout.listviewitemdisabled, null, true);
rowView.setEnabled(false);
}else
{
rowView= inflater.inflate(R.layout.listviewitem, null, true);
}
and when click on
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view.isEnabled()) {
// do our code here
thanks for this easy solution
You can set enabled state in your adapter.
rowView.setEnabled(false)
Use Adapter approach.
Create an adapter and a viewHolder and in OnBind method just get that item of list and disable it.
send value to the adapter using method and notify the adapter about change.
I have written a small app that has a ListView with a custom adapter. Each row contains some Buttons, which will change background color when clicked, and I got the list items to be clickable as well by putting
android:descendantFocusability="blocksDescendants"
in the xml of the list items. But now I have this weird bug where clicking on the list item reverts all clicked Buttons back to their original colorless state. How can I get the Buttons to keep their color?
Details:
Part of the custom adapter:
View.OnClickListener onButtonClicked = new View.OnClickListener() {
#Override
public void onClick(View button) {
View listItem = (View) button.getParent();
final long DBid = (long) listItem.getTag();//database ID
final Button b = (Button) button;
sqldataDataSource datasource = new sqldataDataSource(context);
datasource.open();
datasource.updateButton(DBid);
datasource.close();
b.setBackgroundColor(0xFF386F00);
}
};
As you can see, I change the background color AND change the database entry, so when the whole list is reloaded, the Button keeps its color (another part of my custom adapter):
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.hrlistitems, parent, false);
Button b = (Button) rowView.findViewById(R.id.HRlistB);
b.setOnClickListener(onButtonClicked);
if(!(values.get(i).getB().equals(""))){
b.setBackgroundColor(0xFF386F00);
}
return rowView;
}
This works fine when going to another activity and coming back to this one. The buttons are created colored as expected.
So my guess was that the list is recreated from the original listItem array when an item is clicked, which is why I tried to fix this by reloading my database, like so (from my activity):
#Override
protected void onStart() {
super.onStart();
datasource = new sqldataDataSource(this);
datasource.open();
listItems = datasource.getOnlyRoutes(id);//this works fine
Collections.sort(listItems, HallenRoute.vergleichen());
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listViewHalle);
}
adapter=new customAdapter(this, listItems);
setListAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int pos, long nid) {
listItems.get(pos).increaseCount();
datasource.updateCountHR(listItems.get(pos));
listItems = datasource.getOnlyRoutes(id);//fix I tried, doesn't work
Collections.sort(listItems, HallenRoute.vergleichen());
adapter.notifyDataSetChanged();
}
});
}
But this doesn't work.
How can I get the ListView to either not reload on ItemClick or reload properly (i.e. from database)?
You don't have to reload the whole data for every Button click.
In your Button click you're just updating the data base and not your adapter dataset values, this is why you always get the old background color.
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.hrlistitems, parent, false);
Button b = (Button) rowView.findViewById(R.id.HRlistB);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View button) {
View listItem = (View) button.getParent();
final long DBid = (long) listItem.getTag();//database ID
final Button b = (Button) button;
sqldataDataSource datasource = new sqldataDataSource(context);
datasource.open();
datasource.updateButton(DBid);
datasource.close();
//b.setBackgroundColor(0xFF386F00); no need for this line, getView() method will take care of the background
//update your adapter dataset, eg: values.get(i).setB("newColor");
notifyDataSetChanged(); // to refresh your adapter
}
});
if(!(values.get(i).getB().equals(""))){
b.setBackgroundColor(0xFF386F00);
}
return rowView;
}
PS: It's better if you save your "database ID" in your Model object not as a View tag.
I've been searching for a while now, but I can't seem to find an answer to the following question:
Why does onCreateView never get triggered? This code is the code generated by Android Studio when creating a new MainActivity plus some of the code I wrote.
I want to use setTextConfig(...,...,...) to set the text in the text fields. But I can't seem to get them using findviewbyid(R.id....); because v is always null, even getView(); returns null.
public static class PlaceholderFragment extends Fragment {
private View v;
private EditText etCustomerName, etDeviceID;
private Spinner select;
public PlaceholderFragment() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
public void setTextConfig(String customerName, String selectedOption, int deviceID){
View vv = getView();
//init form controls
etCustomerName = (EditText)vv.findViewById(R.id.etCustomerName);
etDeviceID = (EditText)v.findViewById(R.id.etDeviceId);
select = (Spinner)v.findViewById(R.id.select);
etCustomerName.setText(customerName);
ArrayAdapter adapter = (ArrayAdapter)select.getAdapter();
int index = adapter.getPosition(selectedOption);
select.setSelection(index);
etDeviceID = (EditText)getView().findViewById(R.id.etDeviceId);
etDeviceID.setText(Integer.toString(deviceID), TextView.BufferType.EDITABLE);
}
}
If you need more detailed info, just ask :)