I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....
Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.
Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?
Here's the full code:
package com.me.player
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;
public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{
private int METHOD_TYPE = 0;
private static final int GET_AUDIO = 1;
int CURRENT_POSITION = 0;
int DURATION = 0;
public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
public static final int MAX_TRACKS = 200;
ArrayList<Track> tracks = new ArrayList<Track>();
Artist artist;
private MediaPlayer mp;
private int mSongPlaying = 0;
TextView _player;
#Override
protected void progressRunnableComplete() {
if(isFinishing()){
return;
}
if(METHOD_TYPE == GET_AUDIO){
setList();
}
}
public void setList(){
ListView listview = (ListView)findViewById(R.id.ListView01);
// ListView listview = (ListView)findViewById(R.id.ListView01);
if(listview == null){
setContent(R.layout.artistaudio);
listview = (ListView)findViewById(R.id.ListView01);
}
// listview.addHeaderView();
listview.setCacheColorHint(0);
listview.setAdapter(new TrackListAdapter());
listview.setSelector(R.drawable.listbackground);
listview.setDividerHeight(1);
listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TrackClicked(arg2);
}
});
}
public void TrackClicked(int arg2){
mSongPlaying = arg2;
Track track = tracks.get(arg2);
String url = track.requestInfo("previewURL");
mHandler.post(new PlaySong(url));
// mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
}
public void setDuration(int n) {
DURATION = n;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Audio Clips");
setContent(R.layout.artistaudio);
Object o = getIntent().getParcelableExtra("artist");
if(o!=null){
artist = (Artist)o;
}
progressRunnable(new Runnable(){
public void run(){
getTracks();
}
}, "Loading. Please Wait...",false);
}
protected void getTracks() {
METHOD_TYPE = GET_AUDIO;
if(!DataBaseHelper.isOnline(this)){
RUNNABLE_STATE = RUNNABLE_FAILED;
return;
}
HttpRequest req;
try {
req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
Document doc = req.AutoXMLNoWrite();
NodeList items = doc.getElementsByTagName("e");
tracks= new ArrayList<Track>();
for(int i=0; i<items.getLength(); i++){
Track newsitem = new Track(items.item(i));
tracks.add(newsitem);
}
RUNNABLE_STATE = RUNNABLE_SUCCESS;
} catch (Throwable e) {
RUNNABLE_STATE = RUNNABLE_FAILED;
e.printStackTrace();
}
}
public void onPause(){
super.onPause();
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.release();}catch(Exception e){e.printStackTrace();}
mp = null;
}
private class TrackListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return tracks.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return tracks.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AudioCell blogView = null;
if (convertView != null) {
if(convertView.getClass() == TextView.class){
convertView = null;
}
}
if (convertView == null) {
blogView = new AudioCell(parent.getContext());
}
else {
blogView = (AudioCell) convertView;
}
blogView.display(position);
return blogView;
}
}
/** this class is responsible for rendering the data in the model, given the selection state */
class AudioCell extends RelativeLayout {
TextView _title;
int currentPosition;
public AudioCell(Context mContext) {
super(mContext);
_createUI(mContext);
}
/** create the ui components */
private void _createUI(Context m) {
RelativeLayout.LayoutParams params;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
_player = new TextView(m);
_player.setId(2);
_player.setBackgroundResource(R.drawable.playbtn);
_player.setText(":30");
addView(_player);
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
_player.setLayoutParams(params);
_title = new TextView(m);
_title.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
params.addRule(RelativeLayout.RIGHT_OF, _player.getId());
params.setMargins(0, 10, 0, 10);
_title.setGravity(Gravity.CENTER_VERTICAL);
_title.setLayoutParams(params);
_title.setId(102);
addView(_title);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
// _player.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//
// }
// });
//
}
/** update the views with the data corresponding to selection index */
public void display(int index) {
_title.setText(tracks.get(index).requestInfo("name"));
}
}
private class PlaySong implements Runnable{
String songURL;
public PlaySong(String url){
songURL = url;
}
public void run(){
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
if(mp==null){
createPlayer();
}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}
}
}
public void createPlayer(){
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try{mp.reset();}catch(Exception e){e.printStackTrace();}
// if(mSongPlaying<tracks.size()-1)
// {
// TrackClicked(mSongPlaying+1);
// }
_player.setBackgroundResource(R.drawable.playbtn);
}
#Override
public void onPrepared(MediaPlayer inMP) {
// TODO Auto-generated method stub
mp.start();
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....
Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).
change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);
Inside your TrackClicked method, add this:
getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);
Related
I have a problem when using MediaPlayer to play video from url.
The follow of program : create an activity to play video -> press Home button -> back to app.
The requirement is video play from start, when press Home button video continuos play(only audio), and when back to app, video must play continuous(combine movie and audio).
The first, I created a MediaPlayer variable to play video. When Home button is pressed, MediaPlayer play continuous. But when back to app, video cannot displayed(black screen). So, I created other MediaPlayer variable to solved this issue. But when I using seekTo() function to seek second MediaPlayer to position of first MediaPlayer, this function is working incorrect.
import java.io.IOException;
import com.example.videotest.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback, FGMediaController.MediaPlayerControl {
SurfaceView videoSurface,videoSurfaceFullscreen,videoSurfaceSmallsceen;
MediaPlayer player, backupPlayer;
FGMediaController controller;
LinearLayout llControllerBar;
public boolean isFullscreen = false;
int videoDuration;
int videoCurrent;
SurfaceHolder viewHolder = null;
boolean isPaused = false;
String videoUrl = "http://cdn-smatopi.tv-bank.com/movie/867/867-32/867-32-2015042306-D3/hls/hls3/867-32-2015042306-D3-HLS3.m3u8";
Button btnSeek, btnRelease;
int currentPos = 30000;
boolean videoPrepared = false;
boolean backupPrepared = false;
boolean mVideoSizeIsSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playvideo);
btnSeek = (Button) findViewById(R.id.btnSeek);
btnRelease = (Button) findViewById(R.id.btnRelease);
videoSurface = (SurfaceView)findViewById(getResources().getIdentifier("vvVideo", "id", getPackageName()));
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
backupPlayer = new MediaPlayer();
controller = new FGMediaController(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(videoUrl));
player.prepareAsync();
//backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//backupPlayer.setDataSource(this, Uri.parse(videoUrl));
//backupPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
btnSeek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Huhu",currentPos + "");
backupPlayer.seekTo(currentPos);
}
});
btnRelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
backupPlayer.stop();
backupPlayer.release();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(PlayVideoActivity.this);
controller.setAnchorView((FrameLayout) findViewById(PlayVideoActivity.this.getResources().getIdentifier("videoSurfaceContainer", "id", PlayVideoActivity.this.getPackageName())));
player.start();
}
});
}
#Override
public void onDestroy(){
//backupPlayer.release();
player.release();
super.onDestroy();
}
#Override
public void onResume(){
Log.e("Surface Created","OnResume");
super.onResume();
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("Surface Created","Surface Created! " + holder);
if(viewHolder != null){
viewHolder = holder;
backupPlayer = new MediaPlayer();
try {
backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
backupPlayer.setDataSource(this, Uri.parse(videoUrl));
backupPlayer.prepareAsync();
backupPlayer.setDisplay(holder);
backupPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
backupPrepared = true;
backupPlayer.start();
}
});
backupPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
if (width == 0 || height == 0){
Toast.makeText(getApplicationContext(),"Width = 0 Height = 0"+ mp.getDuration(), Toast.LENGTH_LONG).show();
}else{
if(backupPrepared){
backupPrepared = false;
currentPos = player.getCurrentPosition();
player.reset();
Toast.makeText(getApplicationContext(),"Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos, Toast.LENGTH_LONG).show();
Log.e("Huhu","Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos);
backupPlayer.seekTo(currentPos); // If you set currentPos = 20000ms or 30000ms backupPlayer can to seek, but if you set currentPos = 10000ms backupPlayer cannot seek !
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
player.setDisplay(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("Surface Created","surfaceDestroyed! " + player.getCurrentPosition());
viewHolder = holder;
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.printLog(Log.ERROR, "CURRENT :"+player.getCurrentPosition());
int current = 0;
try{
current = player.getCurrentPosition();
}catch(Exception e){
e.printStackTrace();
}
return current;
}
#Override
public int getDuration() {
int duration = 0;
try{
duration = player.getDuration();
}catch(Exception e){
e.printStackTrace();
}
return duration;
}
#Override
public boolean isPlaying() {
boolean isPlaying = false;
try{
isPlaying = player.isPlaying();
}catch(Exception e){
e.printStackTrace();
}
return isPlaying;
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return isFullscreen;
}
#Override
public void toggleFullScreen() {
// TODO Auto-generated method stub
}
#Override
public void doBackPressed() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
}
}
I get data from database (id, name) and I display (name) in a ListView. When user clicks I need to get database (id) to perform an action
KoiskesdataActivity.java
package koisk.data;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.StrictMode;
import android.widget.AdapterView.OnItemClickListener;
public class KoiskesdataActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog pd;
private ListView koisksListView;
private EditText myfilter;
// private ArrayAdapter <String> koiskarrayAdapter;
String koiskArray[];
Button autocompletekoisksname;
int textlength=0;
private ArrayList<String> array_sort= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
///
koisksListView=(ListView) findViewById(R.id.koiskslist);
myfilter=(EditText) findViewById(R.id.myFilter);
///////
pd = new ProgressDialog(this);
pd.setMessage("loading...");
pd.show();
/////
getarrayofnamekoisk namekoisk=new getarrayofnamekoisk();
koiskArray=namekoisk.WW();
ArrayAdapter <String> koiskarrayAdapter=new ArrayAdapter <String>(KoiskesdataActivity.this, android.R.layout.simple_list_item_1,koiskArray);
koisksListView.setAdapter(koiskarrayAdapter);
pd.dismiss();
koisksListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
myfilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
textlength = myfilter.getText().length();
array_sort.clear();
for (int i = 0; i < koiskArray.length; i++)
{
if (textlength <= koiskArray[i].length())
{
//subSequence returns the specified word between the begien and end
//equalsIgnoreCase compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case
if (myfilter.getText().toString().equalsIgnoreCase((String)koiskArray[i].subSequence(0, textlength)))
{
array_sort.add(koiskArray[i]);
}
}
}
//KoiskesdataActivity.this.koiskarrayAdapter.getFilter().filter(s);
koisksListView.setAdapter(new ArrayAdapter<String>(KoiskesdataActivity.this,android.R.layout.simple_list_item_1,array_sort));
}
});
}
}
getarrayofnamekoisk.java
package koisk.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Templates;
import android.R.array;
import android.R.integer;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class getarrayofnamekoisk{
private int i;
private String[] koiskname ;
private int num_rows;
private ArrayAdapter arrayAdapterdata;
List<String[]> names = new ArrayList<String[]>();
ArrayList<String> arr = new ArrayList<String>();
public String[] WW() {
// TODO Auto-generated method stub
connecttodatabase qq=new connecttodatabase();
qq.dbconnect();
if (qq.con !=null)
{
try
{
Statement st = qq.con.createStatement();
ResultSet rs = st.executeQuery("SELECT Name,id FROM Device where DeviceTypeId=4 and IsDeleted =0 and name is not null ");
while(rs.next())
{
arr.add(rs.getString("name"));
}
koiskname= new String [arr.size()];
arr.toArray(koiskname);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Toast.makeText(ConnectbyprocedureActivity.this, e.toString() , Toast.LENGTH_SHORT).show();
}
qq.closeConnection();
}
return koiskname;
}
}
connecttodatabase.java //to connect to sql server
package koisk.data;
import java.sql.DriverManager;
public class connecttodatabase {
public java.sql.Connection con = null;
private final String userName="sa";
private final String pass="123";
/////////
private final String url = "jdbc:jtds:sqlserver://";
private final String serverName= "192.168.1.200";
private final String portNumber = "1433";
private final String databaseName= "loadshedding";
////////////
/**
* #param args
*/
private String getConnectionUrl(){
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
//return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
return url+serverName+":"+portNumber+"/"+databaseName;
}
public java.sql.Connection dbconnect() {
// TODO Auto-generated method stub
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
con = DriverManager.getConnection(getConnectionUrl(), userName, pass);
// if(con!=null) System.out.println("Connection Successful!");
}
catch(Exception e) {
e.printStackTrace();
// tv.setText(e.toString());
}
return con ;
}
// public void displayDb(){
// java.sql.DatabaseMetaData dm = null;
// java.sql.ResultSet rs = null;
// try{
// con=this.dbConnect();
// }
// catch(Exception e){
// e.printStackTrace();
// }
// }
public void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
}
please i need help ..... thanks guys
You get the id from the database, but you never store it anywhere.. you first need to store it in an Array or ArrayList (lets say, idList). You have to do it similar to how you store the names in a list. then:
You can get the position of the item which is clicked inside the onItemClick method as
follows:
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
int position = arg2;
clickedID = idList.get(position);
// do something with the clicked id.
}
When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.
I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.
on the press of my "next" button I have a speech bubble run through a string array. After all the items finish displaying and the user clicks the "next" button once more I would like to deflate the current child view and inflate a new view. Right now it crashes after the string array finishes displaying on multiple clickings of the "next" button.
How can I get this to work?
package com.jibushi;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class LessonsShell extends Activity{
private static final int MESSAGE_SHOW_POPUP = 1;
private static final int MESSAGE_SHOW_POPUP2 = 1;
private static final long TIME_DELAY = 1000;//1 seconds
private static final long TIME_DELAY2 = 500;
private View view;
private View view2;
private int count = 0;
private TextView lessonsDialog;
private String[] myIntroString;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP:
view();
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lessons);
//this will send a message to the handler to display the popup after 1 seconds.
handler.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP,TIME_DELAY);
}
private void view() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_dialog, null);
parent.addView(view);
lessonsDialog = (TextView) findViewById(R.id.lessonsDialog);
Resources res = getResources();
myIntroString = res.getStringArray(R.array.lessons_dialog_array);
Button nextButton = (Button) findViewById(R.id.next_button);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (count < myIntroString.length) {
lessonsDialog.setText(myIntroString[count]);
count++;
} else {
if (myIntroString[-1] != null) {
handler2.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP2, TIME_DELAY2);
}
}
}
});
}
private Handler handler2 = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP2:
view2();
break;
}
}
private void view2() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view2 = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_start, null);
parent.addView(view2);
parent.removeView(view);
};
};
}
Ah, yes, I see it now. You can't do this:
myString[-1]
The index -1 does not exist in arrays. What are you trying to do? Perhaps myString[count - 1]?