How to play .mp3 file repeatedly in android? - android-mediaplayer

I wanted to play .mp3 repeatedly say for 5-10 times as once the item is selected, a song should play for 5 times repeatedly.
Using SoundPool is not benefit as the song plays only for 5 seconds. I wanted the song to play completely and repeat again.
when Setlooping for media player play the song indefinitely.
Is there any possibilities to play song no of times and no of times would be defined programmatically before application starts. Pleas any one help.
public class BackgroundAudioService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
MediaPlayer mp;
SoundPool loopChant;
int itempositionno;
int soundID, i;
Uri path;
Intent playbackServiceIntent;
BackgroundAudioService instanceService;
public BackgroundAudioService() {
Log.d(this.getClass().getName(), "Background method called");
}
#Override
public void onCreate() {
Log.d(this.getClass().getName(), "onCreate method called");
instanceService = this;
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
Log.d(this.getClass().getName(), "onBind method called");
int itempositionno = intent.getIntExtra("Itempositionno", 0);
this.itempositionno = itempositionno;
if (mp == null ){
mp = new MediaPlayer();}
setSongAtPosition(itempositionno);
return new LocalBinder();
}
public void setSongAtPosition(int position){
Log.d(this.getClass().getName(), "setSongAtPosition method called");
itempositionno = position;
Uri path = null;
switch (itempositionno){
case 0:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.shiva);
break;
}
case 1:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.perumal);
break;
}
case 2:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.ganesh);
break;
}
case 3:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.muruga);
break;
}
case 4:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.iyyappa);
break;
}
case 5:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.hanuman);
break;
}
case 6:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.gayathri);
break;
}
case 7:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.aigiri);
break;
}
case 8:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.saibaba);
break;
}
case 9:{
path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.om);
break;
}
}
if(mp.isPlaying()) {
mp.release();
}
mp = MediaPlayer.create(BackgroundAudioService.this, path);
mp.setOnPreparedListener(BackgroundAudioService.this);
if (itempositionno == 1){
setLoopChant();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(this.getClass().getName(), "onPrepared method called");
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(this.getClass().getName(), "onCompletion method called");
}
class LocalBinder extends Binder{
public BackgroundAudioService getService(){
Log.d(this.getClass().getName(), "LocalBinder method called");
return instanceService;
}
}
public void setLoopChant(){
Log.d(this.getClass().getName(), "setLoopChant method called");
mp.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(this.getClass().getName(), "onStartCommand method called");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Log.d(this.getClass().getName(), "onDestroy method called");
mp.release();
super.onDestroy();
}
}

Your code doesn't even play a media once. You forgot to call
mp.prepareAsync();
right after you set the DataSource.
Why do you create the MediaPlayer twice? I recommend moving the setOnPreparedListener to the line after new MediaPlayer().
if (mp == null ){
mp = new MediaPlayer();
mp.setOnPreparedListener(BackgroundAudioService.this);
}
and then call prepareAsync after setDataSource. Replace the line:
mp = MediaPlayer.create(BackgroundAudioService.this, path);
with
mp.setDataSource(path);
mp.prepareAsync();

Related

How to move map marker like moving car on road from source to destination

I want to move marker on Google map from source to destination like Uber or Ola and i am working on google map, I am new so Please help me how it is possible ...?
My code is :
public void onMapReady(GoogleMap googleMap) {
GoogleMap gMap = googleMap;
addMarks1(gMap);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setZoomControlsEnabled(true);
// Turns on 3D buildings
gMap.setBuildingsEnabled(true);
}
private void addMarks1(GoogleMap googleMap) {
googleMap.clear();
// updateRouteOnMAp();
double d_lat=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT));
double d_loing=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG));
fromPosition=new LatLng(d_lat,d_loing);
toPosition=new LatLng(Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LAT)),
Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LNG)));
List<Marker> markersList = new ArrayList<Marker>();
Marker StartLatLon= googleMap.addMarker(new MarkerOptions().position(fromPosition).title("Start Point").icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
Marker EndLatLon= googleMap.addMarker(new MarkerOptions().position(toPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
markersList.add(StartLatLon);
markersList.add(EndLatLon);
builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
int padding = 150;
LatLngBounds bounds = builder.build();
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
googleMap.animateCamera(cu);
traceMe(googleMap);
}
private void traceMe(final GoogleMap googleMap) {
String srcParam;
String destParam;
String startLat=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT);
String startLng=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG);
GPSTracker gpsTracker=new GPSTracker(getActivity());
srcParam = startLat + "," + startLng;
destParam = gpsTracker.getLatitude() + "," + gpsTracker.getLongitude();
Log.d("drop lat pp2", ":" + destParam);
String modes[] = {"driving", "walking", "bicycling", "transit"};
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + srcParam + "&destination=" + destParam + "&sensor=false&units=metric&mode=driving";
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("dkp lat long", ":" + response);
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
MapDirectionsParser parser = new MapDirectionsParser();
List<List<HashMap<String, String>>> routes = parser.parse(jsonObject);
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
List<HashMap<String, String>> path = routes.get(i);
Log.d("dkp lat long", ":" + path);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
}
Log.d("dkp points lat long", ":" + points);
drawPoints(points, googleMap);
String str_dist=parser.distance();
//String str_dur=parser.duration();
if (!str_dist.equals("null"))
{
distance= Integer.parseInt(str_dist);
//estimate_distance= (distance/100)+50;
//rideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
Log.d("dkp kkk distance", ":" + distance);
}
/*if (!str_dur.equals("null"))
{
int duration=Integer.parseInt(parser.duration());
estimate_duration= duration/60;
ideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
Log.d("dkp kkk duration", ":" + duration);
}*/
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d("error ocurred", "TimeoutError");
//Toast.makeText(getActivity(), "TimeoutError", Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
Log.d("error ocurred", "AuthFailureError");
//Toast.makeText(getActivity(), "AuthFailureError", Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
Log.d("error ocurred", "ServerError");
// emailEdt.requestFocus();
// Toast.makeText(getActivity(), "Please enter valid email or password", Toast.LENGTH_LONG).show();
// Toast.makeText(getActivity(), "ServerError", Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
Log.d("error ocurred", "NetworkError");
//Toast.makeText(getActivity(), "NetworkError", Toast.LENGTH_LONG).show();
} else if (error instanceof ParseError) {
Log.d("error ocurred", "ParseError");
//Toast.makeText(getActivity(), "ParseError", Toast.LENGTH_LONG).show();
}
}
});
// MyApplication.getInstance().addToRequestQueue(jsonObjectRequest, "jreq");
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
}
private void drawPoints(ArrayList<LatLng> points, GoogleMap mMaps) {
if (points == null) {
return;
}
traceOfMe = points;
PolylineOptions polylineOpt = new PolylineOptions();
for (LatLng latlng : traceOfMe) {
polylineOpt.add(latlng);
}
polylineOpt.color(Color.BLUE);
if (mPolyline != null) {
mPolyline.remove();
mPolyline = null;
}
if (mMaps != null) {
mPolyline = mMaps.addPolyline(polylineOpt);
} else {
}
if (mPolyline != null)
mPolyline.setWidth(7);
}
You will have to remove the marker from the map using googleMap.clear() and redraw it again in the new location.

