How to add AlertDialog in my AndroNoise - android

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));
}
}
}

Related

while retreiving contacts again on onResume, last contact is re-added on first card in recycler view

I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.

Open a actvity when a if statement comes true

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);

Android Listview new item at top

I have a Listview. I want to order it such that when new item added they add at top. I try
Collections.reverse(ListElementsArrayList);
And it works. But after (second,third click,....) it mix all earlier item.Is this possible. If yes help me.
My MainActivity is
package com.pradeep.ap;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class AP extends AppCompatActivity {
EditText A, B, D, N, AN;
Button a, b, d, n, an, AP, GP, HP;
int Count = 0;
ListView LV;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ap);
A = (EditText) findViewById(R.id.eta);
B = (EditText) findViewById(R.id.etb);
D = (EditText) findViewById(R.id.etd);
N = (EditText) findViewById(R.id.etn);
AN = (EditText) findViewById(R.id.etan);
AP = (Button) findViewById(R.id.apap);
GP = (Button) findViewById(R.id.apgp);
HP = (Button) findViewById(R.id.aphp);
a = (Button) findViewById(R.id.a);
b = (Button) findViewById(R.id.b);
d = (Button) findViewById(R.id.d);
n = (Button) findViewById(R.id.n);
an = (Button) findViewById(R.id.an);
LV = (ListView) findViewById(R.id.lv);
handler = new Handler();
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(AP.this,android.R.layout.simple_list_item_1,
ListElementsArrayList);
LV.setAdapter(adapter);
adapter.notifyDataSetChanged();
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numb = 0;
float numd = 0;
float numleal=0;
float result = 0;
int Result;
if (TextUtils.isEmpty(B.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())) {
return;
}
numb = Float.parseFloat(B.getText().toString());
numd = Float.parseFloat(D.getText().toString());
ListElementsArrayList.add(" First term of AP is = " + A.getText().toString());
result = numb - numd;
Count = LV.getAdapter().getCount() + 1;
Result = (int) result;
A.setText("" + Result);
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float result = 0;
int Result;
Count = LV.getAdapter().getCount() + 1;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
result = numa + numd;
Result = (int) result;
B.setText("" + Result);
ListElementsArrayList.add(" Second term of AP is = " + B.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numb = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(B.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numb = Float.parseFloat(B.getText().toString());
result = numb - numa;
Result = (int) result;
Count = LV.getAdapter().getCount() + 1;
D.setText("" + Result);
ListElementsArrayList.add(" Value of D is = " + D.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float numan = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())
|| TextUtils.isEmpty(AN.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
numan = Float.parseFloat(AN.getText().toString());
result = ((numan - numa) / numd) + 1;
Result = (int) result;
Count = LV.getAdapter().getCount() + 1;
N.setText("" + Result);
ListElementsArrayList.add(" Number of term/terms in this AP is = " + N.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
an.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float numn = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())
|| TextUtils.isEmpty(N.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
numn = Float.parseFloat(N.getText().toString());
result = ((numn - 1) * numd) + numa;
Result = (int) result;
AN.setText("" + Result);
Count = LV.getAdapter().getCount() + 1;
ListElementsArrayList.add(" Term/Terms of this AP is = " + AN.getText().toString());
adapter.notifyDataSetChanged();
adapter.getCount();
Collections.reverse(ListElementsArrayList);
}
});
}
}
Just use
List.add(0, element)
to add an element as first element of a list. As described in the documentation.

App rate snipit

I am trying to use a code snipit from here:
http://www.androidsnippets.com/prompt-engaged-users-to-rate-your-app-in-the-android-market-appirater
When the code is put into my app I have this:
package com.example.beerportfoliopro;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AppRater {
private final static String APP_TITLE = "YOUR-APP-NAME";
private final static String APP_PNAME = "YOUR-PACKAGE-NAME";
private final static int DAYS_UNTIL_PROMPT = 3;
private final static int LAUNCHES_UNTIL_PROMPT = 7;
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
}
// see http://androidsnippets.com/prompt-engaged-users-to-rate-your-app-in-the-android-market-appirater
I imported all the libraries needed but am getting a few errors at this piece of code:
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
The error is at &gt and at the )) on this line:
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000))
the first error says:
Cannot resolve symbol 'gt'
and the second error is:
';'expected unexpected token
Not sure what is wrong since it was taken straight from the snipit.
Replace > with >
> got encoded for display on a webpage as > but didn't get unencoded when you copied the code.

Android app Mini4WD Lap Timer that uses camera as a sensor

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.. :)

Categories

Resources