i have a problem in this application(Mini4WD Lap Timer) in my Motorola Defy.. they provide they source code.. maybe you could help me to be compatible it on my device..
https://play.google.com/store/apps/details?id=com.pimentoso.android.laptimer&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5waW1lbnRvc28uYW5kcm9pZC5sYXB0aW1lciJd
the problem is when calibrating, it stock..
and the small preview in the upper-left of the timer is not working, only shows black..
here is the codes
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pimentoso.android.laptimer" android:versionCode="8"
android:versionName="1.4.1" android:installLocation="auto">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".TimerActivity" android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SensitivityDialogActivity"
android:label="#string/label_sensitivity" android:theme="#android:style/Theme.Dialog" />
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.SET_ORIENTATION" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
</manifest>
FPSCounter.java
package com.pimentoso.android.laptimer;
import android.util.Log;
public class FPSCounter {
long startTime = System.nanoTime();
int frames = 0;
public void logFrame() {
frames++;
if(System.nanoTime() - startTime >= 1000000000) {
Log.d("FPSCounter", "fps: " + frames);
frames = 0;
startTime = System.nanoTime();
}
}
}
SensitivityDialogActivity.java
package com.pimentoso.android.laptimer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SensitivityDialogActivity extends Activity implements OnClickListener, OnSeekBarChangeListener
{
private SeekBar bar;
private TextView barValue;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sensitivity);
findViewById(R.id.button_sensitivity_close).setOnClickListener(this);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
String currentValue = getPreferences(MODE_PRIVATE).getString("sensitivity", "15");
bar = (SeekBar) findViewById(R.id.seekbar_sensitivity);
bar.setOnSeekBarChangeListener(this);
barValue = (TextView) findViewById(R.id.seekbar_sensitivity_value);
barValue.setText(currentValue);
bar.setProgress(Integer.valueOf(currentValue));
// settare il valore nel timer a (25-barValue)
// barra 20 = 5
// barra 15 = 10
// barra 10 = 15
// barra 5 = 20
// barra 0 = 25
}
#Override
public void onClick(View v)
{
String finalValue = barValue.getText().toString();
getPreferences(MODE_PRIVATE).edit().putString("sensitivity", finalValue).commit();
TimerActivity.calibrateThreshold = 25 - Integer.valueOf(finalValue);
this.finish();
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{
String t = String.valueOf(arg1);
barValue.setText(t);
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
}
TimerActivity.java
package com.pimentoso.android.laptimer;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TimerActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback, OnClickListener {
// elementi del layout
SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
Camera mCamera;
TextView timerLabel;
TextView statusLabel;
TextView lap1Label;
TextView lap2Label;
TextView lap3Label;
TextView lapBestLabel;
Button startButton;
// flags
boolean isPreviewRunning = false;
boolean isCalibrating = false;
boolean isCalibrated = false;
boolean isStarted = false;
boolean isTimerRunning = false;
boolean caughtPreviousFrame = false;
// contatore dei frame per calibrazione
int frame = 0;
// offset dei pixel da controllare
int[] pixelOffset = new int[3];
// array di calibrazione
int[][] calibrateRange = new int[3][20];
// valori finali di calibrazione
int[] calibrateValue = new int[3];
// soglia di differenza di luminosità per catchare il frame
public static int calibrateThreshold = 10;
// tempo iniziale
long mStartTime = 0L;
// millisecondi di ultimo catch
long mLastCatchTime = 0;
// tempo del giro migliore
long bestLap = 0;
// tempi dei giri
// long[] laps = new long[3];
ArrayList<Long> laps = new ArrayList<Long>();
// contatore dei giri
int lapCount = 0;
FPSCounter fps = new FPSCounter();
Handler mHandler = new Handler();
StringBuffer timerBuffer;
StringBuffer lapBuffer;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis() - mStartTime;
timerLabel.setText(convertTime(millis));
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 40);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button_start).setOnClickListener(this);
findViewById(R.id.button_calibrate).setOnClickListener(this);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
String threshold = getPreferences(MODE_PRIVATE).getString("sensitivity", "15");
calibrateThreshold = Integer.valueOf(threshold);
timerLabel = (TextView) findViewById(R.id.text_timer);
statusLabel = (TextView) findViewById(R.id.text_status);
lap1Label = (TextView) findViewById(R.id.text_lap_1);
lap2Label = (TextView) findViewById(R.id.text_lap_2);
lap3Label = (TextView) findViewById(R.id.text_lap_3);
lapBestLabel = (TextView) findViewById(R.id.text_lap_best);
startButton = (Button) findViewById(R.id.button_start);
statusLabel.setText(getString(R.string.label_status_init));
startButton.setEnabled(false);
}
#Override
public void onStart() {
super.onStart();
// show help
if (getPreferences(MODE_PRIVATE).getString("first_time", "1").equals("1")) {
showAlertBox();
getPreferences(MODE_PRIVATE).edit().putString("first_time", "0").commit();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
synchronized (this) {
try {
mCamera = Camera.open();
}
catch (RuntimeException e) {
// camera service already in use: schianta
new AlertDialog.Builder(this).setMessage(getString(R.string.error_camera_locked_text)).setTitle("Error").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TimerActivity.this.finish();
}
}).show();
return;
}
if (mCamera == null) {
// camera not found: schianta
new AlertDialog.Builder(this).setMessage(getString(R.string.error_camera_null_text)).setTitle("Error").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TimerActivity.this.finish();
}
}).show();
return;
}
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size mCameraSize = parameters.getPreviewSize();
int bytesPerPixel = ImageFormat.getBitsPerPixel(parameters.getPreviewFormat());
int bufferSize = (mCameraSize.width * mCameraSize.height * bytesPerPixel) >> 3;
mCamera.addCallbackBuffer(new byte[bufferSize]);
mCamera.addCallbackBuffer(new byte[bufferSize]);
mCamera.addCallbackBuffer(new byte[bufferSize]);
pixelOffset[0] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.1));
pixelOffset[1] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.5));
pixelOffset[2] = (int) (mCameraSize.width / 2) + (mCameraSize.width * (int) (mCameraSize.height * 0.9));
mCamera.setDisplayOrientation(90);
try {
mCamera.setPreviewDisplay(arg0);
}
catch (IOException e) {
Log.e("Camera", "Could not set preview display");
}
mCamera.setPreviewCallbackWithBuffer(this);
mCamera.startPreview();
isPreviewRunning = true;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
synchronized (this) {
try {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
isPreviewRunning = false;
}
}
catch (Exception e) {
Log.e("Camera", e.getMessage());
}
finally {
if (mCamera != null) {
mCamera.release();
}
}
}
}
#Override
public void onPreviewFrame(byte[] yuv, Camera arg1) {
int value0 = (int) yuv[pixelOffset[0]] & 0xFF;
int value1 = (int) yuv[pixelOffset[1]] & 0xFF;
int value2 = (int) yuv[pixelOffset[2]] & 0xFF;
// sto calibrando...
if (isCalibrating) {
frame++;
Log.d("Timer", "Calibrating, " + value0 + ";" + value1 + ";" + value2);
calibrateRange[0][frame - 1] = value0;
calibrateRange[1][frame - 1] = value1;
calibrateRange[2][frame - 1] = value2;
if (frame >= 20) {
// finito di calibrare
isCalibrating = false;
isCalibrated = true;
startButton.setEnabled(true);
statusLabel.setText(getString(R.string.label_status_ready));
// calcolo la media
int tot0 = 0, tot1 = 0, tot2 = 0;
for (int i = 0; i < 20; i++) {
tot0 += calibrateRange[0][i];
tot1 += calibrateRange[1][i];
tot2 += calibrateRange[2][i];
}
calibrateValue[0] = tot0 / 20;
calibrateValue[1] = tot1 / 20;
calibrateValue[2] = tot2 / 20;
Log.d("Timer", "Calibrated on [" + calibrateValue[0] + "][" + calibrateValue[1] + "][" + calibrateValue[2] + "]");
}
}
// sono in ascolto di variazioni
else if (isStarted) {
// catch del frame
if (isCalibrated && (value0 < calibrateValue[0] - calibrateThreshold || value0 > calibrateValue[0] + calibrateThreshold || value1 < calibrateValue[1] - calibrateThreshold || value1 > calibrateValue[1] + calibrateThreshold || value2 < calibrateValue[2] - calibrateThreshold || value2 > calibrateValue[2] + calibrateThreshold)) {
// se ho catchato il frame precedente, ignoro
if (!caughtPreviousFrame) {
Log.d("Timer", "Frame caught!");
caughtPreviousFrame = true;
if (isTimerRunning) {
// calcolo dei lap
long catchTime = SystemClock.uptimeMillis();
lapCount++;
long lapTime = catchTime - mLastCatchTime;
laps.add(lapTime);
if (lapCount == 1) {
bestLap = lapTime;
}
else if (bestLap > lapTime) {
bestLap = lapTime;
}
printLaps();
mLastCatchTime = catchTime;
}
else {
// devo far partire il timer
isTimerRunning = true;
mStartTime = SystemClock.uptimeMillis();
mLastCatchTime = mStartTime;
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 50);
}
}
}
else {
caughtPreviousFrame = false;
}
}
mCamera.addCallbackBuffer(yuv);
fps.logFrame();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_start: {
if (!isCalibrated || isCalibrating) {
// non è calibrato
break;
}
if (isStarted) {
// ho stoppato
startButton.setText("Start");
statusLabel.setText(getString(R.string.label_status_ready));
isStarted = false;
isTimerRunning = false;
mHandler.removeCallbacks(mUpdateTimeTask);
}
else {
// ho startato
startButton.setText("Stop");
statusLabel.setText(getString(R.string.label_status_started));
timerLabel.setText("0:00:0");
isStarted = true;
mStartTime = 0L;
lapCount = 0;
// resetto i laps
laps = new ArrayList<Long>();
bestLap = 0;
printLaps();
}
break;
}
case R.id.button_calibrate: {
if (isTimerRunning) {
// devo stoppare prima di calibrare
break;
}
// ho pigiato calibra, devo resettare tutto
statusLabel.setText(getString(R.string.label_status_calibrating));
timerLabel.setText("0:00:0");
frame = 0;
mStartTime = 0L;
lapCount = 0;
isStarted = false;
isTimerRunning = false;
isCalibrating = true;
isCalibrated = false;
// resetto i laps
laps = new ArrayList<Long>();
bestLap = 0;
printLaps();
break;
}
}
}
private String convertTime(long millis) {
if (millis == 0) {
return "0:00:0";
}
timerBuffer = new StringBuffer();
int split = ((int) (millis / 100)) % 10;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
timerBuffer.append(minutes).append(":0").append(seconds).append(":").append(split);
return timerBuffer.toString();
}
else {
timerBuffer.append(minutes).append(":").append(seconds).append(":").append(split);
return timerBuffer.toString();
}
}
private void printLaps() {
lapBuffer = new StringBuffer();
try {
lapBuffer.append("Lap ").append(lapCount).append(": ").append(convertTime(laps.get(laps.size() - 1)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append("Lap ").append(lapCount).append(": ").append(convertTime(0));
}
lap1Label.setText(lapBuffer.toString());
lapBuffer = new StringBuffer();
if (lapCount > 1) {
lapBuffer.append("Lap ").append(lapCount - 1);
}
else {
lapBuffer.append("Lap 0");
}
try {
lapBuffer.append(": ").append(convertTime(laps.get(laps.size() - 2)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append(": ").append(convertTime(0));
}
lap2Label.setText(lapBuffer.toString());
lapBuffer = new StringBuffer();
if (lapCount > 2) {
lapBuffer.append("Lap ").append(lapCount - 2);
}
else {
lapBuffer.append("Lap 0");
}
try {
lapBuffer.append(": ").append(convertTime(laps.get(laps.size() - 3)));
}
catch (IndexOutOfBoundsException e) {
lapBuffer.append(": ").append(convertTime(0));
}
lap3Label.setText(lapBuffer.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_tutorial: {
showAlertBox();
return true;
}
case R.id.menu_sensitivity: {
// devo stoppare tutto
startButton.setText("Start");
statusLabel.setText(getString(R.string.label_status_ready));
isStarted = false;
isTimerRunning = false;
mHandler.removeCallbacks(mUpdateTimeTask);
Intent i = new Intent(this, SensitivityDialogActivity.class);
startActivity(i);
return true;
}
case R.id.menu_email: {
if (isStarted || isTimerRunning) {
Toast.makeText(this, getString(R.string.error_timer_started), Toast.LENGTH_SHORT).show();
return true;
}
if (laps == null || laps.size() == 0) {
Toast.makeText(this, getString(R.string.error_laps_empty), Toast.LENGTH_SHORT).show();
return true;
}
String emailBody = lapsToString();
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailBody);
startActivity(Intent.createChooser(emailIntent, getString(R.string.menu_mail_laps)));
return true;
}
}
return false;
}
public void showAlertBox() {
new AlertDialog.Builder(this).setMessage(getString(R.string.dialog_tutorial_text)).setTitle("Tutorial").setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
private String lapsToString() {
StringBuffer s = new StringBuffer();
s.append("Mini 4WD Android Lap Timer data");
s.append("\n\n");
for (int i = 0; i < laps.size(); i++) {
long lap = laps.get(i);
s.append("Lap ").append(i + 1).append(": ").append(convertTime(lap)).append("\n");
}
s.append("\n");
s.append("Best lap: " + convertTime(bestLap));
return s.toString();
}
}
thank you in advance.. :)
Related
Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);
I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}
How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
I have ask a question before about change method OnClick to method lifecycle
But I think the problem was solving.
But in this new question is same with before but different.
Now i have ask how add alertdialog to my source code. I have 3 aletdialog will show when the noise until 70 dB , 80 dB and 100 dB.
Here's MY CODE
package com.andronoise;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.text.DecimalFormat;
public class MainActivity extends Activity implements InputListener{
InputSuara micInput;
TextView mdBTextView;
TextView mdBFractionTextView;
LevelBar mBarLevel;
double mGain = 2500.0 / Math.pow(10.0, 90.0 / 20.0);
double mRmsSmoothed;
double mAlpha = 0.9;
public double dB;
private int mSampleRate;
private int mAudioSource;
private volatile boolean mDrawing;
private volatile int mDrawingCollided;
private static final String TAG = "MainActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
micInput = new InputSuara(this);
setContentView(R.layout.activity_main);
mBarLevel = (LevelBar)findViewById(R.id.bar_level_drawable_view);
mdBTextView = (TextView)findViewById(R.id.dBTextView);
mdBFractionTextView = (TextView)findViewById(R.id.dBFractionTextView);
final ToggleButton onOffButton=(ToggleButton)findViewById(
R.id.on_off_toggle_button);
ToggleButton.OnClickListener tbListener =
new ToggleButton.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffButton.isChecked()) {
readPreferences();
micInput.setSampleRate(mSampleRate);
micInput.setAudioSource(mAudioSource);
micInput.start();
} else {
micInput.stop();
}
}
};
onOffButton.setOnClickListener(tbListener);
}
private void readPreferences() {
SharedPreferences preferences = getSharedPreferences("LevelMeter",
MODE_PRIVATE);
mSampleRate = preferences.getInt("SampleRate", 8000);
mAudioSource = preferences.getInt("AudioSource",
MediaRecorder.AudioSource.VOICE_RECOGNITION);
}
public void Alert () {
if (dB >= 70 || dB <80) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 70 dB, kebisingan dalam tingkat rendah")
.setPositiveButton("Close",null).show();
}
else if (dB >=80 || dB <100) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 80 dB, kebisingan dalam tingkat sedang Waspada !")
.setPositiveButton("Close",null).show();
}
else if ( dB >= 100) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 100 dB, berbahaya jika lebih dari 1 menit!!! Segera menghindar")
.setPositiveButton("Close",null).show();
};
}
public void processAudioFrame(short[] audioFrame) {
if (!mDrawing) {
mDrawing = true;
double rms = 0;
for (int i = 0; i < audioFrame.length; i++) {
rms += audioFrame[i]*audioFrame[i];
}
rms = Math.sqrt(rms/audioFrame.length);
mRmsSmoothed = mRmsSmoothed * mAlpha + (1 - mAlpha) * rms;
final double rmsdB = 20.0 * Math.log10(mGain * mRmsSmoothed);
dB = 20 + rmsdB;
mBarLevel.post(new Runnable() {
#Override
public void run() {
mBarLevel.setLevel(( 10 + rmsdB) / 90);
DecimalFormat df = new DecimalFormat("##");
mdBTextView.setText(df.format(dB));
int one_decimal = (int) (Math.round(Math.abs(rmsdB * 10))) % 10;
mdBFractionTextView.setText(Integer.toString(one_decimal));
mDrawing = false;
}
});
} else {
mDrawingCollided++;
Log.v(TAG, "Level bar update collision, i.e. update took longer " +
"than 20ms. Collision count" + Double.toString(mDrawingCollided));
}
}
}
You have an error in yours if conditions
if (dB >= 70 || dB <80){
//do something
}
else if (dB >=80 || dB <100){
//do something
}
e.g db=95 the app will go to the first if
the correct code is:
if (dB >= 70 && dB <80){
//do something
} else if (dB >=80 && dB <100){
//do something
}else{
//do something
}
so
package com.andronoise;
import android.content.DialogInterface;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.text.DecimalFormat;
public class MainActivity extends Activity implements InputListener{
InputSuara micInput;
TextView mdBTextView;
TextView mdBFractionTextView;
LevelBar mBarLevel;
double mGain = 2500.0 / Math.pow(10.0, 90.0 / 20.0);
double mRmsSmoothed;
double mAlpha = 0.9;
public double dB;
private int mSampleRate;
private int mAudioSource;
private volatile boolean mDrawing;
private volatile int mDrawingCollided;
private static final String TAG = "MainActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
micInput = new InputSuara(this);
setContentView(R.layout.activity_main);
mBarLevel = (LevelBar)findViewById(R.id.bar_level_drawable_view);
mdBTextView = (TextView)findViewById(R.id.dBTextView);
mdBFractionTextView = (TextView)findViewById(R.id.dBFractionTextView);
final ToggleButton onOffButton=(ToggleButton)findViewById(
R.id.on_off_toggle_button);
ToggleButton.OnClickListener tbListener =
new ToggleButton.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffButton.isChecked()) {
readPreferences();
micInput.setSampleRate(mSampleRate);
micInput.setAudioSource(mAudioSource);
micInput.start();
} else {
micInput.stop();
}
}
};
onOffButton.setOnClickListener(tbListener);
}
private void readPreferences() {
SharedPreferences preferences = getSharedPreferences("LevelMeter",
MODE_PRIVATE);
mSampleRate = preferences.getInt("SampleRate", 8000);
mAudioSource = preferences.getInt("AudioSource",
MediaRecorder.AudioSource.VOICE_RECOGNITION);
}
public void Alert () {
if (dB >= 70 && dB <80) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 70 dB, kebisingan dalam tingkat rendah")
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
else if (dB >=80 && dB <100) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 80 dB, kebisingan dalam tingkat sedang Waspada !")
.setPositiveButton("Close",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
else if ( dB >= 100) {
AlertDialog.Builder build = new
AlertDialog.Builder(MainActivity.this);
build.setTitle("Alert!!!").setIcon(R.drawable.ic_launcher).setMessage("Level 100 dB, berbahaya jika lebih dari 1 menit!!! Segera menghindar")
.setPositiveButton("Close",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
};
}
public void processAudioFrame(short[] audioFrame) {
if (!mDrawing) {
mDrawing = true;
double rms = 0;
for (int i = 0; i < audioFrame.length; i++) {
rms += audioFrame[i]*audioFrame[i];
}
rms = Math.sqrt(rms/audioFrame.length);
mRmsSmoothed = mRmsSmoothed * mAlpha + (1 - mAlpha) * rms;
final double rmsdB = 20.0 * Math.log10(mGain * mRmsSmoothed);
dB = 20 + rmsdB;
mBarLevel.post(new Runnable() {
#Override
public void run() {
mBarLevel.setLevel(( 10 + rmsdB) / 90);
DecimalFormat df = new DecimalFormat("##");
mdBTextView.setText(df.format(dB));
Alert();
int one_decimal = (int) (Math.round(Math.abs(rmsdB * 10))) % 10;
mdBFractionTextView.setText(Integer.toString(one_decimal));
mDrawing = false;
}
});
} else {
mDrawingCollided++;
Log.v(TAG, "Level bar update collision, i.e. update took longer " +
"than 20ms. Collision count" + Double.toString(mDrawingCollided));
}
}
}
I need some help!
I need to send some NMEA data from device via COM port to USB port on my Android tablet. When I connect my silab CP210x UART Bridge to tablet, it automaticly launches my programm, but when I try to send some data, my programm does not see it. I'm using usb-serial-for-android library ( https://github.com/mik3y/usb-serial-for-android ). I followed all the instructions from github.
Here is my code:
package com.example.simplexyplotactivity;
import java.io.IOException;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PointF;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.EventLog;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import com.androidplot.Plot;
import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class Simple_xy_plot_example extends Activity implements OnTouchListener {
private int com_cnt;
private String buf;
private String[] fields;
private int buf_max_length;
private int buf_idx;
private boolean buf_started;
public float course=0;
SoundPool sound_pool;
int rot_sound_ID;
private static final String ACTION_USB_PERMISSION ="com.prolific.pl2303hxdsimpletest.USB_PERMISSION";
private static final int SERIES_SIZE = 200;
private XYPlot plotOne;
private SimpleXYSeries series1 = null;
private PointF minXY;
private PointF maxXY;
NMEA_Receiver data;
private Thread myThread;
private String str;
private String stroka;
float zoomRatio = 2, leftBoundary, rightBoundary;
USB2ComDetector mUSB2ComDetector;
Handler CBhandler;
private UsbManager usb_manager;
private static UsbSerialPort ser_port = null;
ComponentName service_name;
byte temp_buf[]=new byte[4096];
private class MyPlotUpdater implements Observer {
Plot plot;
public MyPlotUpdater(Plot plot) {
this.plot = plot;
}
#Override
public void update(Observable o, Object arg) {
plot.redraw();
}
}
private boolean USB2ComConnect() {
/*if (ser_port != null) return false;
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
if (availableDrivers.isEmpty()) {
} else {
// open connection to first avail. driver
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = usb_manager.openDevice(driver.getDevice());
if (connection == null) {
} else { // Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
byte temp_buf[]=new byte[4096]; // 1 byte per pressure sensor, plus 2 bytes for carriage return
int numBytesRead = port.read(temp_buf, 1000);
String arduinoData = new String(temp_buf, "US-ASCII");
Toast.makeText(getApplicationContext(), arduinoData, Toast.LENGTH_SHORT).show(); // Toast debugging
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: couldn't read data from USB device", Toast.LENGTH_LONG).show(); // Toast debugging
}
}
}
/* List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
ser_port=ports.get(0);
UsbDeviceConnection connection=usb_manager.openDevice(ser_port.getDriver().getDevice());
try {
ser_port.open(connection);
ser_port.setParameters(4800, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
ser_port.purgeHwBuffers(true, true);
} catch (IOException e) {
Log.e("NMEAParser", "Cant open or set parameter to serial port");
e.printStackTrace();
return true;
}*/
return false;
}
//**********
public boolean IsCOMopened(){return ser_port!=null?true:false;}
private MyPlotUpdater plotUpdater;
public void onResume() {
// kick off the data generating thread:
myThread = new Thread(data);
myThread.start();
super.onResume();
// try {
// data.EnableRec(true);
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
public void stopThread() {
keepRunning = false;
}
#Override
public void onPause() {
// data.stopThread();
super.onPause();
}
private boolean keepRunning = false;
class NMEA_Receiver implements Runnable {
private static final int SAMPLE_SIZE = 30;
public int k = 1;
private int kk = 1;
private UsbSerialDriver driver;
private boolean rec_enabled=false;//enable/disable when cable plug in/off
private boolean rec_alive=true;//to terminate thread when stop app
byte rec_buf[]=new byte[256];
boolean rec_started=false;
boolean trans_started;
private boolean buf_started;
private String buf;
int rec_idx=0;
NMEA_Receiver(UsbSerialDriver driver){
this.driver=driver;
}
public void stopThread() {
keepRunning = false;
}
synchronized private void SuspendRec(){
}
synchronized public void EnableRec(boolean en) throws IOException {
rec_enabled = en;
UsbDevice dev;
if (en) {
try {
//driver.open();
//driver.setBaudRate(4800);
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
//driver.close();
}
}
// ***********************************************************************************
// ***********************************************************************************
String GetRecBuf(){
return new String(rec_buf);
}
// ***********************************************************************************
public int Transmit(String tr_buf){
return 1;
}
// ***********************************************************************************
public boolean IsCOMMConnected(){
// return mPL2303.isConnected();
return false;
}
public void run() {
//byte temp_buf[]=new byte[4096];
int yy1;
int yy2;
int yy3;
int yy4;
int yy5;
int i=0;
int length=0;
try {
length=ser_port.read(temp_buf, 1000);
} catch (Exception e) {
e.printStackTrace();
}
String str2;
String str3, str4, str5;
boolean terminate=false;
keepRunning = true;
while (keepRunning) {
str5=temp_buf.toString();
Toast toast = Toast.makeText(getApplicationContext(),
str5, Toast.LENGTH_SHORT);
toast.show();
for(int k=0;k<length;k++){
if (temp_buf[0]=='$') {
buf_started = true;
}
if(buf_started){
buf+=(char)temp_buf[k];
if(temp_buf[k]=='\n'){
str = buf;
yy1 = Character.getNumericValue(str.charAt(7));
if (str.charAt(8) == '.') {
str3 = String.valueOf(str.charAt(8));
str2 = "" + yy1 + str3;
} else {
yy2 = Character.getNumericValue(str.charAt(8));
str2 = "" + yy1 + yy2;
}
if (str.charAt(9) == '.') {
str4 = String.valueOf(str.charAt(9));
str2 = str2 + str4;
} else {
if ((str.charAt(9) >= '0' && str.charAt(9) <= '9')) {
yy3 = Character.getNumericValue(str.charAt(9));
str2 = str2 + yy3;
}
}
if (str.charAt(10) == '.') {
str4 = String.valueOf(str.charAt(10));
str2 = str2 + str4;
} else if ((str.charAt(10) >= '0' && str.charAt(10) <= '9')) {
yy4 = Character.getNumericValue(str.charAt(10));
str2 = str2 + yy4;
}
if ((str.charAt(11) >= '0' && str.charAt(11) <= '9')) {
yy5 = Character.getNumericValue(str.charAt(11));
str2 = str2 + yy5;
}
course = Float.parseFloat(str2); //добавить необходимое число
kk++;
series1.addLast(kk, course);
plotOne.setRangeLabel(String.valueOf(course));
plotOne.redraw();// для выведения глубины
}
}
}
}
}
public Number getY(int series, int max) {
return 1;
}
}
public class USB2ComDetector extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
//try {
//data.EnableRec(false);
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_xy_plot_example);
// USB2ComConnect();
// try{
// USB2ComConnect();}
// catch (NullPointerException e){
// e.printStackTrace();
// }
// UsbManager usb_mngr=(UsbManager)getSystemService(Context.USB_SERVICE);
// List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_mngr);
//if(availableDrivers.isEmpty()==false){
// List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
// UsbDeviceConnection connection=usb_mngr.openDevice(ports.get(0).getDriver().getDevice());
// }
//
//UsbSerialDriver driver = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
//data = new NMEA_Receiver();
try {
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.isEmpty()){
Toast toast = Toast.makeText(getApplicationContext(),
"FAIL", Toast.LENGTH_SHORT);
toast.show();
}
//try {
// data.EnableRec(true);
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
return;
}
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
return;
}
// Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1,UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error: couldn't read data from USB device",Toast.LENGTH_LONG).show(); // Toast debugging
}
mUSB2ComDetector=new USB2ComDetector();
IntentFilter filter=new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUSB2ComDetector,filter);
sound_pool=new SoundPool(1, AudioManager.STREAM_MUSIC,0);
rot_sound_ID=sound_pool.load("/system/media/audio/ui/VideoRecord.ogg",1 );
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//plot setup
plotOne = (XYPlot) findViewById(R.id.myFirstXYPlot);
plotOne.setOnTouchListener(this);
plotOne.getGraphWidget().setTicksPerRangeLabel(2);
plotOne.getGraphWidget().setTicksPerDomainLabel(2);
plotOne.getGraphWidget().setRangeLabelWidth(25);
//plotOne.setRangeLabel("");
plotOne.setDomainLabel("");
plotOne.setBorderStyle(Plot.BorderStyle.NONE, null, null);
plotOne.getLayoutManager().remove(plotOne.getLegendWidget());
plotOne.getGraphWidget().setSize(new SizeMetrics(0,SizeLayoutType.FILL,
0, SizeLayoutType.FILL));
plotOne.setPlotMargins(0,0,0,0);
//********
//series setup
series1 = new SimpleXYSeries("PARAM");
series1.useImplicitXVals();
LineAndPointFormatter line1 = new LineAndPointFormatter();
line1.setPointLabelFormatter(new PointLabelFormatter());
plotOne.addSeries(series1, line1);
plotOne.redraw();
plotOne.calculateMinMaxVals();
minXY = new PointF(plotOne.getCalculatedMinX().floatValue(),
plotOne.getCalculatedMinY().floatValue());
maxXY = new PointF(plotOne.getCalculatedMaxX().floatValue(),
plotOne.getCalculatedMaxY().floatValue());
leftBoundary = series1.getX(0).floatValue();
rightBoundary = series1.getX(series1.size() - 1).floatValue();
}
//*****************
// Definition of the touch states
static final int NONE = 0;
static final int ONE_FINGER_DRAG = 1;
static final int TWO_FINGERS_DRAG = 2;
int mode = NONE;
PointF firstFinger;
float distBetweenFingers;
boolean stopThread = false;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // Start gesture
firstFinger = new PointF(event.getX(), event.getY());
mode = ONE_FINGER_DRAG;
stopThread = true;
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger
distBetweenFingers = spacing(event);
// the distance check is done to avoid false alarms
if (distBetweenFingers > 5f) {
mode = TWO_FINGERS_DRAG;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ONE_FINGER_DRAG) {
PointF oldFirstFinger = firstFinger;
firstFinger = new PointF(event.getX(), event.getY());
scroll(oldFirstFinger.x - firstFinger.x);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
} else if (mode == TWO_FINGERS_DRAG) {
float oldDist = distBetweenFingers;
distBetweenFingers = spacing(event);
zoom(oldDist / distBetweenFingers);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
}
break;
}
return true;
}
private void zoom(float scale) {
float domainSpan = maxXY.x - minXY.x;
float oldMax = maxXY.x;
float oldMin = minXY.x;
float domainMidPoint = maxXY.x - (domainSpan / 2.0f);
float offset = domainSpan * scale / 2.0f;
minXY.x = domainMidPoint - offset;
maxXY.x = domainMidPoint + offset;
float newSpan = maxXY.x - minXY.x;
if (newSpan < (float)5) {
minXY.x = oldMin;
maxXY.x = oldMax;
}
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan * zoomRatio;
if (maxXY.x > series1.getX(series1.size() - 1).floatValue())
maxXY.x = rightBoundary;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan * zoomRatio;
if (minXY.x < leftBoundary) minXY.x = leftBoundary;
}
}
private void scroll(float pan) {
float domainSpan = maxXY.x - minXY.x;
float step = domainSpan / plotOne.getWidth();
float offset = pan * step;
minXY.x = minXY.x + offset;
maxXY.x = maxXY.x + offset;
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan;
}
}
private float spacing(MotionEvent
event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
}
I suffer similar problems to yours when using the library usb-serial-for-android. I write bytes to the serial port but my Arduino could not get any signal. After a while I discovered the AndroidApp DroidTerm can do what I want straightforwardly. It uses https://github.com/felHR85/UsbSerial as the serial port driver library for DroidTerm. I discovered that this library supports the Silicon Lab CP21xx UART and some more:
..Devices supported Currently UsbSerial supports three of the most used
USB to serial chipsets:
– FTDI FT232 (I am not going to brick your device, trust me :))
– Silicon Labs CP210x
– Prolific PL2303HX (at least HX version)
– CH340/CH341..
So it may solve your problem.