JSON response Using Volley in a recycler view in Android app

I am trying to print a json response response in a recyclerview. my Recyclerview is like a expanded listView. And my json resone is like this:
{"Table1":
[
{"filedate":"Oct 26, 2016"},
{"filedate":"Oct 18, 2016"}
],
"Table2":
[{
"filedate":"Oct 18, 2016",
"file1":"12.txt"
},
{
"filedate":"Oct 26, 2016",
"file1":"acerinvoice.pdf"
}
]}
and I trying to print this json resonse using this code:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
//I think problrm is here
#Override
public void onResponse(String response) {
try {
**JSONObject object = new JSONObject(response);
JSONArray jsonarray = object.getJSONArray("Table1");
JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
String str = obj.optString("filedate").trim();
int lth = jsonarray1.length();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();**
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
Toast.makeText(getApplicationContext(), (CharSequence) data, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
ExpandableListAdapter
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
But this code print nothing in my recycler UI.It show only a empty layout.I have also tried to print the response in my log and it prints whole response together.I want to print table1 contents in headers and table2 contents in as child(items) with their respective headers.how to do this?If any other information needed please ask..
You should probably check your response first of everything. As per your requirements you should use HashMap and ArrayList. Follow these following steps:
1.Take a ArrayLsit and store child data of 1st heading and so on with index starting from 0.
2.Store headers in HashMap as key.
ex: HashMap<String,ArrayList<Data>> hm;
hm.put("your first heading string","related arraylist");
Then use ExpandableListView to arrange parent and child items.
please check your json response this is invalid json response first try to validate your json formate after try to decode and add in recycler view.
Check Your Response into Logcat also the Exception. I've tested the Response you've supplied that contains some unnecessary "," that may cause the Exception.
I have solve my problem to just change above code like this..
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
//
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str3 = obj1.optString("category").trim();
String str2 = obj1.optString("file1").trim();
String str4 = obj1.optString("4").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
// data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str3));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}

Customizing summary section of TestNG emailable report

TestNG generates an emailable report. I have seen that this report can be customized by using Listeners. But could not get what i wanted. My requirement is to include extra details in the summary section of this report. I want to be able to add may be a new table or extra columns to show the environment details of the test execution.
Trying to attach a screenshot but apparently missing something and it does not come up.
That is what I have on my framework. I'll try to explain it (sorry my English)
Copy ReporterListenerAdapter.java and rename as MyReporterListenerAdapter.java, put it on your java project (/listener folder for example)
public class MyReporterListenerAdapter implements IReporter {
public void generateReport(List<XmlSuite> xml, List<ISuite> suites, String outdir) {}
}
Next, copy ReporterListener.java and rename as MyReporterListener.java
Too much code to paste here, but on createWriter function change the report name. For example: "emailable-MyFramework-report".
MyReporterListener.java
public class MyReporterListener extends MyReporterListenerAdapter {
private static final Logger L = Logger.getLogger(MyReporterListener.class);
// ~ Instance fields ------------------------------------------------------
private PrintWriter m_out;
private int m_row;
private Integer m_testIndex;
private int m_methodIndex;
private Scanner scanner;
// ~ Methods --------------------------------------------------------------
/** Creates summary of the run */
#Override
public void generateReport(List<XmlSuite> xml, List<ISuite> suites,
String outdir) {
try {
m_out = createWriter(outdir);
} catch (IOException e) {
L.error("output file", e);
return;
}
startHtml(m_out);
generateSuiteSummaryReport(suites);
generateMethodSummaryReport(suites);
generateMethodDetailReport(suites);
endHtml(m_out);
m_out.flush();
m_out.close();
}
protected PrintWriter createWriter(String outdir) throws IOException {
java.util.Date now = new Date();
new File(outdir).mkdirs();
return new PrintWriter(new BufferedWriter(new FileWriter(new File(
outdir, "emailable-FON-report"
+ DateFunctions.dateToDayAndTimeForFileName(now)
+ ".html"))));
}
/**
* Creates a table showing the highlights of each test method with links to
* the method details
*/
protected void generateMethodSummaryReport(List<ISuite> suites) {
m_methodIndex = 0;
startResultSummaryTable("methodOverview");
int testIndex = 1;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 5);
}
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
String testName = testContext.getName();
m_testIndex = testIndex;
resultSummary(suite, testContext.getFailedConfigurations(),
testName, "failed", " (configuration methods)");
resultSummary(suite, testContext.getFailedTests(), testName,
"failed", "");
resultSummary(suite, testContext.getSkippedConfigurations(),
testName, "skipped", " (configuration methods)");
resultSummary(suite, testContext.getSkippedTests(), testName,
"skipped", "");
resultSummary(suite, testContext.getPassedTests(), testName,
"passed", "");
testIndex++;
}
}
m_out.println("</table>");
}
/** Creates a section showing known results for each method */
protected void generateMethodDetailReport(List<ISuite> suites) {
m_methodIndex = 0;
for (ISuite suite : suites) {
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
if (r.values().size() > 0) {
m_out.println("<h1>" + testContext.getName() + "</h1>");
}
resultDetail(testContext.getFailedConfigurations());
resultDetail(testContext.getFailedTests());
resultDetail(testContext.getSkippedConfigurations());
resultDetail(testContext.getSkippedTests());
resultDetail(testContext.getPassedTests());
}
}
}
/**
* #param tests
*/
private void resultSummary(ISuite suite, IResultMap tests, String testname,
String style, String details) {
if (tests.getAllResults().size() > 0) {
StringBuffer buff = new StringBuffer();
String lastClassName = "";
int mq = 0;
int cq = 0;
for (ITestNGMethod method : getMethodSet(tests, suite)) {
m_row += 1;
m_methodIndex += 1;
ITestClass testClass = method.getTestClass();
String className = testClass.getName();
if (mq == 0) {
String id = (m_testIndex == null ? null : "t"
+ Integer.toString(m_testIndex));
titleRow(testname + " — " + style + details, 5, id);
m_testIndex = null;
}
if (!className.equalsIgnoreCase(lastClassName)) {
if (mq > 0) {
cq += 1;
m_out.print("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">"
+ "<td");
if (mq > 1) {
m_out.print(" rowspan=\"" + mq + "\"");
}
m_out.println(">" + lastClassName + "</td>" + buff);
}
mq = 0;
buff.setLength(0);
lastClassName = className;
}
Set<ITestResult> resultSet = tests.getResults(method);
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
for (ITestResult testResult : tests.getResults(method)) {
if (testResult.getEndMillis() > end) {
end = testResult.getEndMillis();
}
if (testResult.getStartMillis() < start) {
start = testResult.getStartMillis();
}
}
mq += 1;
if (mq > 1) {
buff.append("<tr class=\"" + style
+ (cq % 2 == 0 ? "odd" : "even") + "\">");
}
String description = method.getDescription();
String testInstanceName = resultSet
.toArray(new ITestResult[] {})[0].getTestName();
buff.append("<td><a href=\"#m"
+ m_methodIndex
+ "\">"
+ qualifiedName(method)
+ " "
+ (description != null && description.length() > 0 ? "(\""
+ description + "\")"
: "")
+ "</a>"
+ (null == testInstanceName ? "" : "<br>("
+ testInstanceName + ")") + "</td>"
+ "<td class=\"numi\">" + resultSet.size() + "</td>"
+ "<td>" + start + "</td>" + "<td class=\"numi\">"
+ (end - start) + "</td>" + "</tr>");
}
if (mq > 0) {
cq += 1;
m_out.print("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");
if (mq > 1) {
m_out.print(" rowspan=\"" + mq + "\"");
}
m_out.println(">" + lastClassName + "</td>" + buff);
}
}
}
/** Starts and defines columns result summary table */
private void startResultSummaryTable(String style) {
tableStart(style, "summary");
m_out.println("<tr><th>Class</th>"
+ "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");
m_row = 0;
}
private String qualifiedName(ITestNGMethod method) {
StringBuilder addon = new StringBuilder();
String[] groups = method.getGroups();
int length = groups.length;
if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {
addon.append("(");
for (int i = 0; i < length; i++) {
if (i > 0) {
addon.append(", ");
}
addon.append(groups[i]);
}
addon.append(")");
}
return "<b>" + method.getMethodName() + "</b> " + addon;
}
private void resultDetail(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
ITestNGMethod method = result.getMethod();
m_methodIndex++;
String cname = method.getTestClass().getName();
m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"
+ method.getMethodName() + "</h2>");
Set<ITestResult> resultSet = tests.getResults(method);
generateForResult(result, method, resultSet.size());
m_out.println("<p class=\"totop\">back to summary</p>");
}
}
/**
* Write the first line of the stack trace
*
* #param tests
*/
private void getShortException(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
m_methodIndex++;
Throwable exception = result.getThrowable();
List<String> msgs = Reporter.getOutput(result);
boolean hasReporterOutput = msgs.size() > 0;
boolean hasThrowable = exception != null;
if (hasThrowable) {
boolean wantsMinimalOutput = result.getStatus() == ITestResult.SUCCESS;
if (hasReporterOutput) {
m_out.print("<h3>"
+ (wantsMinimalOutput ? "Expected Exception"
: "Failure") + "</h3>");
}
// Getting first line of the stack trace
String str = Utils.stackTrace(exception, true)[0];
scanner = new Scanner(str);
String firstLine = scanner.nextLine();
m_out.println(firstLine);
}
}
}
/**
* Write all parameters
*
* #param tests
*/
private void getParameters(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
m_methodIndex++;
Object[] parameters = result.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
for (Object p : parameters) {
m_out.println(Utils.escapeHtml(Utils.toString(p)) + " | ");
}
}
}
}
private void generateForResult(ITestResult ans, ITestNGMethod method,
int resultSetSize) {
Object[] parameters = ans.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
tableStart("result", null);
m_out.print("<tr class=\"param\">");
for (int x = 1; x <= parameters.length; x++) {
m_out.print("<th>Param." + x + "</th>");
}
m_out.println("</tr>");
m_out.print("<tr class=\"param stripe\">");
for (Object p : parameters) {
m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p))
+ "</td>");
}
m_out.println("</tr>");
}
List<String> msgs = Reporter.getOutput(ans);
boolean hasReporterOutput = msgs.size() > 0;
Throwable exception = ans.getThrowable();
boolean hasThrowable = exception != null;
if (hasReporterOutput || hasThrowable) {
if (hasParameters) {
m_out.print("<tr><td");
if (parameters.length > 1) {
m_out.print(" colspan=\"" + parameters.length + "\"");
}
m_out.println(">");
} else {
m_out.println("<div>");
}
if (hasReporterOutput) {
if (hasThrowable) {
m_out.println("<h3>Test Messages</h3>");
}
for (String line : msgs) {
m_out.println(line + "<br/>");
}
}
if (hasThrowable) {
boolean wantsMinimalOutput = ans.getStatus() == ITestResult.SUCCESS;
if (hasReporterOutput) {
m_out.println("<h3>"
+ (wantsMinimalOutput ? "Expected Exception"
: "Failure") + "</h3>");
}
generateExceptionReport(exception, method);
}
if (hasParameters) {
m_out.println("</td></tr>");
} else {
m_out.println("</div>");
}
}
if (hasParameters) {
m_out.println("</table>");
}
}
protected void generateExceptionReport(Throwable exception,
ITestNGMethod method) {
m_out.print("<div class=\"stacktrace\">");
m_out.print(Utils.stackTrace(exception, true)[0]);
m_out.println("</div>");
}
/**
* Since the methods will be sorted chronologically, we want to return the
* ITestNGMethod from the invoked methods.
*/
private Collection<ITestNGMethod> getMethodSet(IResultMap tests,
ISuite suite) {
List<IInvokedMethod> r = Lists.newArrayList();
List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();
for (IInvokedMethod im : invokedMethods) {
if (tests.getAllMethods().contains(im.getTestMethod())) {
r.add(im);
}
}
Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());
List<ITestNGMethod> result = Lists.newArrayList();
// Add all the invoked methods
for (IInvokedMethod m : r) {
result.add(m.getTestMethod());
}
// Add all the methods that weren't invoked (e.g. skipped) that we
// haven't added yet
for (ITestNGMethod m : tests.getAllMethods()) {
if (!result.contains(m)) {
result.add(m);
}
}
return result;
}
#SuppressWarnings("unused")
public void generateSuiteSummaryReport(List<ISuite> suites) {
tableStart("testOverview", null);
m_out.print("<tr>");
tableColumnStart("Test");
tableColumnStart("Methods<br/>Passed");
tableColumnStart("Scenarios<br/>Passed");
tableColumnStart("# skipped");
tableColumnStart("# failed");
tableColumnStart("Error messages");
tableColumnStart("Parameters");
tableColumnStart("Start<br/>Time");
tableColumnStart("End<br/>Time");
tableColumnStart("Total<br/>Time");
tableColumnStart("Included<br/>Groups");
tableColumnStart("Excluded<br/>Groups");
m_out.println("</tr>");
NumberFormat formatter = new DecimalFormat("#,##0.0");
int qty_tests = 0;
int qty_pass_m = 0;
int qty_pass_s = 0;
int qty_skip = 0;
int qty_fail = 0;
long time_start = Long.MAX_VALUE;
long time_end = Long.MIN_VALUE;
m_testIndex = 1;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 8);
}
Map<String, ISuiteResult> tests = suite.getResults();
for (ISuiteResult r : tests.values()) {
qty_tests += 1;
ITestContext overview = r.getTestContext();
startSummaryRow(overview.getName());
int q = getMethodSet(overview.getPassedTests(), suite).size();
qty_pass_m += q;
summaryCell(q, Integer.MAX_VALUE);
q = overview.getPassedTests().size();
qty_pass_s += q;
summaryCell(q, Integer.MAX_VALUE);
q = getMethodSet(overview.getSkippedTests(), suite).size();
qty_skip += q;
summaryCell(q, 0);
q = getMethodSet(overview.getFailedTests(), suite).size();
qty_fail += q;
summaryCell(q, 0);
// NEW
// Insert error found
m_out.print("<td class=\"numi" + (true ? "" : "_attn") + "\">");
getShortException(overview.getFailedTests());
getShortException(overview.getSkippedTests());
m_out.println("</td>");
// NEW
// Add parameters for each test case (failed or passed)
m_out.print("<td class=\"numi" + (true ? "" : "_attn") + "\">");
// Write OS and Browser
// m_out.println(suite.getParameter("os").substring(0, 3) +
// " | "
// + suite.getParameter("browser").substring(0, 3) + " | ");
getParameters(overview.getFailedTests());
getParameters(overview.getPassedTests());
getParameters(overview.getSkippedTests());
m_out.println("</td>");
// NEW
summaryCell(
DateFunctions.dateToDayAndTime(overview.getStartDate()),
true);
m_out.println("</td>");
summaryCell(
DateFunctions.dateToDayAndTime(overview.getEndDate()),
true);
m_out.println("</td>");
time_start = Math.min(overview.getStartDate().getTime(),
time_start);
time_end = Math.max(overview.getEndDate().getTime(), time_end);
summaryCell(
formatter.format((overview.getEndDate().getTime() - overview
.getStartDate().getTime()) / 1000.)
+ " seconds", true);
summaryCell(overview.getIncludedGroups());
summaryCell(overview.getExcludedGroups());
m_out.println("</tr>");
m_testIndex++;
}
}
if (qty_tests > 1) {
m_out.println("<tr class=\"total\"><td>Total</td>");
summaryCell(qty_pass_m, Integer.MAX_VALUE);
summaryCell(qty_pass_s, Integer.MAX_VALUE);
summaryCell(qty_skip, 0);
summaryCell(qty_fail, 0);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(
formatter.format(((time_end - time_start) / 1000.) / 60.)
+ " minutes", true);
m_out.println("<td colspan=\"3\"> </td></tr>");
}
m_out.println("</table>");
}
private void summaryCell(String[] val) {
StringBuffer b = new StringBuffer();
for (String v : val) {
b.append(v + " ");
}
summaryCell(b.toString(), true);
}
private void summaryCell(String v, boolean isgood) {
m_out.print("<td class=\"numi" + (isgood ? "" : "_attn") + "\">" + v
+ "</td>");
}
private void startSummaryRow(String label) {
m_row += 1;
m_out.print("<tr"
+ (m_row % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t"
+ m_testIndex + "\">" + label + "</a>" + "</td>");
}
private void summaryCell(int v, int maxexpected) {
summaryCell(String.valueOf(v), v <= maxexpected);
}
private void tableStart(String cssclass, String id) {
m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""
+ (cssclass != null ? " class=\"" + cssclass + "\""
: " style=\"padding-bottom:2em\"")
+ (id != null ? " id=\"" + id + "\"" : "") + ">");
m_row = 0;
}
private void tableColumnStart(String label) {
m_out.print("<th>" + label + "</th>");
}
private void titleRow(String label, int cq) {
titleRow(label, cq, null);
}
private void titleRow(String label, int cq, String id) {
m_out.print("<tr");
if (id != null) {
m_out.print(" id=\"" + id + "\"");
}
m_out.println("><th colspan=\"" + cq + "\">" + label + "</th></tr>");
m_row = 0;
}
/** Starts HTML stream */
protected void startHtml(PrintWriter out) {
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>Hector Flores - TestNG Report</title>");
out.println("<style type=\"text/css\">");
out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");
out.println("td,th {border:1px solid #009;padding:.25em .5em}");
out.println(".result th {vertical-align:bottom}");
out.println(".param th {padding-left:1em;padding-right:1em}");
out.println(".param td {padding-left:.5em;padding-right:2em}");
out.println(".stripe td,.stripe th {background-color: #E6EBF9}");
out.println(".numi,.numi_attn {text-align:right}");
out.println(".total td {font-weight:bold}");
out.println(".passedodd td {background-color: #0A0}");
out.println(".passedeven td {background-color: #3F3}");
out.println(".skippedodd td {background-color: #CCC}");
out.println(".skippedodd td {background-color: #DDD}");
out.println(".failedodd td,.numi_attn {background-color: #F33}");
out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");
out.println(".stacktrace {white-space:pre;font-family:monospace}");
out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
}
/** Finishes HTML stream */
protected void endHtml(PrintWriter out) {
out.println("<center> Report customized by Hector Flores [hectorfb#gmail.com] </center>");
out.println("</body></html>");
}
// ~ Inner Classes --------------------------------------------------------
/** Arranges methods by classname and method name */
private class TestSorter implements Comparator<IInvokedMethod> {
// ~ Methods
// -------------------------------------------------------------
/** Arranges methods by classname and method name */
#Override
public int compare(IInvokedMethod o1, IInvokedMethod o2) {
// System.out.println("Comparing " + o1.getMethodName() + " " +
// o1.getDate()
// + " and " + o2.getMethodName() + " " + o2.getDate());
return (int) (o1.getDate() - o2.getDate());
// int r = ((T) o1).getTestClass().getName().compareTo(((T)
// o2).getTestClass().getName());
// if (r == 0) {
// r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());
// }
// return r;
}
}
}
With those steps you already have your listener ready to listen.
How to call it?
If you use testng.xml add the following lines:
<listeners>
<listener class-name='[your_class_path].MyReporterListener'/>
</listeners>
If you run your tests from a java class, add the following lines:
private final static MyReporterListener frl = new MyReporterListener();
TestNG testng = new TestNG();
testng.addListener(frl);
With those steps, when you execute your tests you'll have two emailable reports, customized and original.
Now it's time to pimp your report.
In my case I had to add error messages, parameters and times (start and end), because it's very useful if you want to paste on an excel file.
My customized report:
You have to mainly modify generateSuiteSummaryReport(List suites) function.
Play with that and ask me if you have any problem.
Make a you CSS and embed it in EmailableReporter.class. This class file can be found in TestNG folder> org.testNg.reporters> EmailableReporter.class.
There you can edit the Style of the TestNG report HTML file which starts with
protected void startHtml(PrintWriter out)
Better you can use extent report html reporting library jar file. However i am using extentreport1.4.jar jar file. So you will get summary details at right corner of your report
Using the above code, I am facing the below null pointer issue, HTML report works fine when fewer tests are included in testng.xml, but when I include more tests, the HTML report does not get generated and the below exception is thrown
[TestNG] Reporter report.MyListener#60e07aed failed
java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null
at java.base/java.io.StringReader.<init>(StringReader.java:51)
at java.base/java.util.Scanner.<init>(Scanner.java:766)
at report.MyListener.getShortException(MyListener.java:294)
at report.MyListener.generateSuiteSummaryReport(MyListener.java:473)
at report.MyListener.generateReport(MyListener.java:72)
at org.testng.TestNG.generateReports(TestNG.java:1093)
at org.testng.TestNG.run(TestNG.java:1036)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
To fix the above added a null check to avoid Null Pointer at line 295
if(str!=null) {
scanner = new Scanner(str);
String firstLine = scanner.nextLine()+"<br>";
m_out.println(firstLine);
}

