LWUIT and kXML Parser - java-me

Uncaught exception: java.lang.Error: Static initializer: java.lang.NullPointerException, 0
- java.lang.Class.throwError(), bci=57
- java.lang.Class.initialize(), bci=221
- com.sun.lwuit.Component.<init>(), bci=5
- com.sun.lwuit.Container.<init>(), bci=1
- com.sun.lwuit.Form.<init>(), bci=8
- com.sun.lwuit.Form.<init>(), bci=1
- com.midlet.RSSMidlet.<init>(), bci=11
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=9
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=4
- com.sun.midp.appmanager.SelectorBase.run(), bci=33
- java.lang.Thread.run(), bci=11
Coding:
package com.midlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
//import com.sun.lwuit.list.ListModel;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class RSSMidlet extends MIDlet implements ActionListener{
public Vector feedVector;
public String rssFeed;
private Command cmdSelect;
private Command cmdExit;
private Form form1 = new Form("Feeds List");
// private Form form2 = new Form("Feed Description");
// private Vector feed_Title;
private List resultList;
// private List feedTitle;
public RSSModel model = new RSSModel();
class ReadXML extends Thread{
public void run(){
try{
rssFeed = "http://www.rottentomatoes.com/syndication/rss/top_news.xml";
HttpConnection httpConnection = (HttpConnection) Connector.open(rssFeed);
KXmlParser parser = new KXmlParser();
parser.setInput(new InputStreamReader(httpConnection.openInputStream()));
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, null);
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "channel");
readXMLData(parser);
parser.require(XmlPullParser.END_TAG, null, "channel");
}
parser.require(XmlPullParser.END_TAG, null, "rss");
parser.next();
parser.require(XmlPullParser.END_DOCUMENT, null, null);
}catch(Exception e){
}
}
}
public RSSMidlet() {
// TODO Auto-generated constructor stub
Display.init(this);
Resources r;
try{
r = Resources.open("/LWUITtheme.res");
UIManager.getInstance().setThemeProps(r.getTheme("LWUITDefault"));
}catch(IOException e){
//e.printStackTrace();
}
resultList = new List();
for(int i=0; i<feedVector.size();i++){
model = (RSSModel) feedVector.elementAt(i);
resultList.addItem(model.getTitle().toString());
}
form1.addComponent(BorderLayout.CENTER,resultList);
form1.addCommand(cmdExit);
form1.addCommand(cmdSelect);
form1.setScrollable(true);
//form1.addCommandListener((ActionListener) this);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
new ReadXML().start();
}
public void readXMLData(KXmlParser parser) throws IOException, XmlPullParserException{
while(!"item".equals(parser.getName()) ){
/** Check if document doesn't include any item tags */
if( parser.next() == XmlPullParser.END_DOCUMENT )
throw new IOException("No items in RSS feed!");
}
parser.require(XmlPullParser.START_TAG, null, "item");
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.require(XmlPullParser.START_TAG, null, null);
String name = parser.getName();
String text = parser.nextText();
//System.out.println ("<"+name+">"+text);
if(name.equals("pubDate")){
model.setPubDate(text);
}else if(name.equals("title")){
model.setTitle(text);
}else if(name.equals("link")){
model.setLink(text);
}else if(name.equals("description")){
model.setDescription(text);
}
parser.require(XmlPullParser.END_TAG, null, name);
}
feedVector.addElement(model);
parser.require(XmlPullParser.END_TAG, null, "item");
}
public void actionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
if(evt.getCommand() == cmdExit){
notifyDestroyed();
}else if(evt.getCommand() == cmdSelect){
}
}
}
This is my codes. I can't seem to get LWUIT running with kXML. There is a forum post that says that I need to initialize graphics objects after the Display.init(this) line. But where that line should lie? Please assist me...

The Display.init(your_midlet) is responsible for initializing the Display for LWUIT, no need to do it yourself. Only restriction is, you have to initialize the Display BEFORE you use any Form.
Move the line
form1 = new Form("Feeds List")
after the line
Display.init(this);
so you initialize the Form in the Constructor after initializing the Display!

Related

How to generate extent report for cucumber + testng framework

