[Q] Android Maps draw path problem - Android Q&A, Help & Troubleshooting

I am developing an application which draws the path of the user as he moves and calculates the area .
This is the code i am trying my problem is at the start of recording the path the path is drawn even if the user has not moved and sometimes when even if user is moving the path is not drawn .
RouteOverlay class:
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
MainActivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}

This probably has to do with the accuracy of the GPS. I didn't really look at your code but maybe you should add some kind of buffer. if (movement>5m){//draw stuff}

Related

Android - SurfaceView flickers and sometimes does not apply the proper paint

I have been experiencing this issue for quite a while and even after googling a while, I havent found a reasonable solution for my problem.
The issue I am experiencing is that the SurfaceView I am using flickers. Once in a while, the objects I draw flicker and they change their size or colour.
It looks like that sometimes the application skips my calls to 'Paint.setColor()' and the one to 'Paint.setStrokeWidth()'.
I have made methods which change the used paint and then, in order to try to fix this issue, to set it back to the default paint values. Still the issue persists. I have also read that the problem might be due to the double buffering. Is it the case? I am using this code for the DrawingThread:
PS. u can notice that I also tried to use a dirty Rectangle to try to see if the issue can be fixed, but still nothing. [I might not have understood what it actually does.
Code:
class DrawingThread extends Thread {
private SurfaceHolder _surfaceHolder;
private CustomView _cv;
private boolean _run = false;
public DrawingThread(SurfaceHolder surfaceHolder, CustomView cv) {
super();
_surfaceHolder = surfaceHolder;
_cv = cv;
}
public void setRunning(boolean run) {
_run = run;
}
public boolean isRunning() {
return _run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
@Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
//c = _surfaceHolder.lockCanvas(new Rect(lon - range, lon + range, lat - range, lat + range));
c = _surfaceHolder.lockCanvas();
synchronized (_surfaceHolder) {
_cv.onDraw(c);
}
} finally {
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
PS. I have read somewhere I should draw on a single bitmap and then draw the bitmap on the canvas. I have tried several times but I cannot manage to do so.
Thanks in advance,
N.
Is there anyone who can help me?
Could someone give me a hand?
I cannot find the reason why I cannot fix this issue.
I have tried to draw the items on a bitmap first and then adding it to the canvas, but I didnt manage and I either get a white canvas or a completely black one.
I believe the issue is quite easy to solve after you do it once.
Not even someone who could give some suggestions?
Hey!
As far as I can see the code you posted looks fine. Can you please post the code of your CustomView class? I think there could be an issue there.
Are you trying to make a game?
Hello!!!!
Finally someone
Here is the code I use for the onDraw(canvas):
Code:
@Override
public void onDraw(Canvas canvas) {
try {
canvas.drawColor(Color.WHITE);
pt.setAntiAlias(true);
canvas.rotate(-90, 0, 0);
canvas.translate(translateX, translateY);
canvas.scale(scale, scale);
canvas.rotate(-rotation, lat, lon);
// Drawing Points
Renderer.drawStreet(gaia.getStreets(), scale, canvas, pt);
Renderer.drawPolygon(gaia.getPolygons(), canvas, pt);
Renderer.drawPOI(myContext, gaia.getPOIs(), canvas, pt, scale, rotation);
Renderer.drawCustomPOI(myContext, gaia.getCustomPOI(), canvas, pt, scale, rotation);
if (showLocation) {
drawMarker(canvas);
}
if(drivingMode)
{
Renderer.drawRoute(gaia.getRoute(), canvas, pt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is actually a map renderer.
I know the issue is very likely to be due to the double buffering, but I cannot find a way to fix it.
Thanks!
N.
Can you please post the code for the callback methods (onSurfaceCreated, onSurfaceChanged, onSurfaceDestroyed) and maybe the constructor for the view too? I think the problem could be due to the setting up and not the actual rendering.
How are you accessing the surfaceHolder. Are you using the getHolder() method for that? And are you sending the reference you get to the surfaceHolder from getHolder() to the DrawingThread?
Here is the light version of the code:
Code:
public class CustomMapView extends SurfaceView implements
SurfaceHolder.Callback, LocationListener {
private DrawingThread _thread;
private RenderingThread _threadStreets;
Context myContext;
Paint pt = new Paint();
final int SCREEN_HEIGHT = 600;
final int SCREEN_WIDTH = 480;
float scale;
int range = 100000;
static public int rotation = 0;
int sensibility = 100;
int lat;
int lon;
float translateX = -lat * scale - SCREEN_HEIGHT / 2;
float translateY = -lon * scale + SCREEN_WIDTH / 2;
boolean followLocation = true;
boolean isZooming = false;
boolean showLocation = true;
boolean followRotation = false;
static boolean drivingMode = false;
boolean DEBUG = true;
Handler mHandler;
public static GaiaApp gaia;
public CustomMapView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
gaia = ((GaiaApp) context.getApplicationContext());
scale = gaia.getCurScale();
lat = (int) gaia.getCurPosition().getLatitude();
lon = (int) gaia.getCurPosition().getLongitude();
pf = new PathFinder();
startupDB();
myContext = context;
mHandler = new Handler();
_thread = new DrawingThread(getHolder(), this);
_threadStreets = new RenderingThread(this);
setFocusable(true);
pt.setFlags(Paint.DITHER_FLAG);
pt.setFilterBitmap(true);
this.invalidate();
}
@Override
public void onDraw(Canvas canvas) {
try {
canvas.drawColor(Color.WHITE);
pt.setAntiAlias(true);
canvas.rotate(-90, 0, 0);
canvas.translate(translateX, translateY);
canvas.scale(scale, scale);
canvas.rotate(-rotation, lat, lon);
// Drawing Points
Renderer.drawStreet(gaia.getStreets(), scale, canvas, pt);
Renderer.drawPolygon(gaia.getPolygons(), canvas, pt);
Renderer.drawPOI(myContext, gaia.getPOIs(), canvas, pt, scale, rotation);
Renderer.drawCustomPOI(myContext, gaia.getCustomPOI(), canvas, pt, scale, rotation);
if (showLocation) {
drawMarker(canvas);
}
if(drivingMode)
{
Renderer.drawRoute(gaia.getRoute(), canvas, pt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!_thread.isRunning()) {
_thread.setRunning(true);
_thread.start();
}
if (!_threadStreets.isRunning()) {
_threadStreets.setRunning(true);
_threadStreets.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
_thread.setRunning(false);
_threadStreets.setRunning(false);
while (retry) {
try {
_thread.join();
_threadStreets.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
class DrawingThread extends Thread {
private SurfaceHolder _surfaceHolder;
private CustomMapView _cmv;
private boolean _run = false;
public DrawingThread(SurfaceHolder surfaceHolder, CustomMapView cmv) {
super();
_surfaceHolder = surfaceHolder;
_cmv = cmv;
}
public void setRunning(boolean run) {
_run = run;
}
public boolean isRunning() {
return _run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
@Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas();
synchronized (_surfaceHolder) {
_cmv.onDraw(c);
}
} finally {
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
class RenderingThread extends Thread {
CustomMapView _cmv;
Boolean _run = false;
public RenderingThread(CustomMapView cmv) {
super();
_cmv = cmv;
}
public void setRunning(boolean run) {
_run = run;
}
public boolean isRunning() {
return _run;
}
@Override
public void run() {
while (_run) {
try {
Log.d("CustomMapView", "Retrieving...");
new StreetRunnable(_cmv).run();
Log.d("CustomMapView", "Retrieving");
if(!followRotation)
rotation = 0;
else
rotation = gaia.getOrientation();
Log.d("CustomMapView", "Updating...");
mHandler.post(new Runnable() {
@Override
public void run() {
_cmv.invalidate();
}
});
Log.d("CustomMapView", "Updated");
} finally {
}
}
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Hello,
have you had the chance to check it out?
Thanks
N.
Sorry about that. I did not have access to the internet for the last 2 - 3 days.
Anyways I went through your code...If that is what you call light I wouldn't want to know whats heavy
I noticed that you have two threads which are responsible for drawing to the same view. You are using the DrawingThread to call the onDraw method of your CustomMapView object and the RenderingThread to post the invalidate method of the same CustomMapView object, which also results in a call to the onDraw method of the same view.
I am not really sure if doing this is a good thing and maybe this is what is causing the problems with the rendering? As a test, you could comment out one of the Thread.start() calls to one of the two rendering threads in your onSurfaceCreated method and check if it stops flickering.
I know this isn't how you want your app to function but if it fixes the flickering you'd know its the the two drawing threads that are causing the problem.
Code:
@Override
public void surfaceCreated(SurfaceHolder holder) {
// Comment out either one of the following two if blocks
if (!_thread.isRunning()) {
_thread.setRunning(true);
_thread.start();
}
if (!_threadStreets.isRunning()) {
_threadStreets.setRunning(true);
_threadStreets.start();
}
}
Awesome dude!
It fixed it straight away.
The reason is that I got a thread first and then added a new one, without thinking about just merging them both together
Thanks again!
Yep. You're welcome!
You'll just have to redesign your code to use just one rendering thread and it should work fine. All the best!

Using multiple drawables with MapsForge

After following the developer tutorial using Google Maps, my code is crashing when trying to execute the map code from the start up screen. I am trying to add Big East basketball team icons on the map in the correct GPS location. When that part of the code is taken out it works but I can't find what I'm doing wrong. Thanks for any help you can provide.
Here is the map code:
Code:
public class MapsForgeViewer extends MapActivity implements LocationListener, OnClickListener {
private static final double latitudePitt = 40.443061;
private static final double longitudePitt = -79.962273;
private static final double latitudeUConn = 41.807975;
private static final double longitudeUConn = -72.253626;
private MapView mapView;
private GeoPoint myCurrentLocation;
private Button findPosition;
private Button roster;
private Button schedule;
private Button stats;
private Button exit;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.map_view);
// setting up the location listener
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
100, 0, mlocListener);
// end of location listener setup
// find from XML and set onClickListeners
findPosition = (Button) findViewById(R.id.findPositionButton);
roster = (Button) findViewById(R.id.roster);
schedule = (Button) findViewById(R.id.schedule);
stats = (Button) findViewById(R.id.stats);
exit = (Button) findViewById(R.id.exit);
findPosition.setOnClickListener(this);
roster.setOnClickListener(this);
schedule.setOnClickListener(this);
stats.setOnClickListener(this);
exit.setOnClickListener(this);
// end of mapView layout setup
// setting the up the map at the proper zoom level and creating the
// scale bars and buttons
mapView = (MapView) findViewById(R.id.mapView);
mapView.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
mapView.setBuiltInZoomControls(true);
mapView.setScaleBar(true);
mapView.setClickable(true);
findPositionButton(myCurrentLocation);
mapView.getController().setZoom(14);
setCenterlocation();
// end of mapView setup
//Put pins on map
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawablePitt = this.getResources().getDrawable(R.drawable.pittspin);
CustomItemizedOverlay itemizedOverlayPitt = new CustomItemizedOverlay(drawablePitt, this);
Drawable drawableUConn = this.getResources().getDrawable(R.drawable.connpin);
CustomItemizedOverlay itemizedOverlayUConn = new CustomItemizedOverlay(drawableUConn, this);
//Create points using latitude and longitude
GeoPoint pointPitt = new GeoPoint(latitudePitt, longitudePitt);
OverlayItem overlayitemPitt = new OverlayItem(pointPitt, "Pitt", "Panthers");
GeoPoint pointUConn = new GeoPoint(latitudeUConn, longitudeUConn);
OverlayItem overlayitemUConn = new OverlayItem(pointUConn, "UConn", "Huskies");
itemizedOverlayPitt.addOverlay(overlayitemPitt);
itemizedOverlayUConn.addOverlay(overlayitemUConn);
//add to map
mapOverlays.add(itemizedOverlayPitt);
mapOverlays.add(itemizedOverlayUConn);
}
public void onClick(View v)
{
switch (v.getId())
{
case (R.id.findPositionButton):
findPositionButton(myCurrentLocation);
break;
case (R.id.roster):
// get data from database
break;
case (R.id.schedule):
break;
case (R.id.stats):
break;
// close the app
case (R.id.exit):
finish();
break;
}
}
public void findPositionButton(GeoPoint p)
{
mapView.getController().setCenter(p);
}
@Override
// resumes the actions of the application on a pause
protected void onResume()
{
super.onResume();
}
// sets the center of the screen on the map
protected void setCenterlocation()
{
if (myCurrentLocation == null)
mapView.getController().setCenter(new GeoPoint(39.00, -100.00));
else
mapView.getController().setCenter(myCurrentLocation);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
GeoPoint gp = new GeoPoint(loc.getLatitude(), loc.getLongitude());
if (gp != null)
myCurrentLocation = gp;
}
// activates when the current provider is disabled, or inactive
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Disabled",
Toast.LENGTH_LONG).show();
}
// activates when a provider is found.
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Enabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void onLocationChanged(Location arg0)
{
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
CustomItemizedOverlay:
Code:
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public MapsForgeViewer mActivtyl;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
@Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
@Override
public int size() {
return mapOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}

[Q] Android camera in portrait but playing in landscape

I have this code below. The problem is i set the orientation of camera to portrait, even preview is portrait. But when i playback that video i see it in landscape mode. Do you guys know why and how i can fix this? Is there a way to rotate VideoView when i playback or to rotate video itself after recording..? I beg you, help me, anywhere i ask nobody knows why and how to fix it...
Here is the code:
Code:
public class BetaRecordActivity extends Activity {
private Preview preview;
private Camera camera;
private MediaRecorder recorder;
private int defaultCameraId;
private int videoCount;
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.beta_record, menu);
return true;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beta_record);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
initCameraAndPreview();
videoCount = 0;
preview.setOnTouchListener(new View.OnTouchListener() {
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
releaseCamera();
getThatCamReady();
recorder.start();
videoCount ++;
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
stopRecording();
break;
}
return true;
}
});
}
[user=439709]@override[/user]
protected void onResume() {
super.onResume();
}
[user=439709]@override[/user]
protected void onPause() {
super.onPause();
}
private boolean getThatCamReady() {
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
File tempFile = new File(Environment.getExternalStorageDirectory(), "/rec/temp/video_" + String.valueOf(videoCount) + ".mp4");
recorder.setOutputFile(tempFile.getPath());
recorder.setMaxDuration(12500);
recorder.setMaxFileSize(7000000);
recorder.setPreviewDisplay(preview.getHolder().getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
private void stopRecording() {
//timer.pause();
try {
recorder.stop();
} catch(RuntimeException stopException) {
// Handle the cleanup here
//badList.add(videoCount);
//videoCount--;
//RecordActivity.this.timeLeft.setText(String.valueOf(videoCount));
}
releaseMediaRecorder();
}
private void initCameraAndPreview() {
// Find the total number of cameras available
int numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
preview = new Preview(this, camera);
FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
myCameraPreview.addView(preview);
}
private void releaseMediaRecorder(){
if (recorder != null) {
recorder.reset();
recorder.release();
recorder = null;
camera.lock();
}
}
private void releaseCamera(){
if (camera != null){
camera.release();
camera = null;
}
}
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}

[Q] How do I filter a retrieve data in Spinner?

I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
randomise said:
I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
Click to expand...
Click to collapse
Can someone please help me out?
your help will be appreciated.
Thanks

Help for Avin App or Auxiliary in

I have a problem that my monkeyboard Dab receiver needs audio in. This can be switched with the avin app. But I only need the Audio switched not the video. Is it possible to make a Task with Tasker or similar to run some code or script to switch the audio.
Because also after boot the avin app is blocking the system. For example pppwidget starts only after exiting the avin app.
I also did take a look at the code of the app but I am a completely noob at java app programming and could not identify the code for switching the audio.
Can anyone understand and help me please?
Thanks
I am on malaysk kitkat rom.
here is the code i could decompile. Maybe it is useful for my Problem
MTCAVIN.apk com microntek avin AVINActivity.java
package com.microntek.avin;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.System;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
public class AVINActivity extends Activity {
private static boolean activityVisible;
private static boolean statusbarshow;
private static boolean videoEnable;
private BroadcastReceiver AVINBootReceiver;
private final int MSG_CAPTURE_OFF;
private final int MSG_CAPTURE_ON;
private final int MSG_TIME_TICK;
private final int MSG_VIDEO_CHECK;
private AudioManager am;
private Handler mHandler;
private ImageView mImageBlack;
private ImageView mImageScreen;
private boolean mInChannel;
private boolean mIsSignal;
private View mTextWarning;
private View signalshow;
private int startbackflag;
private int statusbarhidetime;
/* renamed from: com.microntek.avin.AVINActivity.1 */
class C00001 extends Handler {
C00001() {
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 65281:
AVINActivity.this.captureOn();
case 65282:
AVINActivity.this.captureOff();
case 65283:
AVINActivity.this.videoCheck();
case 65284:
AVINActivity.this.refresTick();
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
default:
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.2 */
class C00012 implements OnClickListener {
C00012() {
}
public void onClick(View v) {
if (!AVINActivity.statusbarshow) {
AVINActivity.statusbarshow = true;
AVINActivity.this.mHandler.removeMessages(65284);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
AVINActivity.this.statusbarhidetime = 0;
AVINActivity.this.resumeStatusBar();
} else if (AVINActivity.this.mIsSignal && AVINActivity.videoEnable) {
AVINActivity.statusbarshow = false;
AVINActivity.this.hideStatusBar();
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.3 */
class C00023 extends BroadcastReceiver {
C00023() {
}
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
if (action.equals("com.microntek.bootcheck")) {
String classname = arg1.getStringExtra("class");
if (!classname.equals("com.microntek.avin") && !classname.equals("phonecallin") && !classname.equals("phonecallout")) {
AVINActivity.this.sendFinish();
}
} else if (action.equals("com.microntek.carstatechange")) {
if (AVINActivity.activityVisible && arg1.getStringExtra("type").equals("SAFE")) {
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
} else if (action.equals("com.microntek.videosignalchange") && arg1.getStringExtra("type").equals("avin")) {
AVINActivity.this.mIsSignal = arg1.getBooleanExtra("sta", true);
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
}
public AVINActivity() {
this.MSG_CAPTURE_ON = 65281;
this.MSG_CAPTURE_OFF = 65282;
this.MSG_VIDEO_CHECK = 65283;
this.MSG_TIME_TICK = 65284;
this.mImageBlack = null;
this.mTextWarning = null;
this.signalshow = null;
this.mImageScreen = null;
this.mIsSignal = true;
this.startbackflag = 0;
this.statusbarhidetime = 0;
this.am = null;
this.mInChannel = false;
this.mHandler = new C00001();
this.AVINBootReceiver = new C00023();
}
static {
videoEnable = false;
activityVisible = false;
statusbarshow = true;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.startbackflag = getIntent().getIntExtra("start", 0);
if (this.startbackflag != 0) {
moveTaskToBack(true);
}
Intent it1 = new Intent("com.microntek.bootcheck");
it1.putExtra("class", "com.microntek.avin");
sendBroadcast(it1);
this.am = (AudioManager) getSystemService("audio");
this.statusbarhidetime = 0;
setContentView(R.layout.main);
this.signalshow = findViewById(R.id.signalshow);
this.mImageScreen = (ImageView) findViewById(R.id.screen);
this.mImageScreen.setOnClickListener(new C00012());
this.mImageBlack = (ImageView) findViewById(R.id.black);
this.mTextWarning = findViewById(R.id.safewarning);
IntentFilter itfl = new IntentFilter();
itfl.addAction("com.microntek.bootcheck");
itfl.addAction("com.microntek.carstatechange");
itfl.addAction("com.microntek.videosignalchange");
registerReceiver(this.AVINBootReceiver, itfl);
deviceOn();
sendCanBusAvinOn();
this.mHandler.sendEmptyMessageDelayed(65284, 1000);
}
private void sendFinish() {
deviceOff();
finish();
}
private void deviceOn() {
if (!this.mInChannel) {
this.am.setParameters("av_channel_enter=line");
this.mInChannel = true;
}
}
private void deviceOff() {
if (this.mInChannel) {
this.mInChannel = false;
this.am.setParameters("av_channel_exit=line");
}
}
private void sendCanBusAvinOn() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-on");
sendBroadcast(it1);
}
private void sendCanBusAvinOff() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-off");
sendBroadcast(it1);
}
public void onBackPressed() {
sendFinish();
}
private void refresTick() {
if (!this.mIsSignal) {
boolean en = GetDrivingVideoEnable();
if (videoEnable != en) {
videoEnable = en;
this.mHandler.removeMessages(65283);
this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
if (this.statusbarhidetime < 10) {
this.statusbarhidetime++;
if (this.statusbarhidetime == 10 && videoEnable && statusbarshow) {
statusbarshow = false;
hideStatusBar();
}
}
}
private boolean GetDrivingVideoEnable() {
if (System.getInt(getContentResolver(), "DrivingVideoEN", 0) != 0) {
return true;
}
if (this.am.getParameters("sta_driving=").equals("true")) {
return false;
}
return true;
}
public void hideStatusBar() {
if (this.mIsSignal) {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags |= 1024;
win.setAttributes(winParams);
}
}
public void resumeStatusBar() {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags &= -1025;
win.setAttributes(winParams);
}
protected void onResume() {
super.onResume();
statusbarshow = true;
activityVisible = true;
resumeStatusBar();
captureOn();
videoEnable = GetDrivingVideoEnable();
this.mHandler.sendEmptyMessageDelayed(65283, 100);
sendBroadcast(new Intent("com.microntek.musicclockreset"));
}
protected void onPause() {
activityVisible = false;
captureOff();
super.onPause();
}
protected void onDestroy() {
this.mHandler.removeCallbacksAndMessages(null);
unregisterReceiver(this.AVINBootReceiver);
deviceOff();
sendCanBusAvinOff();
super.onDestroy();
}
protected void videoCheck() {
if (videoEnable) {
this.mTextWarning.setVisibility(4);
} else {
this.mTextWarning.setVisibility(0);
}
if (this.mIsSignal) {
this.signalshow.setVisibility(8);
return;
}
this.signalshow.setVisibility(0);
this.statusbarhidetime = 0;
if (!statusbarshow) {
resumeStatusBar();
}
statusbarshow = true;
}
protected void captureOn() {
this.am.setParameters("ctl_capture_on=line");
this.mImageBlack.setVisibility(4);
}
protected void captureOff() {
this.mImageBlack.setVisibility(0);
this.am.setParameters("ctl_capture_off=line");
}
}
Privacy Policy
Maybe simple shell command or something? Anyone?
I did a simple Tweak in the Avin app. Now it launches without Ui. For audio in only and only for kitkat roms.
I have a typo in the attached APK...
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
ivellios said:
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
Click to expand...
Click to collapse
2nd - if you're still around - can you recompile with this ?
Might be as simple as commenting out the this.am.setParameters calls
Sorry, this is not possible for me. I did not figure it out how to disable the video.

Categories

Resources