ListView without extending ListActivity - java

I have an application that extends ActionBarActivity, but I'm using ListView and I need to implement OnItemClickListener and I'm not sure how to do this without extending ListActivity. Also I want to ask you: Moreover I have a button and I need to listen if the button is clicked or if an item in the list is clicked. I'm not pretty sure how to do this.
So I would really appreciate if you help me :)
Here is my code:
package com.src.vicnote;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
Button newButton;
String path = Environment.getExternalStorageDirectory().toString()+"/VICNote";
String lastOfPath;
File f = new File(path);
File files[] = f.listFiles();
String[] theNamesOfFiles = new String[files.length + 1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theNamesOfFiles[0] = "Create new note";
for(int i = 1; i < theNamesOfFiles.length; i++) {
lastOfPath = files[i-1].toString().split("/")[files[i-1].toString().split("/").length-1];
theNamesOfFiles[i] = lastOfPath.replace(".txt","");
Log.d("Files", "String: " + theNamesOfFiles[i]);
}
ListView lv = (ListView) findViewById(R.id.notesList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
theNamesOfFiles);
lv.setAdapter(adapter);
newButton = (Button) findViewById(R.id.buttonNew);
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newNote = new Intent(MainActivity.this, NewNoteActivity.class);
startActivity(newNote);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

You can implement the OnItemClickListener interface and override onItemClick
lv.setAdapter(adapter);
lv.setOnItemClickListener( new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this.this, "List View row Clicked at"+position,Toast.LENGTH_SHORT).show();
}
});
If the button belongs to activity_main.xml then what you have
newButton.setOnClickListener(new View.OnClickListener()
is right

You can set item click listener for ListView using this code.
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
// it is used to get the clicked string
String theNamesOfFile = adapter.getItem(position);
}
});
I guess it can help you.

Related

MP3 songs do not play in media player

I am trying out below code
here is the MainActivity.java
import java.io.File;
import java.util.ArrayList;
import javax.crypto.spec.PSource;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterViewFlipper;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvPlaylist);
final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
items = new String[mySongs.size () ];
for (int i = 0; i < mySongs.size(); i++) {
//toast(mySongs.get(i).getName().toString());
items[i] = mySongs.get(i).getName().toString();
}
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,R.id.textView1,items);
lv.setAdapter(adp);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(), player.class).putExtra("pos", position).putExtra("songlist",mySongs));
}
});
}
public ArrayList<File> findSongs(File root){
ArrayList al = new ArrayList<File>();
File[] files = root.listFiles();
for(File singleFile : files){
if (singleFile.isDirectory()&& !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
}
else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
al.add(singleFile);
}
}
}
return al;
}
public void toast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
above code gives me a list of mp3 files when we click on one of the songs it takes to player.ja and songs are played
and
player.java
import java.io.File;
import java.util.ArrayList;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class player extends ActionBarActivity implements View.OnClickListener{
static MediaPlayer mp;
ArrayList<File> mySongs;
int position;
Uri u;
SeekBar sb;
Button btPv, btFB,btplay,btFF, btNxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btFB = (Button) findViewById(R.id.btFB);
btPv = (Button) findViewById(R.id.btPv);
btplay = (Button) findViewById(R.id.btplay);
btFF = (Button) findViewById(R.id.btFF);
btNxt = (Button) findViewById(R.id.btNxt);
btFB.setOnClickListener(this) ;
btPv.setOnClickListener(this);
btplay.setOnClickListener(this);
btFF.setOnClickListener(this);
btNxt.setOnClickListener(this);
//
if(mp != null)
{
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u).start();
mp.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v)
{
int id = v.getId();
switch (id) {
case R.id.btplay:
if(mp.isPlaying())
{btplay.setText("play");
mp.pause();
}
else
{ btplay.setText("play");
mp.start();
}
break;
case R.id.btFF:
mp.seekTo(mp.getCurrentPosition()+ 5000);
break;
case R.id.btFB:
mp.seekTo(mp.getCurrentPosition()- 5000);
break;
case R.id.btNxt:
mp.stop();
mp.release();
position = (position+1)%mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
break;
case R.id.btPv :
mp.stop();
mp.release();
// Important
position = (position-1<0) ? mySongs.size()-1: position-1;
/*if(position-1 < 0)
{
position = mySongs.size()-1;
}
else
{
position= position-1;
}*/
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
default:
break;
}
}
}
While the above code works perfectly fine for few songs which are mp3 but it does not work for other songs which are also mp3 . I have tried this on an actual device the app would just crash if the song has some problem
the mp3 files which give me problems work perfectly on other media players and even the default android media player
What exactly could be the issue?
you need to call mediaPlayer.prepare() or mediaPlayer.prepareAsync() before you call , mediaPlayer.start(), also if the application crash, post your log so we can know the problem.

Android: ListView and ArrayAdapter