How to generate extent report for cucumber + testng framework in such a way that on each scenario failure I can get the screen shot captured, without repeating the code with every scenario in step definition file
I have setup the Testing framework using Cucumber+Testng. However, I need extent reporting but not sure how to achieve it through testNG runner class without actually repeating the code with every scenario of step definition. So the idea is to write code in one place just like using cucumber hooks which will run for each and every scenario.
I Have already tried the approach with TestNG listener with Extent report but with this the drawback is I have to write the code every time for each and every scenario. LIke below I have ITestListnerImpl.java, ExtentReportListner and YouTubeChannelValidationStepDef where for each scenario I have to repeat the loginfo and screencapture methods
Code: ItestListerner.java
package com.testuatomation.Listeners;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
public class ITestListenerImpl extends ExtentReportListener implements ITestListener {
private static ExtentReports extent;
#Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
extent.flush();
System.out.println("Execution completed on UAT env ......");
}
#Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
extent = setUp();
System.out.println("Execution started on UAT env ......");
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0){
// TODO Auto-generated method stub
}
#Override
public void onTestFailure(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("FAILURE");
}
#Override
public void onTestSkipped(ITestResult arg0) {
System.out.println("SKIP");
}
#Override
public void onTestStart(ITestResult arg0) {
System.out.println("STARTED");
}
#Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("PASS-----");
}
}
ExtentReportListener. java
package com.testuatomation.Listeners;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentReportListener {
public static ExtentHtmlReporter report = null;
public static ExtentReports extent = null;
public static ExtentTest test = null;
public static ExtentReports setUp() {
String reportLocation = "./Reports/Extent_Report.html";
report = new ExtentHtmlReporter(reportLocation);
report.config().setDocumentTitle("Automation Test Report");
report.config().setReportName("Automation Test Report");
report.config().setTheme(Theme.STANDARD);
System.out.println("Extent Report location initialized . . .");
report.start();
extent = new ExtentReports();
extent.attachReporter(report);
extent.setSystemInfo("Application", "Youtube");
extent.setSystemInfo("Operating System", System.getProperty("os.name"));
extent.setSystemInfo("User Name", System.getProperty("user.name"));
System.out.println("System Info. set in Extent Report");
return extent;
}
public static void testStepHandle(String teststatus,WebDriver driver,ExtentTest extenttest,Throwable throwable) {
switch (teststatus) {
case "FAIL":
extenttest.fail(MarkupHelper.createLabel("Test Case is Failed : ", ExtentColor.RED));
extenttest.error(throwable.fillInStackTrace());
try {
extenttest.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (IOException e) {
e.printStackTrace();
}
if (driver != null) {
driver.quit();
}
break;
case "PASS":
extenttest.pass(MarkupHelper.createLabel("Test Case is Passed : ", ExtentColor.GREEN));
break;
default:
break;
}
}
public static String captureScreenShot(WebDriver driver) throws IOException {
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest = "C:\\Users\\Prateek.Nehra\\workspace\\SeleniumCucumberBDDFramework\\screenshots\\" + getcurrentdateandtime() + ".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
private static String getcurrentdateandtime() {
String str = null;
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
Date date = new Date();
str = dateFormat.format(date);
str = str.replace(" ", "").replaceAll("/", "").replaceAll(":", "");
} catch (Exception e) {
}
return str;
}
}
YoutubeChannelValidationsStepDef.java
package com.testautomation.StepDef;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Feature;
import com.aventstack.extentreports.gherkin.model.Scenario;
import com.testuatomation.Listeners.ExtentReportListener;
import com.testautomation.PageObjects.YoutubeChannelPage;
import com.testautomation.PageObjects.YoutubeResultPage;
import com.testautomation.PageObjects.YoutubeSearchPage;
import com.testautomation.Utility.BrowserUtility;
import com.testautomation.Utility.PropertiesFileReader;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class YoutubeChannelValidationsStepDef extends ExtentReportListener
{
PropertiesFileReader obj= new PropertiesFileReader();
private WebDriver driver;
#Given("^Open Chrome browser with URL$")
public void open_Chrome_browser_with_URL() throws Throwable
{
ExtentTest logInfo=null;
try {
test = extent.createTest(Feature.class, "Youtube channel name validation");
test=test.createNode(Scenario.class, "Youtube channel name validations");
logInfo=test.createNode(new GherkinKeyword("Given"), "open_Chrome_browser_with_URL");
Properties properties=obj.getProperty();
driver=BrowserUtility.OpenBrowser(driver, properties.getProperty("browser.name"), properties.getProperty("browser.baseURL"));
logInfo.pass("Opened chrome browser and entered url");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial$")
public void search_selenium_tutorial() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "search_selenium_tutorial");
new YoutubeSearchPage(driver).NavigateToResultPage("selenium by bakkappa n");
logInfo.pass("Searching selenium tutorial");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial \"([^\"]*)\"$")
public void search_selenium_tutorial(String searchString) throws Throwable
{
new YoutubeSearchPage(driver).NavigateToResultPage(searchString);
}
#When("^Click on channel name$")
public void click_on_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "click_on_channel_name");
new YoutubeResultPage(driver).NavigateToChannel();
logInfo.pass("Clicked on the channel name");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#Then("^Validate channel name$")
public void validate_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("Then"), "validate_channel_name");
String expectedChannelName="1Selenium Java TestNG Tutorials - Bakkappa N - YouTube";
String actualChannelName=new YoutubeChannelPage(driver).getTitle();
Assert.assertEquals(actualChannelName, expectedChannelName,"Channel names are not matching"); //
logInfo.pass("Validated channel title");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
System.out.println("closing browser");
driver.quit();
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
}
Your lofInfo is null, should be something like this
#Then("Open Chrome browser with URL")
public void open_Chrome_browser_with_URL() {
try {
logInfo = test.createNode(new GherkinKeyword("Then"), "open_Chrome_browser_with_URL");
//YOUR CODE HERE
logInfo.pass("Chrome opens URL");
}
catch (AssertionError | Exception e) {testStepHandle("FAIL", d, logInfo, e);
}
}

