I am making an android application where i got a seekbar for some music. I got the seekbar to show the music playing status, where i currently am in the music playback. But how can i setup a listener so that i can say that the mediaplayer would play a specific place on a track? I know the code for setting the play time in mediaplayer, but how can i handle the click events from seekbar? like onClick() or anything similar?
FIXED:
My code:
package com.mycompany.appname;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
public class MusicActivity extends ListActivity implements OnClickListener, OnSeekBarChangeListener {
//Called when the activity is first created
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
static final String[] COUNTRIES = new String[] {
"Movies"
};
MediaPlayer mp1;
String musicUri;
Button PausePlay;
int positionInt;
SlidingDrawer slidingDrawer2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musicscreen);
//Import views
PausePlay = (Button)findViewById(R.id.PausePlay);
slidingDrawer2 = (SlidingDrawer)findViewById(R.id.slidingDrawer2);
//Setup onClickListener for the buttons
PausePlay.setOnClickListener(this);
//Setup mediaPlayer
mp1 = new MediaPlayer();
//Setup ListView
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setOnSeekBarChangeListener(this);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
File mFile = new File(Environment.getExternalStorageDirectory() + "/Music/");
myList.addAll(Arrays.asList(mFile.list()));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//When an item is clicked, play it on a MediaPlayer
//Play song
positionInt = position;
if (mp1.isPlaying()) {
//Reset mediaPlayer
mp1.reset();
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(positionInt);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(position);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setProgress(0);
progress.setMax(mp1.getDuration());
new CountDownTimer(mp1.getDuration(), 250) {
public void onTick(long millisUntilFinished) {
if (progress.getProgress() == mp1.getDuration()) {
mp1.reset();
progress.setProgress(0);
} else {
progress.setProgress(mp1.getCurrentPosition());
}
}
public void onFinish() {}
}.start();
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser == true) {
mp1.seekTo(seekBar.getProgress());
} else {
//Do nothing
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK)) {
if (mp1.isPlaying()) {
mp1.reset();
System.exit(0);
} else {
finish();
}
return true;
}
return super.onKeyDown(KeyCode, event);
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.PausePlay:
if (mp1.isPlaying()) {
mp1.pause();
PausePlay.setText("Play");
} else {
mp1.start();
PausePlay.setText("Pause");
}
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
My 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="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Musikk"
android:textAppearance="?android:attr/textAppearanceLarge" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<SlidingDrawer
android:id="#+id/slidingDrawer2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="#+id/content"
android:handle="#+id/handle" >
<Button
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spiller nĂ¥" />
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SeekBar
android:id="#+id/musicProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/PausePlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
</LinearLayout>
You'll want to implement SeekBar.OnSeekBarChangeListener, then implement the onProgressChanged method.
This is called when the progress is changed (eg a user click somewhere on the seekbar), and will provide you with the new position.
Example:
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {
// Do something
}
Don't forget to register the OnSeekBarChanged listener with seekBar.setOnseekBarChangeListener
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp1.seekTo(progress);
seekBar.setProgress(progress);
}
}
Related
I have a listview in my app, if I click one item from the list, it gets highlighted. Then if I click another item, that highlight shifts to that item. But if the scroll the list after selecting an item and then select another item from another part of the list, both of them remains highlighted. But not if I don't scroll the screen. What is causing this? And how to deal with it?
ListAdapter.java
package com.example.mp3;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter{
private Context _context;
private List<String> list;
public ListAdapter(Context _context,List<String> list)
{
this._context=_context;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
View row = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
}
TextView textView = (TextView) row.findViewById(R.id.rowTextView);
textView.setText(list.get(position).toString());
return row;
}
}
MainActivity.java
package com.example.mp3;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> adapter ;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title;
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MainActivity.class.getSimpleName();
private Context _context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
//list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
_context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
EditText editText = new EditText(getApplicationContext());
getActionBar().setCustomView(editText);
//bar.setDisplayShowTitleEnabled(true);
//bar.setDisplayHomeAsUpEnabled(true);
Scanner("/sdcard/");///storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
//listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
ListAdapter listAdapter=new ListAdapter(_context,listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
///////////////////changing list item background on click///////////////////
list.clearChoices();
//list.setSelection(position);
view.setSelected(true); ///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
String selected = listTest.get(position);
list.setItemChecked(position, true);//
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
}
else
{
index = (list.getAdapter().getCount()-1)-1;
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
play.setImageResource(R.drawable.play);
}
/*#Override
protected void onStop() {
super.onStop();
mp.stop();
Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
}*/
//////////////////////////////////////////Search box/////////////////////////////////////////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
//Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
try
{
File fl = new File("/sdcard/");
File[] listOfFiles = fl.listFiles();
String selectedPath="";
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
{
selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM
//listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();
/*mp.setDataSource(selectedPath);
mp.prepare();
mp.start();*/
}
/////////////////////////////////
File f = new File("/sdcard/"+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner("/sdcard/"+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
The cause of this problem is the way Android recycles the ListView items. A way to prevent something like this is to manually save wich item is clicked. In your adapter you can make a variable wich holds the current selected item. In your getView you will have to check if the current item is the same as selected. It will look something like this:
if(row==currentSelected){
//set background color
else{
//another background color -> this is important otherwise all listview items will have the same background color after swiping up and down
}
Hello, try with this.
1- Your activity extend from ListActivity. 2-Create the next adapater
for your list, you can create this adapter inside your activity:
private class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return items.length;
}
#Override
public String getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return items[position].hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item,
container, false);
}
((TextView) convertView.findViewById(android.R.id.text1))
.setText(getItem(position));
ImageView imageView = (ImageView) a convertView.findViewById(R.id.imageView_Icon);
imageView.setImageResource(imagesId[position]);
return convertView;
}
}
items = Array String with the text items. imagesId = Array with the
image's id in your draweable.
In the layout create the next list_item.xml
<com.Test.CheckableLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:minHeight="?android:listPreferredItemHeight"
android:gravity="center_vertical">
<ImageView
android:id="#+id/imageView_Icon"
android:layout_height="60dp"
android:contentDescription="IconDescription"
android:layout_width="60dp" />
<TextView android:id="#android:id/text1"
android:duplicateParentState="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#color/hideable_text_color" />
<ImageView android:src="#drawable/ic_hideable_item"
android:duplicateParentState="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:id="#+id/imageView1" />
</com.Test.CheckableLinearLayout>
In your Activity set adapter in the ListView:
ListView listTest = (ListView) findViewById(R.id.listTest);
listTest .setAdapter(new MyAdapter());
If you need a best example, go to Import Sample -> Select your version
y go to List, here is excelente example for the list multi select.
On Clicking the spinner item need to show the popup window but its not showing up, only i can see the toast notification.
Log: system.err
java.lang.IllegalStateException: System services not available to Activities before onCreate()
My Code Below
MainActivity.java
package com.example.newapplication;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;
import com.example.newapplication.service;
public class MainActivity extends Activity {
Button btnClosePopup;
//Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*OpenPopup = (Button) findViewById(R.id.button1);
OpenPopup.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
initiatepopupwindow();
}
});
*/
array = ser.getArrayList();
Log.d("TAG","" +array);
//for(int i=0;i<array.length();i++){
//}
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
dataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
addListenerOnSpinnerItemSelected();
}
private PopupWindow pwindo;
private void addListenerOnSpinnerItemSelected() {
// TODO Auto-generated method stub
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
#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;
}
public void initiatepopupwindow() {
// TODO Auto-generated method stub
try{
Log.d("TAG", "" +"Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
}
catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
Listener for spinner event.
CustomOnItemSelectedListener.java
package com.example.newapplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.newapplication.MainActivity;
public class CustomOnItemSelectedListener implements OnItemSelectedListener{
MainActivity main = new MainActivity();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
main.initiatepopupwindow();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
screenpopup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp" >
<TextView
android:id="#+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="Hello!" />
<Button
android:id="#+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />
</LinearLayout>
activity_main layout
<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="#drawable/lightbackground"
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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="32dp"
android:text="Welcome to MyApp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="21dp" />
</RelativeLayout>
remove your CustomOnItemSelectedListener.java class
and then use this code
public class MainActivity extends Activity {
Button btnClosePopup;
// Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*
* OpenPopup = (Button) findViewById(R.id.button1);
* OpenPopup.setOnClickListener(new OnClickListener(){
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* stub initiatepopupwindow(); }
*
* });
*/
array = ser.getArrayList();
Log.d("TAG", "" + array);
// for(int i=0;i<array.length();i++){
// }
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, array);
dataadapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
initiatepopupwindow();
Toast.makeText(getApplicationContext(), array.get(arg2) + "",
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private PopupWindow pwindo;
#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;
}
public void initiatepopupwindow() {
// TODO Auto-generated method stub
try {
Log.d("TAG", "" + "Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screenpopup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
In place of layout pass spinner object of your view:
replace
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
with
pwindo.showAtLocation(spinner, Gravity.CENTER, 0, 0);
And to open popup window just below your spinner use below code
pwindo.showAsDropDown(spinner, 0, 0);
Update your CustomOnItemSelectedListener class as:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
Context mCtx;
public CustomOnItemSelectedListener(Context ctx) {
this.mCtx = ctx;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
((MainActivity) mCtx).initiatepopupwindow();
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG)
.show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
My main problem is "When i click start button but It did not change TextView".
I am trying Service.I use Handler object for calling broadcast then it show textView.But it did not work what problem i can not understand.please help me.
MainActivity.java
package com.example.service_ahsanul;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnStart, btnStop;
TextView txtOutput;
private ServiceResponseReceiver myreceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
txtOutput = (TextView) findViewById(R.id.txtOutput);
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, MyServices.class);
startService(intent);
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, MyServices.class);
stopService(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Register broadcast port theke
if (myreceiver == null) {
myreceiver = new ServiceResponseReceiver();
IntentFilter filter = new IntentFilter("service_action");
registerReceiver(myreceiver, filter);
}
}
#Override
protected void onPause() {
super.onPause();
// unregister broadcast port theke
if (myreceiver != null) {
unregisterReceiver(myreceiver);
}
}
class ServiceResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("service_action")) {
txtOutput.append("service has finished task\n");
}
}
}
}
MyServices.java
package com.example.service_ahsanul;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class MyServices extends Service {
private Timer timer;
private TimerTask task;
private int counter = 0;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e("MyService", "onCreate");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("MyServices", "onStart");
counter = 0;
handleStart();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.e("MyServices", "onStartCommand");
handleStart();
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
return super.stopService(name);
}
private void handleStart() {
new MyThread().start();
}
class MyThread extends Thread {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Notify the activity broadcast korbe
sendBroadcast(new Intent("service_action"));
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("MyService", "onDestroy");
// timer.cancel();
// timer = null;
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Start" />
<Button
android:id="#+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Stop" />
<TextView
android:id="#+id/txtOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I agree with vijay.
I don't see anywhere you may have registered for the receipt of a message, nor am i sure what messages you're intending on receiving.
I'd also resist short names for your intent. Using fully qualified names for an intent is preferred. so instead of "service_action" I'd use "com.example.service_ahsanul.service_action"
Inside your service, the handler's handleMessage method is not called from anywhere so it's code is not executed and textview content is not updated...
you can use handler.postMessage("msg"); statement inside MyThread run method to call the handleMessage function.
I have a list menu that links to another list menu and into an activity called counter. But the counter keeps throwing an exception and not show me the actual counter activity
here's the code below
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the tool class
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the counter class
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Counter extends Activity {
int counter;
Button add;
Button sub;
TextView display;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
}
}
and the counter.xml if that helps anyone
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Counter: 0"
android:textSize="45dp"
android:layout_gravity="center"
android:id="#+id/tvDisplay"
></TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="Subtract" />
</RelativeLayout>
I can't see what can be wrong any ideas?
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese); in this line append "." before cheese
i have a surface view and i wish "draw" the content of a linear layout on my surface view.
My surface view is the preview of the camera, i wish when i take the picture the content of my layout is drawn on the picture.
How do this?
Thx.
Surface layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="bottom"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/takepicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/trans_tshirt"
android:contentDescription="tshirt" />
main.xml
<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<SurfaceView android:layout_height="match_parent" android:layout_width="match_parent" android:id="#+id/camerapreview"/>
</LinearLayout>
java code:
package com.views;
import android.app.Activity;
import android.content.ContentValues;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.fashion.alex.R;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
public class HomeActivity extends Activity implements SurfaceHolder.Callback
{
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private boolean previewing = false;
private LayoutInflater controlInflater = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.tshirt_layout, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
final ImageView ivButton = (ImageView)findViewById(R.id.takepicture);
ivButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}}
);
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
}
};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}
};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(HomeActivity.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
camera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
create a Layout/.xml file..like below
1) LinearLayout A
2) Linear Layout A must have child views which may be BUtton/text whatever you want.
3) Linear Layout A must also have a surfaceview B
use this surfaceView B in your activity to show camera preview. in this way you can basically have surface view and other views on the screen.