Actively read 150 x 150 pixels from a camera preview

I have set up an Android camera application that allows me to preview the camera in a Frame Layout within my main Activity. What I would like to do (without using camera specific functionality; I want this to be completely independent of hardware.) is out line 150 X 150 pixels in the center of the preview either by showing a box around the pixels or blurring all of the pixels except the 150 x 150. Additionally, without taking a picture, I would like to read these pixels. Ultimately the effect I am going for is, as the camera is moved I display the change in the red, green, and blue color concentrations within the 150 x 150 area. I know how to do the nested for loop and get the color from the pixel, but I would need to know how to get the offset for the height and weight to start reading the pixels from.
Thanks in advance for all of your help!
Mike
public class MyActivity extends Activity {
final public String TAG = "MyActivity";
static private Camera mCamera = null;
static public Camera getCamera() { return mCamera; }
private static boolean mBPreviewingCamera = false;
private PreviewSurface mPS;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String lMTH = "onCreate ";
Log.i(TAG, lMTH + "Start");
setContentView(R.layout.activity_color_temperature_estimator);
if (isThereACamera()) {
mPreviewCamera(true);
TextView lTVTemp = (TextView) findViewById(R.id.TV_TEMP);
lTVTemp.setText("Camera exists able to proceed");
lTVTemp = null;
} else {
Toast.makeText(this, "No camera! Uunable to proceed", Toast.LENGTH_LONG).show();
TextView lTVTemp = (TextView) findViewById(R.id.TV_TEMP);
lTVTemp.setText("No camera! Uunable to proceed");
lTVTemp = null;
}
}
public void mPreviewCamera(boolean pBPreviewingCamera) {
String lMTH = "mPreviewCamera ";
try {
if (pBPreviewingCamera) {
Log.i(TAG, lMTH + "Open Camera");
mCamera = Camera.open();
mPS = new PreviewSurface(this);
FrameLayout lFVPreview = (FrameLayout) findViewById(R.id.FL_Preview);
lFVPreview.addView(mPS);
lFVPreview = null;
mBPreviewingCamera = true;
Button lBTNTemp = (Button) findViewById(R.id.BTN_CLOSE);
lBTNTemp.setText(R.string.BTN_CLOSE);
lBTNTemp = null;
} else {
Log.i(TAG, lMTH + "Open Camera");
mCloseCamera();
Button lBTNTemp = (Button) findViewById(R.id.BTN_CLOSE);
lBTNTemp.setText(R.string.BTN_OPEN);
lBTNTemp = null;
}
} catch (Exception e) {
Log.i(TAG, lMTH + e.getMessage());
mCloseCamera();
e.printStackTrace();
}
}
public void mCloseCamera() {
String lMTH = "mCloseCamera ";
Log.i(TAG, lMTH + "Turn Camera Off");
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
mCamera = null;
mBPreviewingCamera = false;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
String lMTH = "onPause ";
Log.i(TAG, lMTH + "Turn Camera Off");
mPreviewCamera(false);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
String lMTH = "onDestroy ";
Log.i(TAG, lMTH + "Turn Camera Off");
mPreviewCamera(false);
}
/** Check if this phone has a camera */
private boolean isThereACamera() {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// There is a camera
return true;
} else {
// There isn't a camera
return false;
}
}
public void mBTN(View view) {
mPreviewCamera(!mBPreviewingCamera);
}
}
public class PreviewSurface extends SurfaceView implements SurfaceHolder.Callback {
final static public String TAG = "PreviewSurface";
private SurfaceHolder mSH;
/**
* #param context
*/
public PreviewSurface(Context pContext) {
super(pContext);
// TODO Auto-generated constructor stub
String lMTH = "PreviewSurface(Context pContext) ";
Log.i(TAG, lMTH + "Constructor");
pContext = null;
mSH = getHolder();
mSH.addCallback(this);
mSH.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder, int, int, int)
*/
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
String lMTH = "surfaceChanged ";
// TODO Auto-generated method stub
Log.i(TAG, lMTH + "arg1 = " + arg1 + " arg2 " + arg2 + " arg3 " + arg3);
if (arg0.getSurface() != null) {
// stop old preview if it exists
try {
Log.i(TAG, lMTH + "Stop Preview ");
MyActivity.getCamera().stopPreview();
} catch (Exception e) {
Log.i(TAG, lMTH + "Stoping preview exception " + e.getMessage());
}
// start new preview
try {
Log.i(TAG, lMTH + "Set Preview ");
MyActivity.getCamera().setPreviewDisplay(arg0);
Log.i(TAG, lMTH + "Start Preview ");
MyActivity.getCamera().startPreview();
} catch (Exception e){
Log.i(TAG, lMTH + "Starting camera preview exception " + e.getMessage());
}
}
// stop preview before making changes
}
/* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder)
*/
public void surfaceCreated(SurfaceHolder arg0) {
String lMTH = "surfaceCreated ";
// TODO Auto-generated method stub
try {
Log.i(TAG, lMTH + "Set Preview ");
MyActivity.getCamera().setPreviewDisplay(arg0);
Log.i(TAG, lMTH + "Start Preview ");
MyActivity.getCamera().startPreview();
} catch (Exception e) {
Log.i(TAG, lMTH + "Exception " + e.getMessage());
e.printStackTrace();
}
}
/* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder)
*/
public void surfaceDestroyed(SurfaceHolder arg0) {
String lMTH = "surfaceDestroyed ";
// TODO Auto-generated method stub
Log.i(TAG, lMTH + "Activity will handle destroy");
}
"I would need to know how to get the offset for the height and weight
to start reading the pixels from"
An easy way to get the offset for your nested for-loop is walked through with descriptive variables:
int xWidth = 150; // The length you want to concentrate on
int yHeight = 150;
int xCenter = previewWidth/2;
int yCenter = previewHeight/2;
int xStart = xCenter - xWidth/2;
int xEnd = xCenter + xWidth/2;
int yStart = yCenter - yHeight/2;
int yEnd = yCenter + yHeight/2;
for(int y = yStart; y < yEnd; y++) {
for(int x = xStart; x < xEnd; x++) {
// read pixels
}
}
The previewWidth and previewHeight can be easily gotten from surfaceChange():
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
previewWidth = w;
previewHeight = h;
...
}
The reason I use many variables here is so that you can clearly see how I walked through this problem.
Let me know how it goes.