so i want to make an app which loads a list with news.
now i did this to create a ListView and an ArrayAdapter:
package com.example.MPAK.newsapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.MPAK.newsapp.R;
import java.util.ArrayList;
public class NewsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
ListView lv = (ListView) findViewById(R.id.listView);
String[] values = new String[]{"News1", "NewsTitle2", "NewsTitle3", "NewsTitl4", "NewsTtitle5"};
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
list.add(values[i]);
}
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.news, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
the problem is it only shows me the 1st item from my values Array. I dont know why? What did i do wrong?
In the end i want the app to read xml files, read the title, display it on the List. By clicking on the list item it should open a new activity and display the description of the News.
Anyone has some good tutorial for that?
Thanks in advance
for (int i = 0; i < values.length; i++) {
list.add(values[i]);
}
for more informations about xml parsing there is a good tutorial presented by Darek Banas:
http://www.youtube.com/watch?v=92p6noZjRbk&index=9&list=PLGLfVvz_LVvQUjiCc8lUT9aO0GsWA4uNe
http://www.youtube.com/watch?v=Kt5wIEF7Lls&list=PLGLfVvz_LVvQUjiCc8lUT9aO0GsWA4uNe&index=10
http://www.youtube.com/watch?v=facoiyC7pC8&list=PLGLfVvz_LVvQUjiCc8lUT9aO0GsWA4uNe&index=11
http://www.youtube.com/watch?v=SlAHPyNvJ44&index=12&list=PLGLfVvz_LVvQUjiCc8lUT9aO0GsWA4uNe
and there is another good tutorial that is:
http://www.youtube.com/watch?v=40mYDQkK44A

How to add Edittext and Spinner when I clicked on Add button in java code?

package com.nyurals.school;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActitivity extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_settings );
ActionBar actionBar = getActionBar();
actionBar.show();
actionBar.setTitle("SETTINGS");
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView textView = (TextView)findViewById(titleId);
// textView.setText("ANNOUNCEMENTS");
textView.setTextColor(android.graphics.Color.BLUE);
actionBar.setDisplayHomeAsUpEnabled(true);
init();
super.onCreate(savedInstanceState);
}
private void init() {
//textParentName = (TextView) findViewById(R.)
String[] items = { "Nursery", "KG-I", "KG-II", "I", "II",
"III", "IV", "V" };
Spinner spinnerForClass = (Spinner) findViewById(R.id.spinnerClass);
// spinnerForClass.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerClass = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,items);
spinnerForClass.setAdapter(spinnerClass);
}
public void addChildren(View view) {
Toast.makeText(SettingsActitivity.this, "Clicked on Add", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_settings, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item_save:
Toast.makeText(SettingsActitivity.this, "Details saved.. Thank You!!", Toast.LENGTH_SHORT).show();
return true;
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return false;
}
}
}
In above code in add Children method, What should I write to add child again???? i.e. How to add Edit Text and Spinner like it is already present there which came from XML..
please suggest any solution...
if you have Spinner and EditText in xml already and want to add again by probgrammatically then first remove all views from your parent layout..
like:
parentlayout.removeAllViews();
and after that create object for Spinner and EditText and add to parent layout
EditText edt= new EditText(this);
Spinner sp= new Spinner(this);
parentlayout.addView(edt);
parentlayout.addView(sp);
Try this:
EditText myEdtTxt = new EditText(this);
myLayout.addView(myEdtTxt);
Spinner spinner = new Spinner(this);
myLayout.addView(spinner);

Unable to display option selected through a spinner

I want the option selected in the spinner menu to be displayed in a textview whose id is 'spinnertxt'.
I'm able to open the spinner menu and select the option, but after that nothing happens.
Here is the code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Addproject extends Activity implements OnItemSelectedListener {
protected int mPos;
protected String mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addproject);
Spinner spinner = (Spinner) findViewById(R.id.difficultyspinner); ArrayAdapter<CharSequence>
adapter = ArrayAdapter.createFromResource(this,R.array.difficultyarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_addproject, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
Addproject.this.mPos = pos;
Addproject.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView spinnerresult = (TextView)findViewById(R.id.spinnertxt);
spinnerresult.setText(Addproject.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
//NOTHING TO LOOK HERE, MOVE ALONG
}
}
Can someone tell me why? I'm new to this.
Instantiate your array and use
Addproject.this.mSelection = array[pos];
instead of
Addproject.this.mSelection = parent.getItemAtPosition(pos).toString();
Solved!
A listener was missing.
I just added
spinner.setOnItemSelectedListener(this);
to onCreate() after setAdapater()
The listener is needed so that the application listens for taps on particular items.

how to make a clickable listview

Ok. I'm working on a project, I have already created the listview, but I want to click on it and go to another page e.g like when you click a button it goes to another page, exactly like that, this is my code so far:
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class listV extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter( new ArrayAdapter<String>(this, R.layout.listview,Food));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show();
}
});
}
static final String[] Food = new String[]{
"Physical Activity" , "Healthy Diet", "Childhood Obesity"
};
}
Any help would be appreciated.
I'm just a beginner so please try to explain in detail.
Looks like you're 95% of the way there. In your onItemClick method of the listener, you just have to start the new activity like you normally would. You can use the 3rd argument of the onItemClick to give you the position of the listview item that was click and use that to differentiate the activity you call OR pass it into a single activity:
#Override
public void onItemClick(AdapterView<?> arg0, View position, int arg2, long arg3) {
Intent i;
if( position == 1 ){
i = new Intent(listV.this, MyFirstActivity.class);
} else if (position == 2){
i = new Intent(listV.this, MySecondActivity.class);
} else if (position == 3) {
i = new Intent(listV.this, MyThirdActivity.class);
} else {
return;
}
startActivity(i);
}
I am a fairly new programmer myself and I am attempting to create the same thing. A ListView where the user is able to click each individual item in the list and each item will start its own activity. Please check out my code based on the help you gave earlier.
package com.tylerbmc.test;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.abdominals)));
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i;
if (position == 1) {
i = new Intent(Main.this, Second.class);
startActivity(i);
}
else if (position == 2) {
i = new Intent(Main.this, Third.class);
startActivity(i);
}
}
});
}
}

Categories

Resources