Problems with some Automation Testing using Before / After / Test - selenium

Problems with some Automation Testing using Before / After / Test
I'm getting stuck at the browser window, no test is executed...
Not sure why this doesn't work. I've exported some tests from Selenium IDE, exported as Java, edited that stuff in Eclipse, yet still it doesn't work...
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Checkimage {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testCheckimage() throws Exception {
driver.get("http://");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("sign in / up"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("login-email")).clear();
driver.findElement(By.id("login-email")).sendKeys("michael.sinitsin#avid.com");
driver.findElement(By.id("login-password")).clear();
driver.findElement(By.id("login-password")).sendKeys("mike1780");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("sign in".equals(driver.findElement(By.id("login-buttons-password")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("login-buttons-password")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Tester".equals(driver.findElement(By.linkText("Tester")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.linkText("Tester")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.id("inputScoreUrl"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("inputScoreUrl")).sendKeys("http://www.sheetmusicdirect.com/scorches/smd_000001.sco");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Enter a URL to a publicly accessible SCO file. No need to URL encode it, just copy and paste it in.".equals(driver.findElement(By.cssSelector("p.help-block")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("submitScoreView")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("img"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
try {
assertTrue(isElementPresent(By.cssSelector("img")));
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
Not sure why this doesn't work. I've exported some tests from Selenium IDE, exported as Java, edited that stuff in Eclipse, yet still it doesn't work...

Dear Michael Sinitsin,
As I see it you have here several issues:
You do not supply a valid URL to the web driver
replace driver.get("http://"); with a valid URL like driver.get("http://www.google.com");
You are exposing your user/password on a public site

Michael Sinitsin,
you should first mention proper URl driver.get("http://"); And your script is too complex,you could write it in a simplest way.

Related

How can take screenshot of new tab once its loaded completly in selenium

#Test
public void testHeaderlinks() throws IOException {
homePage=new HomePage();
homePage.ClickmenuHolidays();
homePage.Clickmenuattraction();
homePage.Clickmenuhotdeal();
String originalHandle = driver.getWindowHandle();
for(String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(originalHandle);
}
public static void Takescreenshot(String filename) throws IOException {
File file= ((TakesScreenshot))driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,new File("C:\\Users\\User\\Desktop\\POMMabuhayFinal\\src\\main\\java\\Screnshots\\"+filename+".jpg"));
}
In my code i am click hyperlinks in new tab and close those tabs (closing all tabs after all hyperlinks clicks)
My question is how can i take screenshot of opened tabs( i wanna take all new tabs which are open)
Use WebDriverWait to wait for tab/page load and then call your Takescreenshot method while you iterate tabs
#Test
public void testHeaderlinks() throws IOException {
homePage=new HomePage();
homePage.ClickmenuHolidays();
homePage.Clickmenuattraction();
homePage.Clickmenuhotdeal();
String originalHandle = driver.getWindowHandle();
int count = 1;
for(String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
// Initialize WebDriverWait with 15 secs wait timeout or expected wait timeout
WebDriverWait wait = new WebDriverWait(myDriver, 15);
// Wait for page to load
wait.until(webDriver -> ((JavascriptExecutor) myDriver).executeScript("return document.readyState").toString().equals("complete"));
driver.switchTo().window(handle);
// Take screenshot of your current tab
Takescreenshot("tabImage" + String.valueOf(count)) // You can use your own imageName
driver.close();
count++;
}
}
driver.switchTo().window(originalHandle);
}
public static void Takescreenshot(String filename) throws IOException {
File file= ((TakesScreenshot))driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,new File("C:\\Users\\User\\Desktop\\POMMabuhayFinal\\src\\main\\java\\Screnshots\\"+filename+".jpg"));
}
Please Try this
public void TakeScreenShot()
{
try
{
string text = AppDomain.CurrentDomain.BaseDirectory + "\\screenshots\\";
if (!Directory.Exists(text))
{
Directory.CreateDirectory(text);
}
if (Directory.Exists(text))
{
string text2 = text + XYZ+ ".jpeg";
if (File.Exists(text2))
{
File.Delete(text2);
}
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(text2, ScreenshotImageFormat.Jpeg);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

XPath for auto-suggestion list is not working

On https://www.zillow.com I am trying to verify search using auto suggestion box.
I have written below code:
public static void verifySearch() {
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.sendKeys("sea");
// Thread.sleep(10);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[#role='listbox']/li")));
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
Here for auto suggestion list I am using following xpath but it doesn't work at run time:"//ul[#role='listbox']//li"
Can anybody guide where I am wrong.
Note:on this website autosuggestion is starts to be displayed after 3chars in search field.
Here my friend. Please try to execute the below code. You can now try to fix your issue with this simple solution.
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.click();
for( char character : "sea".toCharArray() )
{
searchbar.sendKeys(String.valueOf(character));
Thread.sleep(2000);
}
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}

Can not add SeekBar to MediaPlayer.

I have tried Runnable as well but of no use. Here is my code, What can be done here?
I have used Parecelable method to get my currently selected song from main activity to this playscreen activity.Now I want to attach seekbar to that 'currsong' I received when my mediaplayer mPlayer starts
package com.musicplayer;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
public class PlayScreen extends ActionBarActivity {
private Song currsong;
public MainActivity mainActivity;
private MediaPlayer mPlayer;
public TextView songTitle , songArtist;
public ImageView playPause, next, prev;
public SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
currsong = (Song)getIntent().getParcelableExtra("currSong");
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.playScreen);
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
songTitle=(TextView)findViewById(R.id.stitle);
songArtist=(TextView)findViewById(R.id.artist);
playPause= (ImageView)findViewById(R.id.playPause);
next= (ImageView)findViewById(R.id.next);
prev= (ImageView)findViewById(R.id.prev);
seekbar=(SeekBar)findViewById(R.id.progress);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer.isPlaying()){
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
mainActivity.songPos++;
currsong=mainActivity.songList.get(mainActivity.songPos);
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
seekbar.setMax(mPlayer.getDuration());
playSong();
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer.isPlaying()){
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
mainActivity.songPos--;
currsong=mainActivity.songList.get(mainActivity.songPos);
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
seekbar.setMax(mPlayer.getDuration());
playSong();
}
});
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer.isPlaying() ){
mPlayer.pause();
playPause.setImageResource(R.drawable.play);
}
else {
mPlayer.start();
playPause.setImageResource(R.drawable.pause);
}
}
});
playSong();
}
public void playSong(){
mPlayer= new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
songTitle.setText(currsong.getTitle());
songArtist.setText(currsong.getArtist());
//set uri
Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currsong.getID());
//set the data source
try{
mPlayer.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
//seekbar.setMax(mPlayer.getDuration());
mPlayer.start();
playPause.setImageResource(R.drawable.pause);
}
public void initMusicPlayer(){
//set player properties
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) this);
mPlayer.setOnCompletionListener((MediaPlayer.OnCompletionListener) this);
mPlayer.setOnErrorListener((MediaPlayer.OnErrorListener) this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_play_screen, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
After Searching a lot i have figured out a way to do this and since no one ha answered this question so to help others with same problem I am providing my solved java file code below-
package com.musicplayer;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.StaticLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.view.View.OnClickListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
public class PlayScreen extends ActionBarActivity implements Runnable,
OnClickListener, OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
protected static Song currsong ;
protected TextView songTitle , songArtist;
protected ImageView playPause, next, prev, loop ,shuffle;
protected SeekBar seekbar;
protected RelativeLayout relativeLayout;
protected Uri trackpath;
protected static boolean looping=false, shuffling=false;
protected ArrayList<Song> shuffleSong;
protected MediaPlayerSingleton mPlayer = MediaPlayerSingleton.getInstance();
protected ArrayList<Song> songList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
currsong = (Song)getIntent().getParcelableExtra("currSong");
songList =new ArrayList<Song>();
Bundle b = this.getIntent().getExtras();
songList = b.getParcelableArrayList("categories");
relativeLayout = (RelativeLayout) findViewById(R.id.playScreen);
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
songTitle=(TextView)findViewById(R.id.stitle);
songArtist=(TextView)findViewById(R.id.artist);
playPause= (ImageView)findViewById(R.id.playPause);
next= (ImageView)findViewById(R.id.next);
prev= (ImageView)findViewById(R.id.prev);
loop = (ImageView)findViewById(R.id.loop);
shuffle = (ImageView)findViewById(R.id.shuffle);
seekbar=(SeekBar)findViewById(R.id.progress);
next.setOnClickListener(this);
prev.setOnClickListener(this);
playPause.setOnClickListener(this);
loop.setOnClickListener(this);
shuffle.setOnClickListener(this);
seekbar.setOnSeekBarChangeListener(this);
seekbar.setEnabled(true);
loop.setImageResource(R.drawable.loop);
shuffle.setImageResource(R.drawable.shuffle);
shuffleSong = new ArrayList<Song>();
playSong();
}
public void getSongList() {
shuffleSong.addAll(songList);
Collections.shuffle(shuffleSong);
}
public void playSong(){
mPlayer.reset();
int minute = 60*1000;
Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getPath(), Toast.LENGTH_LONG).show();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
TextView totaltime =(TextView)findViewById(R.id.timeleft);
//set uri
Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currsong.getID());
trackpath=trackUri;
//set the data source
try{
mPlayer.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getTitle(), Toast.LENGTH_LONG).show();
next.performClick();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getTitle(), Toast.LENGTH_LONG).show();
next.performClick();
}
songTitle.setText(currsong.getTitle());
songArtist.setText(currsong.getArtist());
seekbar.setMax(mPlayer.getDuration());
seekbar.setEnabled(true);
new Thread(this).start();
if(mPlayer.getDuration()<minute) {
totaltime.setText(String.format("0:%1$tS", new Date(mPlayer.getDuration()-60*1000*30)));
}else{
totaltime.setText(String.format("%1$tM:%1$tS", new Date(mPlayer.getDuration()-60*1000*30)));
}
mPlayer.start();
playPause.setImageResource(R.drawable.pause);
mPlayer.setOnCompletionListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_play_screen, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v.equals(playPause)){
if(mPlayer == null){
try{
mPlayer.setDataSource(getApplicationContext(), trackpath);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
seekbar.setEnabled(true);
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
playPause.setImageResource(R.drawable.play);
}
else {
mPlayer.start();
playPause.setImageResource(R.drawable.pause);
seekbar.setMax(mPlayer.getDuration());
new Thread(this).start();
}
}
if(v.equals(next) && mPlayer != null){
if(shuffling==false) {
if (mPlayer.isPlaying()) {
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
if (looping == true) {
if (AllSongs.songPos == songList.size() - 1) {
AllSongs.songPos = 0;
currsong = songList.get(AllSongs.songPos);
} else {
AllSongs.songPos++;
currsong = songList.get(AllSongs.songPos);
}
} else {
if (AllSongs.songPos == songList.size() - 1) {
Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
//currsong=mainActivity.songList.get(mainActivity.songPos);
} else {
AllSongs.songPos++;
currsong = songList.get(AllSongs.songPos);
}
}
}else{
if (mPlayer.isPlaying()) {
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
/*Random rand = new Random();
int randomNum = mainActivity.songPos;
while(randomNum==mainActivity.songPos) {
randomNum = rand.nextInt(shuffleSong.size());
}
currsong = shuffleSong.get(randomNum);
shuffleSong.remove(randomNum);*/
if (looping == true) {
if (AllSongs.songPos == shuffleSong.size() - 1) {
AllSongs.songPos = 0;
currsong = shuffleSong.get(AllSongs.songPos);
} else {
AllSongs.songPos++;
currsong = shuffleSong.get(AllSongs.songPos);
}
} else {
if (AllSongs.songPos == shuffleSong.size() - 1) {
Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
//currsong=mainActivity.songList.get(mainActivity.songPos);
} else {
AllSongs.songPos++;
currsong = shuffleSong.get(AllSongs.songPos);
}
}
}
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
seekbar.setMax(mPlayer.getDuration());
seekbar.setProgress(0);
playSong();
}
if(v.equals(prev) && mPlayer != null){
if(shuffling==false) {
if(mPlayer.isPlaying()){
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
if (looping == true) {
if (AllSongs.songPos == 0) {
AllSongs.songPos = songList.size() - 1;
currsong = songList.get(AllSongs.songPos);
} else {
AllSongs.songPos--;
currsong = songList.get(AllSongs.songPos);
}
} else {
if (AllSongs.songPos == 0) {
Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
} else {
AllSongs.songPos--;
currsong = songList.get(AllSongs.songPos);
}
}
}else{
if (mPlayer.isPlaying()) {
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
if (looping == true) {
if (AllSongs.songPos == 0) {
AllSongs.songPos = shuffleSong.size() - 1;
currsong = shuffleSong.get(AllSongs.songPos);
} else {
AllSongs.songPos--;
currsong = shuffleSong.get(AllSongs.songPos);
}
} else {
if (AllSongs.songPos == 0) {
Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
} else {
AllSongs.songPos--;
currsong = shuffleSong.get(AllSongs.songPos);
}
}
/*Random rand = new Random();
int randomNum = mainActivity.songPos;
while(randomNum==mainActivity.songPos) {
randomNum = rand.nextInt(shuffleSong.size());
}
currsong = shuffleSong.get(randomNum);
shuffleSong.remove(randomNum);*/
}
Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
relativeLayout.setBackground(drawable);
seekbar.setMax(mPlayer.getDuration());
seekbar.setProgress(0);
playSong();
}
if(v.equals(loop)){
if(looping==false) {
loop.setImageResource(R.drawable.loopactive);
looping = true;
}
else{
looping=false;
loop.setImageResource(R.drawable.loop);
}
}
if(v.equals(shuffle)){
if(shuffling==false) {
getSongList();
shuffle.setImageResource(R.drawable.shuffleactive);
shuffling = true;
Collections.shuffle(shuffleSong);
//setNextSongDetails();
//shuffleList();
}else{
shuffleSong.clear();
shuffling=false;
shuffle.setImageResource(R.drawable.shuffle);
//setNextSongDetails();
}
}
}
/*private void shuffleList() {
for(int i=0;i<mainActivity.songList.size();i++){
Random rand = new Random();
int randomNum = rand.nextInt((mainActivity.songList.size() - i)) + i;
int j=0,k=0;
int flag=0;
k=mainActivity.posList.size();
for(j=0;j<k;j++){
if(MainActivity.posList.get(j) == randomNum){
flag=1;
}
//j=j+1;
}
if(flag==1){
i=i-1;
}else{
MainActivity.posList.add(new Integer(randomNum));
tempsong=MainActivity.songList.get(randomNum);
shuffleSong.add(new Song(tempsong.getID(), tempsong.getTitle(), tempsong.getArtist(), tempsong.getAlbumID()));
}
}
}*/
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
try {
if (mPlayer.isPlaying() || mPlayer != null) {
if (fromUser)
mPlayer.seekTo(progress);
} else if (mPlayer == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
//Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = mPlayer.getCurrentPosition();
int total = mPlayer.getDuration();
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onCompletion(MediaPlayer mp) {
if(mPlayer.getCurrentPosition()>0){
mp.reset();
next.performClick();
}
}
}

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.

junit test with Eclipse

Hi i am trying to use junit and it does not work s well.
Here is my code.
package safe;
import java.lang.reflect.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import safe.SafetyException;
public class SafetyInspector {
public static boolean isSafe(Class<?> clazz) throws SafetyException{
if (clazz.equals(Object.class)) return true;
if (clazz == null ) {
throw new SafetyException();
}
Field fields[] = clazz.getDeclaredFields();
for(Field f: fields){
f.setAccessible(true);
int mod = f.getModifiers();
if (Modifier.isFinal(mod)){
continue;
}
else if (Modifier.isPrivate(mod)){
Class<?> typeArray[] = new Class<?>[1] ;
typeArray[0] = f.getType();
try {
Method mSet = clazz.getMethod("set" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray );
int modMet = mSet.getModifiers();
if(!Modifier.isPublic(modMet)) return false;
if(!mSet.getReturnType().equals(void.class)) return false;
}
catch (SecurityException e) {
throw new SafetyException();
}
catch (NoSuchMethodException e) {
return false;
}
try {
Class<?> typeArray2[] = new Class<?>[1] ;
Method mGet = clazz.getMethod("get" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray2);
int modMet2 = mGet.getModifiers();
if(!Modifier.isPublic(modMet2)) return false;
if(!mGet.getReturnType().equals(f.getType())) return false;
}
catch (SecurityException e) {
throw new SafetyException() ;
}
catch (NoSuchMethodException e) {
return false;
}
}
}
return isSafe(clazz.getSuperclass());
}
public static void sort(List<Class<?>> classes) throws SafetyException{
for (int i = 1; i < classes.size(); i++) {
for (int j = 0; j < classes.size() - i; j++) {
if (compare(classes.get(j), classes.get(j + 1)) > 0) {
swap(classes, j);
}
}
}
}
public static void reset(Object object) throws SafetyException{
Class c = object.getClass();
Field fields[] = c.getDeclaredFields();
for(Field f :fields ){
if (!isSafe(f.getClass()))
{
f.setAccessible(true);
try{
if(!f.getClass().isPrimitive()){
}
else if(f.getClass().equals(boolean.class)){
f.setBoolean(object, false);
}
else{
f.set(object, 0);
}
}
catch(Exception e)
{
throw new SafetyException();
}
}
}
}
private static int compare(Class<?> o1, Class<?> o2) throws SafetyException {
Field[] fields1 = o1.getDeclaredFields();
int count1 = 0;
for (Field f : fields1){
if (isSafe(f.getClass())) count1++;
}
Field[] fields2 = o2.getDeclaredFields();
int count2 = 0;
for (Field f : fields2){
if (isSafe(f.getClass())) count2++;
}
if (count1 == count2)
return o1.getName().compareTo(o2.getName());
else return count1- count2;
}
private static void swap(List<Class<?>> list, int j) {
Class<?> temp = list.get(j);
list.set(j, list.get(j+1));
list.set(j + 1, temp);
}
};
and here is the code junit test that they gave me.
package test;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import safe.SafetyException;
import safe.SafetyInspector;
public class SafetyInspectorTest {
#Test
public void testIsSafeEmployee() throws SafetyException {
assertEquals(false, SafetyInspector.isSafe(Employee.class));
}
#Test
public void testResetEmployee() throws SafetyException {
Employee e = new Employee(123,3000);
SafetyInspector.reset(e);
assertEquals(0, e.id);
assertEquals(3000, e.getSalary());
}
#Test
public void testSort() throws SafetyException {
List<Class<?>> sortedClasses = new LinkedList<Class<?>>();
sortedClasses.add(Employee.class);
List<Class<?>> classes = new LinkedList<Class<?>>(sortedClasses);
Collections.shuffle(classes);
SafetyInspector.sort(classes);
assertEquals(sortedClasses, classes);
}
}
and when I run the safetyInspectorTest as a junitTESTCLASS i get an initialization error. I work with eclipse if it helps and I put Junit as a library of the project.
An initialization error in JUnit is generally caused by a bad classpath. See this related question which also suffered from initialization error:
Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window
The most likely cause is as that question addressed, you are using a version of JUnit 4 which requires the hamcrest jar to be added. Instead of adding the junit and hamcrest jars you should be able to add the JUnit 4 library on your project's Java Build Path.
Your imports largely look benign but you should confirm safe.SafetyException is on your classpath.
Finally, the initialization error could be caused by a static initialization failure in code that loads before your test runs. The code you've posted looks safe but SafetyException class could possibly have an initialization block to check.