Error Parsing Data java.lang.IllegalStateException: Not on the main thread when trying to add a marker

I am trying to update markers on Google map using a service, but when I use the "setParkingSpotMarker" function that add a marker to every item at the list I get an error "java.lang.IllegalStateException: Not on the main thread"
The function "setParkingSpotMarker" is called in the loop inside the service -DataUpdateService.
I don't know how to change my code so it will update the markers on the main thread.I have read some posts about that but didn't understand how to change it in my code.
this is the service:
package com.example.sailon;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class DataUpdateService extends Service {
Timer myTimer = new Timer();
MyTimerTask myTask = new MyTimerTask();
MyMap mymap;
String teamID;
static LatLng teamLocation;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
String action;
Context fromContext;
String CompName;
String heatNum;
boolean isSailor;
String usermail;
GPSTracker gps;
private final IBinder mBinder = new LocalBinder();
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PS", "DataUpdateService onStartCommand");
return Service.START_NOT_STICKY;
}
#Override
// return thee instance of the local binder to the activity
public IBinder onBind(Intent intent) {
Log.d("PS", "DataUpdateService onBind");
return mBinder;
}
public class LocalBinder extends Binder {
DataUpdateService getService() {
Log.d("PS", "DataUpdateService LocalBinder onBind");
return DataUpdateService.this;
}
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
String unitToUpdate= mymap.getUnitToUpdate (CompName,heatNum,usermail);
Log.d("NY","CompName " +CompName);
Log.d("NY","heatNum " +heatNum);
Log.d("NY","usermail " +usermail);
Log.d("NY","unitToUpdate" +unitToUpdate);
Log.d("NY","isSailor" +isSailor);
if (isSailor){
gps = new GPSTracker(DataUpdateService.this,unitToUpdate );
if( ! (gps.canGetLocation())){
gps.showSettingsAlert();
}
}
unitswithteam=mymap.refresh (CompName,heatNum);
int j= unitswithteam.size();
for (int i=0; i<j;i++){
teamID=unitswithteam.get(i).getTeamID();
Log.d("NY","teamID "+i+teamID);
UnitsInHeats us=unitswithteam.get(i).getUnit();
teamLocation = new LatLng(us.getLat(),us.getLng() );
Log.d("NY","team location "+i + " "+us.getLat());
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
}
}
}
// called from the activity
public void MapUpdateFromService(Context context, MyMap map, final String action,
String CompName, String heatNum, boolean isSailor , String usermail) {
Log.d("PS", "DataUpdateService MapUpdateFromService");
this.mymap = map;
this.action = action;
this.CompName=CompName;
this.heatNum=heatNum;
this.isSailor=isSailor;
this.usermail=usermail;
// this command activate the run function from the inner class MyTimerTask every 5 seconds.
myTimer.schedule(myTask,0,5000);
}
public void onDestroy() {
super.onDestroy();
// cancel the scheduler.
myTimer.cancel();
}
}
this is the activity that calls the service:
package com.example.sailon;
import java.util.ArrayList;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Map extends Activity {
Bundle extras;
// private GoogleMap map;
static LatLng teamLocation;
//public static ArrayList<Teams> teams;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
Marker mark;
double lat;
double lng;
GPSTracker gps;
String Location ;
String teamID;
String CompName;
MyMap mymap;
String heatNum;
String CompID;
boolean isSailor;
String usermail;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
// ArrayList<LatLng> List= new ArrayList<LatLng>() ;
DataUpdateService dbuService;
boolean dbuBound=false;// when service connected get true
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mymap= new MyMap(this,((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap());
//map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
extras = getIntent().getExtras();
CompName=extras.getString("CompName");
heatNum=extras.getString("heatNum");
isSailor=extras.getBoolean("isSailor");
usermail=extras.getString("usermail");
Log.d("CompName",CompName);
Log.d("heatNum",heatNum);
// get action bar
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
if (mymap!=null){
Log.d("PS", "map isnt null");
mymap.setMapType();
mymap.setMyLocationEnabled(true);
CameraPosition firstZom =new CameraPosition.Builder()
.target(BeerSheva)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(firstZom);
}
}
// serviceConnerction is an interface that must be implemented when using bound service
private ServiceConnection sConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("PS", "Map onServiceConnected");
DataUpdateService.LocalBinder binder=(DataUpdateService.LocalBinder)service;
dbuService=binder.getService();
Log.d("PS", "Map callupdate");
dbuService.MapUpdateFromService(Map.this,mymap,"ActionSearch",CompName,heatNum, isSailor,usermail);
dbuBound=true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.d("PS", "Map onServiceDisconnected");
dbuBound=false;
}
};
#Override
protected void onStart() {
super.onStart();
// Bind to DataUpdateService
Log.d("PS", "Map onStart");
Intent intent= new Intent(this,DataUpdateService.class);
bindService(intent,sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
Log.d("PS", "Map onStop");
if(dbuBound){
unbindService(sConnection);
dbuBound=false;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.logoutAction:
Intent i = new Intent(Map.this, MainActivity.class);
startActivity(i);
return true;
case R.id.VideoAction:
Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
startActivity(intent);
return true;
case R.id.CallAction:
Intent call = new Intent(Intent.ACTION_DIAL);
startActivity(call);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is the calss of the map:
package com.example.sailon;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseException;
import java.util.ArrayList;
/**
* Created by Evyatar.m on 21/02/2015.
*/
public class MyMap {
private GoogleMap map;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
String CompID;
String teamID;
String CompName;
String heatNum;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam2= new ArrayList<UnitInHeatForMap>();
static LatLng teamLocation;
Model DB;
public MyMap(Context context, GoogleMap map) {
Log.d("PS", "MyMap builder");
DB = Model.getInstance(context);
this.map = map;
}
public String getUnitToUpdate (String CompName,String heatNum, String usermail){
String unit=null;
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
unit= DB.getUnitToUpdateFromDB (CompID,heatNum, usermail);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unit;
}
public void setMyLocationEnabled(boolean b){
Log.d("PS", "MyMap set location enable");
map.setMyLocationEnabled(true);
}
public void setParkingSpotMarker(LatLng teamLocation,String teamID) {
Log.d("PS", "ParkingMap setParkinSpotMarker");
map.addMarker(new MarkerOptions()
.position(teamLocation)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.iconsmall))
.title("Team " +teamID)).showInfoWindow();
}
public void setMapType(){
Log.d("PS", "MyMap setType");
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void moveMyMapCamera(CameraPosition firstZom) {
Log.d("PS", "MyMap moveParkingMapCamera");
map.moveCamera(CameraUpdateFactory.newCameraPosition(firstZom));
}
//updates all points on map
public ArrayList<UnitInHeatForMap> refresh (String CompName,String heatNum){
Log.d("PS", "MyMap refresh");
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
DB.setUnitInHeatForMap (new Model.CallbackModel () {
#Override
public void done (ArrayList<UnitInHeatForMap> unitswithteam){
if (unitswithteam.size() >0){
unitswithteam2=unitswithteam;
}
}
}, CompID, heatNum,this);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unitswithteam2;
}
}
please help me
thanks !!!**
The run method of the TimerTask runs on background thread, and you can only update the map on the main thread.
So you have to wrap the following Map UI update codes into runOnUiThread()
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
You need to have an Activity to apply runOnUIThread, so you need to put your
fromContext = ((Map)context);
inside the first line of your MapUpdateFromService method. Then you can call runOnUiThread() in your TimerTask's run() method.
((Map)fromContext).runOnUiThread(new Runnable() {
#Override
public void run() {
//run your Map UI update code
}
});
This is also a similar issue of this problem.

ASM ByteCode Instrumentation , Which Method is Executed

I am using ASM Bytecode Library to instrument Java Classes using pre-main.
How do we get the name of the method executed?
Thanks in advance...
In short, there is a name parameter on corresponding visit*() method call. You'll have to produce a more specific example to get more detailed answer.
Attached my Code for your reference
package com.eg.agent;
import java.lang.instrument.Instrumentation;
public class Agent {
private Agent(Instrumentation instrumentation){
}
public static void premain(String agentArgs, Instrumentation inst)
{
EgClassFileTransformer egClassFileTransformer =
new EgClassFileTransformer (agentArgs , inst);
}
}
package com.eg.agent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.objectweb.asm.ClassReader;
public class EgClassFileTransformer implements ClassFileTransformer {
protected String agentArgString = "";
protected Instrumentation instrumentation;
public EgClassFileTransformer(String agentArgs, Instrumentation inst){
agentArgString = agentArgs;
instrumentation = inst;
instrumentation.addTransformer(this);
}
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException
{
//System.out.println("ClassName :"+className);
InputStream in = loader.getResourceAsStream(className.replace('.', '/') + ".class");
try{
ClassReader classReader=new ClassReader(in);
String superClassName = classReader.getSuperName();
String[] interfaces = classReader.getInterfaces();
if(interfaces!=null && interfaces.length > 0){
for(int k=0;k<interfaces.length;k++){
String inface = interfaces[k];
System.out.println(" \t interface :"+inface);
}
}
//System.out.println("superClassName :"+superClassName);
ArrayList thisList = new ArrayList();
thisList.add(superClassName);
ArrayList superList = printSuperClassNames(superClassName , thisList);
System.out.println("className :"+className +" ==>"+ " superList :"+superList);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("[EXECEPTION] ..."+className);
}
return null;
}
public static ArrayList printSuperClassNames(String className, ArrayList list)
{
ClassReader cr=null;
try {
cr = new ClassReader(className);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String superName = cr.getSuperName();
//System.out.println("[superName]"+superName);
if(superName!=null && !superName.equals("java/lang/Object"))
{
list.add(superName);
String superClass = superName.replace('.', '/');
printSuperClassNames(superClass, list);
}
return list;
}
}

TextField.setConstraints null pointer exception

I have a TextField in a form:
private TextField cc1F = new TextField("", "", 250, TextField.ANY);
Once click button OK, then set cc1F field's Constraints to:
cc1F.setConstraints(TextField.UNEDITABLE);
then I am getting an exception:
java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultInputMethodHandler.setConstraints(+63)
at javax.microedition.lcdui.TextField$InputMethodClientImpl.setConstraints(+20)
at javax.microedition.lcdui.TextField.setConstraints(+37)
at com.zousys.j2me.zmail.gui.view.HeaderView.menuAction(+146)
.....................................
Anyone know this?
The example of code was tested with simulator WTK 3.0 and device Samsung Chat
http://www.gsmarena.com/samsung_ch#t_527-4096.php and the test passed. :)
I think that the problem is caused by device model or the object cc1F is null.
import java.io.UnsupportedEncodingException;
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.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TextFieldMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command cmdExit;
private Command cmdSetConstraints;
private Display display;
private TextField textField;
public TextFieldMIDlet() {
form = new Form("Testing constraints");
cmdExit = new Command("Exit",Command.EXIT, 1);
cmdSetConstraints = new Command("Set Constraints",Command.ITEM, 1);
textField = new TextField("", "", 250, TextField.ANY);
form.addCommand(cmdExit);
form.addCommand(cmdSetConstraints);
form.append(textField);
display = Display.getDisplay(this);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.notifyDestroyed();
} else if (c == cmdSetConstraints) {
try {
System.out.println("Set...");
if (textField.getConstraints() == TextField.UNEDITABLE) {
textField.setConstraints(TextField.ANY );
} else {
textField.setConstraints(TextField.UNEDITABLE );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

implementing grid view with in a horizontal scroll(view flipper)

i want to implement a horizontal slide to my grid view so that one slide displays 9 images and next slide displays the other 9 images and so on. The images here are took from sd card. can any one help out please..!!
after a trying for a long time i got the right code as
package flipper.view;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class NewflipperActivity extends Activity implements OnClickListener,OnTouchListener{
ViewFlipper flip;
Animation animFlipInForeward;
Animation animFlipOutForeward;
Animation animFlipInBackward;
Animation animFlipOutBackward;
int filepos=0;
int y;
private GestureDetector gestureDetector;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
RelativeLayout rl1,rl2;
TextView tv1,tv2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display dip=getWindowManager().getDefaultDisplay();
int width=dip.getWidth();
int actualheight=dip.getHeight();
System.out.println("width is--->"+width);
System.out.println("height is--->"+actualheight);
int layoutheight=(actualheight)/8;
int flipheight=6*layoutheight;
RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(width,layoutheight-30);
params1.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
tv1=(TextView)findViewById(R.id.textView1);
tv1.setLayoutParams(params1);
RelativeLayout.LayoutParams params2=new RelativeLayout.LayoutParams(width,layoutheight-30);
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
tv2=(TextView)findViewById(R.id.textView2);
tv2.setLayoutParams(params2);
gestureDetector = new GestureDetector(new MyGestureDetector());
flip=(ViewFlipper)findViewById(R.id.viewFlipper1);
flip.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return false;
}
return true;
}
});
LinearLayout mylay=(LinearLayout)findViewById(R.id.linearlay);
LinearLayout.LayoutParams layparam=new LinearLayout.LayoutParams(width,flipheight);
mylay.setLayoutParams(layparam);
animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
animFlipOutForeward = AnimationUtils.loadAnimation(this, R.anim.flipout);
animFlipInBackward = AnimationUtils.loadAnimation(this, R.anim.flipin_reverse);
animFlipOutBackward = AnimationUtils.loadAnimation(this, R.anim.flipout_reverse);
String folderpath=Environment.getExternalStorageDirectory()+"/New Folder/";
File filepath=new File(folderpath);
File[] mylist=filepath.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return (filename.toLowerCase().endsWith(".jpg")||filename.toLowerCase().endsWith(".png")||filename.toLowerCase().endsWith(".jpeg"));
}
});
Arrays.sort(mylist);
int folderlength=mylist.length;
int mylength=folderlength/9;
if(folderlength%9==0)
{
y=mylength;
}
else
{
y=(mylength)+1;
}
for(int i=0;i<y;i++)
{System.out.println("abc"+i);
TableLayout mtable=new TableLayout(this);
TableLayout.LayoutParams myparams=new TableLayout.LayoutParams(width,flipheight);
mtable.setLayoutParams(myparams);
mtable.setWeightSum(3);
mtable.setOnTouchListener(NewflipperActivity.this);
for(int j=0;j<3;j++)
{
TableRow mrow=new TableRow(this);
mrow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
mrow.setOnTouchListener(NewflipperActivity.this);
for(int k=0;k<3;k++)
{
if(filepos<folderlength)
{
Log.i("displaying","image at file pos"+mylist[filepos]);
final ImageView imageView = new ImageView(this);
Bitmap imgBitmap,b1;
try
{
if(mylist[filepos].length()>1500){
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 4;
imgBitmap = BitmapFactory.decodeFile(mylist[filepos] + "",bounds);
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20, ((int)(flipheight/3))-20, true);
}
else
{
imgBitmap=BitmapFactory.decodeFile(mylist[filepos] + "");
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20,((int)(flipheight/3))-20, true);
}
imageView.setImageBitmap(b1);
imageView.setAdjustViewBounds(true);
imageView.setPadding(10,10,10,10);
imageView.setTag(mylist[filepos]+"");
imageView.setOnTouchListener(NewflipperActivity.this);
imageView.setOnClickListener(NewflipperActivity.this);
// final String imagename=mylist[filepos].getName();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mrow.addView(imageView);
filepos++;
}
}
mtable.addView(mrow);
}
flip.addView(mtable);
}
}
private void SwipeRight(){
flip.setInAnimation(animFlipInBackward);
flip.setOutAnimation(animFlipOutBackward);
flip.showPrevious();
}
private void SwipeLeft(){
flip.setInAnimation(animFlipInForeward);
flip.setOutAnimation(animFlipOutForeward);
flip.showNext();
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
SwipeLeft();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
SwipeRight();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImageView imagename1 = (ImageView)v;
String imgName = (String) imagename1.getTag();
Toast.makeText(NewflipperActivity.this, "clicked on image-->"+imgName, Toast.LENGTH_SHORT).show();
Log.e("displaying","clicked onimage::::::"+imgName);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
}

Resources