SMPP error code 61,62

I am using the jsmpp lib for sending sms. The SMSC center returns negative response like 61,62 which are Invalid scheduled delivery time and Invalid Validty Period value. After talking with SMSC support, they require to set a default timeout for the message to be delivered, after some search on jsmpp site, didn't find it. Thanks for any suggestions ?
According to SMPP standard it should be possible to leave both of these null, but if Validity Period is required, this can be either an absolute date or a relative one.
The format should be YYMMDDhhmmsstnnp, where
YY is a two digit year (00-99)
MM is month (01-12)
DD is day (01-31)
hh is hours (00-23)
mm is minutes (00-59)
ss is seconds (00-59)
t is tenths of second (00-59)
nn is the time difference in quarter hours between local time and UTC (00-48)
p can be one of the following :-
'+' local time is ahead of UTC.
'-' local time is behind UTC.
'R' This is a relative time.
So to make the validity period 1 hour using a relative time use the following: "000000010000000R"
In my project I didn't have business requirement to schedule delivery time and set validity Period, so I set them null and it's work fine :-)
I use this class to load smpp config from properties file. Code that will using it will looks more readable and simple :-)
SMPPConfigManager is an interface for this class. It's possible to read this config not only from properties file. For example from Db and you can then implement this interface in new class.
package ru.rodin.denis.smpp;
import java.util.Properties;
import org.jsmpp.bean.*;
/**
*
* #author Denis Rodin
*/
public class SMPPFileConfig implements SMPPConfigManager {
private String host;
private int port;
private String systemId;
private String password;
private String systemType;
private TypeOfNumber sourceAddrTon;
private TypeOfNumber destAddrTon;
private NumberingPlanIndicator sourceAddrNpi;
private NumberingPlanIndicator destAddrNpi;
private String addressRange;
private int connectTimeout;
private long reconnectInterval;
private String sourceAddr;
private String destinationAddr;
private SMSCDeliveryReceipt deliveryReceipt;
private RegisteredDelivery registeredDelivery;
private BindType bindType;
private ESMClass esmClass;
private byte protocolId;
private byte priorityFlag;
private String scheduleDeliveryTime;
private String validityPeriod;
private byte replaceIfPresentFlag;
private GeneralDataCoding generalDataCoding;
private boolean generalDataCoding_compressed = true;
private boolean generalDataCoding_containMessageClass = true;
private MessageClass generalDataCoding_messageClass = MessageClass.CLASS1;
private Alphabet generalDataCoding_alphabet = Alphabet.ALPHA_DEFAULT;
private byte smDefaultMsgId;
private long transactionTimer;
private int enquireLinkTimer;
public SMPPFileConfig(Properties prop) {
this.host = prop.getProperty("smpp.host");
this.port = Integer.parseInt(prop.getProperty("smpp.port"));
this.systemId = prop.getProperty("smpp.systemId");
this.password = prop.getProperty("smpp.password");
this.systemType = prop.getProperty("smpp.systemType");
this.sourceAddrTon = getTypeOfNumber(SMPPConfigManager.AddrTon.SOURCE, prop);
this.destAddrTon = getTypeOfNumber(SMPPConfigManager.AddrTon.DEST, prop);
this.sourceAddrNpi = getNumberingPlanIndicator(SMPPConfigManager.AddrNpi.SOURCE, prop);
this.destAddrNpi = getNumberingPlanIndicator(SMPPConfigManager.AddrNpi.DEST, prop);
this.addressRange = prop.getProperty("smpp.addressRange");
this.connectTimeout = Integer.parseInt(prop.getProperty("smpp.connect.timeout"));
this.reconnectInterval = Long.parseLong(prop.getProperty("smpp.reconnect.interval"));
this.sourceAddr = prop.getProperty("smpp.sourceAddr");
this.destinationAddr = null;
this.deliveryReceipt = getSMSCDeliveryReceipt(prop.getProperty("smpp.SMSC.delivery.receipt"));
this.registeredDelivery = new RegisteredDelivery(deliveryReceipt);
this.bindType = getBindTypeFromProp(prop.getProperty("smpp.bindType"));
this.esmClass = createESMClass(prop.getProperty("smpp.ESMClass.MessageMode"), prop.getProperty("smpp.ESMClass.MessageType"), prop.getProperty("smpp.ESMClass.GSMSpecificFeature"));
this.protocolId = new Byte(prop.getProperty("smpp.protocolId"));
this.priorityFlag = new Byte(prop.getProperty("smpp.priorityFlag"));
this.scheduleDeliveryTime = prop.getProperty("smpp.scheduleDeliveryTime");
this.validityPeriod = prop.getProperty("smpp.validityPeriod");
this.replaceIfPresentFlag = new Byte(prop.getProperty("smpp.replaceIfPresentFlag"));
this.generalDataCoding = new GeneralDataCoding(generalDataCoding_compressed, generalDataCoding_containMessageClass, generalDataCoding_messageClass, generalDataCoding_alphabet);
this.smDefaultMsgId = new Byte(prop.getProperty("smpp.smDefaultMsgId"));
this.transactionTimer = Long.parseLong(prop.getProperty("smpp.transactionTimer"));
this.enquireLinkTimer = Integer.parseInt(prop.getProperty("smpp.enquireLinkTimer"));
}
#Override
public String toString() {
return "SMPPFileConfig{" + "host=" + host + ", port=" + port + ", systemId=" + systemId + ", password=" + password + ", systemType=" + systemType + ", sourceAddrTon=" + sourceAddrTon + ", destAddrTon=" + destAddrTon + ", sourceAddrNpi=" + sourceAddrNpi + ", destAddrNpi=" + destAddrNpi + ", addressRange=" + addressRange + ", connectTimeout=" + connectTimeout + ", reconnectInterval=" + reconnectInterval + ", sourceAddr=" + sourceAddr + ", destinationAddr=" + destinationAddr + ", deliveryReceipt=" + deliveryReceipt + ", registeredDelivery=" + registeredDelivery + ", bindType=" + bindType + ", esmClass=" + esmClass + ", protocolId=" + protocolId + ", priorityFlag=" + priorityFlag + ", scheduleDeliveryTime=" + scheduleDeliveryTime + ", validityPeriod=" + validityPeriod + ", replaceIfPresentFlag=" + replaceIfPresentFlag + ", generalDataCoding=" + generalDataCoding + ", generalDataCoding_compressed=" + generalDataCoding_compressed + ", generalDataCoding_containMessageClass=" + generalDataCoding_containMessageClass + ", generalDataCoding_messageClass=" + generalDataCoding_messageClass + ", generalDataCoding_alphabet=" + generalDataCoding_alphabet + ", smDefaultMsgId=" + smDefaultMsgId + '}';
}
#Override
public String getAddressRange() {
return addressRange;
}
#Override
public int getConnectTimeout() {
return connectTimeout;
}
#Override
public SMSCDeliveryReceipt getDeliveryReceipt() {
return deliveryReceipt;
}
#Override
public RegisteredDelivery getRegisteredDelivery() {
return registeredDelivery;
}
#Override
public NumberingPlanIndicator getDestAddrNpi() {
return destAddrNpi;
}
#Override
public TypeOfNumber getDestAddrTon() {
return destAddrTon;
}
#Override
public void setDestinationAddr(String destinationAddr) {
this.destinationAddr = destinationAddr;
}
#Override
public String getDestinationAddr() {
return destinationAddr;
}
#Override
public String getHost() {
return host;
}
#Override
public String getPassword() {
return password;
}
#Override
public int getPort() {
return port;
}
#Override
public long getReconnectInterval() {
return reconnectInterval;
}
#Override
public String getSourceAddr() {
return sourceAddr;
}
#Override
public NumberingPlanIndicator getSourceAddrNpi() {
return sourceAddrNpi;
}
#Override
public TypeOfNumber getSourceAddrTon() {
return sourceAddrTon;
}
#Override
public String getSystemId() {
return systemId;
}
#Override
public String getSystemType() {
return systemType;
}
#Override
public BindType getBindType() {
return bindType;
}
#Override
public ESMClass getESMClass() {
return esmClass;
}
#Override
public void setESMClass(ESMClass esmClass) {
this.esmClass = esmClass;
}
#Override
public byte getProtocolId() {
return protocolId;
}
#Override
public byte getPriorityFlag() {
return priorityFlag;
}
#Override
public String getScheduleDeliveryTime() {
return scheduleDeliveryTime;
}
#Override
public String getValidityPeriod() {
return validityPeriod;
}
#Override
public byte getReplaceIfPresentFlag() {
return replaceIfPresentFlag;
}
#Override
public GeneralDataCoding getGeneralDataCoding() {
return generalDataCoding;
}
#Override
public byte getsmDefaultMsgId(){
return smDefaultMsgId;
}
#Override
public long getTransactionTimer()
{
return transactionTimer;
}
#Override
public int getEnquireLinkTimer()
{
return enquireLinkTimer;
}
private ESMClass createESMClass(String messageMode, String messageType, String GSMSpecificFeature) {
return new ESMClass(getESMClassMessageMode(messageMode), getESMMessageType(messageType), getESMGSMSpecificFeature(GSMSpecificFeature));
}
private MessageMode getESMClassMessageMode(String type) {
if (type.equals("DEFAULT")) {
return MessageMode.DEFAULT;
} else if (type.equals("DATAGRAM")) {
return MessageMode.DATAGRAM;
} else if (type.equals("STORE_AND_FORWARD")) {
return MessageMode.STORE_AND_FORWARD;
} else if (type.equals("TRANSACTION")) {
return MessageMode.TRANSACTION;
} else {
return null;
}
}
private MessageType getESMMessageType(String type) {
if (type.equals("DEFAULT")) {
return MessageType.DEFAULT;
} else if (type.equals("CONV_ABORT")) {
return MessageType.CONV_ABORT;
} else if (type.equals("ESME_DEL_ACK")) {
return MessageType.ESME_DEL_ACK;
} else if (type.equals("ESME_MAN_ACK")) {
return MessageType.ESME_MAN_ACK;
} else if (type.equals("INTER_DEL_NOTIF")) {
return MessageType.INTER_DEL_NOTIF;
} else if (type.equals("SME_DEL_ACK")) {
return MessageType.SME_DEL_ACK;
} else if (type.equals("SME_MAN_ACK")) {
return MessageType.SME_MAN_ACK;
} else if (type.equals("SMSC_DEL_RECEIPT")) {
return MessageType.SMSC_DEL_RECEIPT;
} else {
return null;
}
}
private GSMSpecificFeature getESMGSMSpecificFeature(String type) {
if (type.equals("DEFAULT")) {
return GSMSpecificFeature.DEFAULT;
} else if (type.equals("REPLYPATH")) {
return GSMSpecificFeature.REPLYPATH;
} else if (type.equals("UDHI")) {
return GSMSpecificFeature.UDHI;
} else if (type.equals("UDHI_REPLYPATH")) {
return GSMSpecificFeature.UDHI_REPLYPATH;
} else {
return null;
}
}
private BindType getBindTypeFromProp(String type) {
//String type = prop.getProperty("smpp.bindType");
if (type.equals("BIND_RX")) {
return BindType.BIND_RX;
} else if (type.equals("BIND_TX")) {
return BindType.BIND_TX;
} else if (type.equals("BIND_TRX")) {
return BindType.BIND_TRX;
} else {
return null;
}
}
private TypeOfNumber getTypeOfNumber(SMPPConfigManager.AddrTon ton, Properties prop) {
String type;
if (ton == SMPPConfigManager.AddrTon.SOURCE) {
type = prop.getProperty("smpp.sourceAddrTon");
} else {
type = prop.getProperty("smpp.destAddrTon");
}
if (type.equals("ABBREVIATED")) {
return TypeOfNumber.ABBREVIATED;
} else if (type.equals("ALPHANUMERIC")) {
return TypeOfNumber.ALPHANUMERIC;
} else if (type.equals("INTERNATIONAL")) {
return TypeOfNumber.INTERNATIONAL;
} else if (type.equals("NATIONAL")) {
return TypeOfNumber.NATIONAL;
} else if (type.equals("NETWORK_SPECIFIC")) {
return TypeOfNumber.NETWORK_SPECIFIC;
} else if (type.equals("SUBSCRIBER_NUMBER")) {
return TypeOfNumber.SUBSCRIBER_NUMBER;
} else if (type.equals("UNKNOWN")) {
return TypeOfNumber.UNKNOWN;
} else {
return null;
}
}
private SMSCDeliveryReceipt getSMSCDeliveryReceipt(String type) {
//String type = prop.getProperty("smpp.SMSC.delivery.receipt");
if (type.equals("DEFAULT")) {
return SMSCDeliveryReceipt.DEFAULT;
} else if (type.equals("SUCCESS")) {
return SMSCDeliveryReceipt.SUCCESS;
} else if (type.equals("SUCCESS_FAILURE")) {
return SMSCDeliveryReceipt.SUCCESS_FAILURE;
} else {
return null;
}
}
private NumberingPlanIndicator getNumberingPlanIndicator(SMPPConfigManager.AddrNpi npi, Properties prop) {
String type;
if (npi == SMPPConfigManager.AddrNpi.SOURCE) {
type = prop.getProperty("smpp.sourceAddrNpi");
} else {
type = prop.getProperty("smpp.destAddrNpi");
}
if (type.equals("DATA")) {
return NumberingPlanIndicator.DATA;
} else if (type.equals("ERMES")) {
return NumberingPlanIndicator.ERMES;
} else if (type.equals("INTERNET")) {
return NumberingPlanIndicator.INTERNET;
} else if (type.equals("ISDN")) {
return NumberingPlanIndicator.ISDN;
} else if (type.equals("LAND_MOBILE")) {
return NumberingPlanIndicator.LAND_MOBILE;
} else if (type.equals("NATIONAL")) {
return NumberingPlanIndicator.NATIONAL;
} else if (type.equals("PRIVATE")) {
return NumberingPlanIndicator.PRIVATE;
} else if (type.equals("TELEX")) {
return NumberingPlanIndicator.TELEX;
} else if (type.equals("WAP")) {
return NumberingPlanIndicator.WAP;
} else if (type.equals("UNKNOWN")) {
return NumberingPlanIndicator.UNKNOWN;
} else {
return null;
}
}
}
when you submit current time as scheduled delivery time this error may occur.because it takes some time to send request. so the time you mentioned might be in past .so set the scheduled delivery time to (current time + 10 seconds )
long TEN_SECONDS=10000;//millisecs
Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date scheduleDeliveryTime=new Date(t + ( TEN_SECONDS));