start audio clip in background in android at a particular time - android

I am creating an android app in which I want to put clock ticking sound in the background and that too for last few seconds.
the audio is for 21 sec and i too want it to be played in last 21 seconds of the timer. The actual timer is running for 2 minutes.
I was trying the following code :
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
millis = millisUntilFinished;
if(millis == 21000){
mp1.start();
}
hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
timer.setText(hms);
}
where mp1 is :
mp1 = MediaPlayer.create(AnimalMain.this,R.raw.tick_tock);
But nothing is getting played. Also, I am getting the error in the log cat as :
should have subtitle controller already set
I tried many of the stackoverflow links with the same issue but could not resolve it using them. Please Help.
For any reference, please see the entire code here:
package com.example.jumboquest;
import android.app.Activity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.media.MediaPlayer;
public class AnimalMain extends Activity {
TextView timer, roundStatus;
ListView jum;
ProgressBar prog;
EditText ans;
ToggleButton pause;
String s,hms,hmso;
int[] a;
Button next;
static long millis;
static CountDownTimer t;
long toggleValue;
String[] s1 = new String[4];
static ArrayList<String> words;
static ArrayAdapter<String> aa;
static int progressStatus = 0;
//Button match;
static long resumeTsp;
static boolean phoneRinging = false;
static int scorekeeper;
static int rnd_counter;
boolean bonus = false;
long bonus_millis = 0;
MediaPlayer mp1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
rnd_counter++;
setContentView(R.layout.screen2);
resumeTsp = 120000;
jum = (ListView)findViewById(R.id.jum);
ans = (EditText)findViewById(R.id.ans);
timer = (TextView)findViewById(R.id.timer);
roundStatus = (TextView)findViewById(R.id.desc);
prog = (ProgressBar)findViewById(R.id.prog);
//match = (Button) findViewById(R.id.button1);
mp1 = MediaPlayer.create(AnimalMain.this,R.raw.tick_tock);
roundStatus.setText("Round:" +rnd_counter);
Intent intnt = getIntent();
progressStatus = intnt.getIntExtra("prog", 0);
new Thread(new Runnable(){
public void run(){
prog.setProgress(progressStatus);
try{
Thread.sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
}
}).start();
// Create the array list of to do items
words = new ArrayList<String>();
// Create the array adapter to bind the array to the listview
aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,words);
// Bind the array adapter to the listview.
jum.setAdapter(aa);
InputStream i = this.getResources().openRawResource(R.raw.first_round);
String line = null;
int currentLineNo = 1;
int min = 1;
int max = 49;
int startLine = 0;
int endLine = 0;
Random rand = new Random();
switch(rnd_counter){
case 1:
min = 1;
max = 28;
break;
case 2:
min = 32;
max = 59;
break;
case 3:
min = 63;
max = 92;
break;
}
int r = rand.nextInt((max - min) + 1) + min;
startLine = r;
endLine = r+3;
BufferedReader in = null;
try {
in = new BufferedReader (new InputStreamReader(i));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
++currentLineNo;
}
int i1=0;
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
s1[i1]=line;
//= new StringBuffer(line).reverse().toString();
List<Character> jumble = new ArrayList<Character>();
StringBuilder sample = new StringBuilder(line.length());
for(char c : line.toCharArray()){
jumble.add(c);
}
//int flag_first = 0;
while(jumble.size() != 0){
int rnd = (int)(Math.random()*jumble.size());
if(rnd == 0 && jumble.size() == line.length()){
continue;
}
else{
sample.append(jumble.remove(rnd));
}
}
words.add(sample.toString());
aa.notifyDataSetChanged();
++i1;
++currentLineNo;
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
a = new int[4];
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = 0;
/* match.setOnClickListener(new OnClickListener(){
public void onClick(View v){
String answer = ans.getText().toString();
if(answer.equalsIgnoreCase(s1[0])){
words.remove(0);
aa.notifyDataSetChanged();
words.add(0,answer);
aa.notifyDataSetChanged();
}
else if(answer.equalsIgnoreCase(s1[1])){
words.remove(1);
aa.notifyDataSetChanged();
words.add(1,answer);
aa.notifyDataSetChanged();
}
else if(answer.equalsIgnoreCase(s1[2])){
words.remove(2);
aa.notifyDataSetChanged();
words.add(2,answer);
aa.notifyDataSetChanged();
}
else if(answer.equalsIgnoreCase(s1[3])){
words.remove(3);
aa.notifyDataSetChanged();
words.add(3,answer);
aa.notifyDataSetChanged();
}
}
});*/
jum.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String selected = jum.getItemAtPosition(arg2).toString();
s= ans.getText().toString();
if(s.equals(s1[arg2]))
{
a[arg2]=1;
//Toast.makeText(getApplicationContext(), "CORRECT!! Now Crack the Next One.. :) ", Toast.LENGTH_SHORT).show();
words.remove(arg2);
aa.notifyDataSetChanged();
words.add(arg2,s);
aa.notifyDataSetChanged();
arg1.setEnabled(false);
ans.setText("");
if(a[0]==1 && a[1]==1 && a[2]==1 && a[3]==1)
{
t.cancel();
if(millis >= 60000){
bonus = true;
bonus_millis = (millis/1000)-60;
}
//scorekeeper += 40;
Intent i=new Intent(getApplicationContext(), AnimalDatabase.class);
i.putExtra("milli", millis);
i.putExtra("score", scorekeeper);
i.putExtra("bonus", bonus);
i.putExtra("round", rnd_counter);
i.putExtra("bonus_score",bonus_millis);
//i.putExtra("progress",progressStatus);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//Toast.makeText(getApplicationContext(), "WELL DONE!! All the best for the quiz :) ", Toast.LENGTH_LONG).show();
// finish();
}
}
else
{
ans.setText(s);
Toast.makeText(getApplicationContext(), "INCORRECT :( Try Again.. ", Toast.LENGTH_SHORT).show();
}
}
});
TelephonyManager telephonyManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING){
resumeTsp = millis;
t.cancel();
timer.setText("Game Paused!");
Toast.makeText(getApplicationContext(),"Phone Is Riging",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(getApplicationContext(),"Phone is Currently in A call",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_IDLE){
t = new StartTimer(resumeTsp,1000);
t.start();
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
#Override
public void onBackPressed(){
return;
}
class StartTimer extends CountDownTimer{
public StartTimer(long duration, long interval){
super(duration, interval);
}
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
millis = millisUntilFinished;
//if(millis == 21000){
// Toast.makeText(getApplicationContext(), String.valueOf(millis), Toast.LENGTH_SHORT).show();
// mp1.start();
//}
hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
timer.setText(hms);
}
#Override
public void onFinish() {
//time up
phoneRinging = false;
timer.setText("TIME UP!");
mp1.stop();
ans.setEnabled(false);
for(int j = 0; j<4;j++){
timer.setText("SOLUTION:");
words.remove(j);
aa.notifyDataSetChanged();
words.add(j,s1[j]);
aa.notifyDataSetChanged();
}
}
}
}

It can be done by simply adding delay instead of checking timer value in the OnTick() which will not work. The delay can be added in the following way :
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
mp1.start();
mp1.setLooping(true);
}
}, 100000);
put the delay after which you want to start the audio in background and it worked in my case.

Related

Android Realtime Signal not smooth using graphview library

Iam trying to plot realtime signal from arduino to my android tablet. I've using a potentiometer for testing purpose and ADC sampling rate is 256Hz.
My issue is that the graph plotted on the android app is not smooth. The serial communication is working properly but the plotting is not very good.It feels like the App is lagging and it lags further as the data gets plotted.
Below is the app image
app screenshot
package com.example.ecgauth;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
//import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.LegendAlign;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener{
private static final String ACTION_USB_PERMISSION = "com.example.ecg.USB_PERMISSION";
TextView hr_value_text;
UsbDevice device;
UsbDeviceConnection connection;
UsbManager usbManager;
UsbSerialDevice serialPort;
PendingIntent pendingIntent;
// private Handler mHandler;
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
final static int gMAX_BLOCKS = 32; //Maximum blocks
final static int gMAX_SAMPLES = 8; //'Maximum samples
final static int gMAX_CHANNELS = 4; //'Maximum channels
final static int gSampFreq = 256; //Sampling frequency
final static int gRawBufferSize = gMAX_BLOCKS * gMAX_SAMPLES ;
final static float swpfactor = 0;
final static int gSec =0;
int sample =0;
private static boolean acq1 = false;
static int block =0;
int g_intRawBuffer[][] = new int[gMAX_BLOCKS][gMAX_SAMPLES];
double g_sngDnOutBuf[] = new double[gMAX_SAMPLES ];
#Override
public void onBackPressed() {
// // TODO Auto-generated method stub
// if (Bluetooth.connectedThread != null) {
// Bluetooth.connectedThread.write("Q");}//Stop streaming
super.onBackPressed();
}
//toggle Button
static boolean Lock;//whether lock the x-axis to 0-5
static boolean AutoScrollX;//auto scroll to the last x value
static boolean Stream;//Start or stop streaming
int old_interval=0;
int new_interval=0;
int mean_interval=20;
//Button init
Button bXminus;
Button bXplus;
ToggleButton tbLock;
ToggleButton tbScroll;
ToggleButton tbStream;
boolean startthread = true;
//GraphView init
static LinearLayout GraphView;
static GraphView graphView;
static GraphViewSeries Series;
//graph value
private static double graph2LastXValue = 0;
private static int Xview=1023;
Button bConnect, bDisconnect;
private TextView connectionstatus;
public int control_a = 0;
public int TotalSample=0;
char chdata = 0;
int i =0;
String finaldata = "";
String rawdata = "";
byte highbyte=0;
int data = 0 ;
int plotdata = 0 ;
int databuff = 0;
public int[] buffer_bt = new int[768];
public int[] copy_buffer_bt = new int[768];
public int ind_bt = 0;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
// lowbyte = arg0;
// highbyte = arg0;
byte[] buffer = arg0;
for (int i = 0; i <= (buffer.length - 1); i++) {
if (buffer[i] != 13) {
if (buffer[i] == 10) {
finaldata = rawdata;
rawdata = "";
} else {
chdata = (char) buffer[i];
rawdata += chdata;
}
}
}
data = Integer.parseInt(finaldata);
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
control_a = 1;
buffer_bt[databuff] = data;
// }
//lowbyte = buffer;
//highbyte = buffer;
databuff = databuff + 1;
if (databuff == 767){
databuff=0;
}
//
// for (int uu=0; uu<=767; uu++) {
// copy_buffer_bt[uu] = buffer_bt[uu];
// }
// databuff=0;
// ready_bt=1;
// threadon = true;
// }
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);//Hide title
this.getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//Hide Status bar
setContentView(R.layout.activity_main);
//set background color
LinearLayout background = (LinearLayout)findViewById(R.id.bg);
background.setBackgroundColor(Color.BLACK);
// mHandler = new Handler();
//GraphView = (LinearLayout) findViewById(R.id.Graph);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
connectionstatus = (TextView) findViewById(R.id.tvBluetooth);
bConnect = (Button)findViewById(R.id.bConnect);
bConnect.setOnClickListener(this);
bDisconnect = (Button)findViewById(R.id.bDisconnect);
bDisconnect.setOnClickListener(this);
//X-axis control button
bXminus = (Button)findViewById(R.id.bXminus);
bXminus.setOnClickListener(this);
bXplus = (Button)findViewById(R.id.bXplus);
bXplus.setOnClickListener(this);
//
tbLock = (ToggleButton)findViewById(R.id.tbLock);
tbLock.setOnClickListener(this);
tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
tbScroll.setOnClickListener(this);
tbStream = (ToggleButton)findViewById(R.id.tbStream);
tbStream.setOnClickListener(this);
//init toggleButton
Lock=true;
AutoScrollX=true;
Stream=true;
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
init();
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted =
intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
//setUiEnabled(true); //Enable Buttons in UI
serialPort.setBaudRate(57600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback); //
//connectionstatus.setText("Connected");
tvAppend(connectionstatus, " Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
}
} else {
Log.d("SERIAL", "PORT IS NULL");
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onConnect(bConnect);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
// onClickStop(buttonRestart);
}
}
};
public void onConnect(View view){
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID == 0x10C4)//Arduino Vendor ID//0x10C4 cp2102 VID
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
private void tvAppend (TextView tv, CharSequence text){
connectionstatus.setText(" ");
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
void init(){
//Bluetooth.gethandler(mHandler);
//init graphview
GraphView = (LinearLayout) findViewById(R.id.Graph);
// init example series data-------------------
Series = new GraphViewSeries("Signal",
new GraphViewStyle(Color.YELLOW, 2),//color and thickness of the line
new GraphViewData[] {new GraphViewData(0, 0)});
graphView = new LineGraphView(
this // context
, "Electrocardiogram AUTH" // heading
);
graphView.setViewPort(0, Xview);
graphView.setScrollable(true);
graphView.setScalable(false);
graphView.setShowLegend(false);
//graphView.setLegendAlign(LegendAlign.BOTTOM);
graphView.setManualYAxis(true);
graphView.setManualYAxisBounds(2560, 0);
graphView.addSeries(Series); // data
GraphView.addView(graphView);
}
Handler mHandler = new Handler(){
#Override
public void handleMessage(#NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MESSAGE_FROM_SERIAL_PORT:
plotdata = data;
g_intRawBuffer[block][TotalSample] = plotdata;
TotalSample = TotalSample+1;
if (TotalSample == 8) {
TotalSample = 0;
for (int sample = 0; sample <= (gMAX_SAMPLES - 1); sample++) {
g_sngDnOutBuf[sample] = g_intRawBuffer[block][sample];
}
for (int sample = 0; sample <= (gMAX_SAMPLES - 1); sample++) {
Series.appendData(new GraphViewData(graph2LastXValue, g_sngDnOutBuf[sample]), AutoScrollX);
if (graph2LastXValue >= Xview && Lock == true) {
Series.resetData(new GraphViewData[]{});
graph2LastXValue = 0;
}else
graph2LastXValue += 0.5;
if (Lock == true)
graphView.setViewPort(0, Xview);
else
graphView.setViewPort(graph2LastXValue - Xview, Xview);
//refresh
GraphView.removeView(graphView);
GraphView.addView(graphView);
}
}
}
}
};
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bConnect:
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID == 0x2341)//Arduino Vendor 2341 ID//0x10C4 cp2102 VID
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
}
break;
case R.id.bDisconnect:
serialPort.close();
tvAppend(connectionstatus, "Serial Connection Closed!\n");
break;
case R.id.bXminus:
if (Xview<30) Xview++;
break;
case R.id.bXplus:
if (Xview>1) Xview--;
break;
case R.id.tbLock:
if (tbLock.isChecked()){
Lock = true;
}else{
Lock = false;
}
break;
case R.id.tbScroll:
if (tbScroll.isChecked()){
AutoScrollX = true;
}else{
AutoScrollX = false;
}
break;
case R.id.tbStream:
if (tbStream.isChecked()){
serialPort.write("a".getBytes());
}else{
serialPort.write("z".getBytes());
control_a = 0;
}
break;
}
}
}

how to type letter from right to left in android eclipse project

i am trying to reskin an app ( riddle me that )
wheen typing the response the response begin from left to right
i want it to begin from right to left
the answer is in arabic so it has to be from right to left
this how the answer is typed
i want it to be typed like this
this is my activity.java
package com.gkcrop.riddlemethat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.loopj.android.image.SmartImageView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class TheGame extends Activity {
// Variables
InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "ا", "ب", "ت", "ث", "د", "ذ", "ر", "ز", "س","ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ك", "م", "ن", "ه","و", "ي", "ة", "ئ" };
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
Context mContext;
String TextFile,Ribbon;
TextView txt_ribon,txt_riddle;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean isLast=false;
StringBuilder sb;
private int winSound;
private int failureSound;
private int clickSound;
SoundPool sounds;
EarnCoin coin;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
coin=new EarnCoin(getApplicationContext());
initSounds();
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
txt_riddle=(TextView)findViewById(R.id.txt_riddle);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
if(!isLast)
{
txt_riddle.setText(TextFile);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
if (Integer.parseInt(lvl) % Integer.parseInt(getString(R.string.number_of_stage_ad)) == 0) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intertestial_id));
interstitial.loadAd(new AdRequest.Builder().build());
interstitial.show();
if (!interstitial.isLoaded()) {
AdRequest adRequest1 = new AdRequest.Builder()
.build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest1);
}
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
interstitial.show();
}
});
}
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
File imagepath=new File(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagepath));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initSounds()
{
setVolumeControlStream(3);
sounds = new SoundPool(4, 3, 0);
winSound = sounds.load(this,R.raw.win, 1);
failureSound = sounds.load(this, R.raw.failure, 1);
clickSound = sounds.load(this, R.raw.click2, 1);
}
private void playSound(int i)
{
if (coin.isSoundEnabled())
{
sounds.play(i, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(20);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x].toUpperCase());
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
playSound(clickSound);
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord += word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
playSound(winSound);
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
playSound(failureSound);
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
TextFile=level.getTextId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
}
You need to enable bidirectional text direction.
As usual click Window > Preferences > General > Globalization > Enable bidirectional support. Don't forget to restart your eclipse for it to take effect.

Why does my application crash sometimes?

All,
I would greatly appreciate some help. We have a system that is being sent data at 2 Hz (every 0.5 sec). My application is supposed to start acquiring this data upon the press of a "start" button through a handler, and upon pressing the "stop" button, the user can choose to save the data collected. If save is chosen, a new activity is SUPPOSED to be started, however, my application crashes. The error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(int)' on a null object reference
at com.example.cherryjp.buttonapp.StartNewSessionActivity$2.onClick(StartNewSessionActivity.java:130)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
and my code:
package com.example.cherryjp.buttonapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Set;
import java.util.Timer;
import java.util.UUID;
/**
*/
public class StartNewSessionActivity extends AppCompatActivity {
final int MSG_START_TIMER = 0;
final int MSG_STOP_TIMER = 1;
final int MSG_UPDATE_TIMER = 2;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
long startTime;
Double endTime;
TextView watch;
Double totalSeconds;
Double seconds;
Double minutes;
Double hours;
String time;
boolean recording = false;
String fromBluetooth;
BluetoothAdapter mBluetoothAdapter;
ArrayAdapter mArrayAdapter;
final Context context = this;
final int REFRESH_RATE = 100;
Stopwatch timer = new Stopwatch();
Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
watch.setText("" + timer.toString());
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER, REFRESH_RATE); //text view is updated every second,
if(writeBuf == null){
break;
}
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
fromBluetooth += writeMessage;
fromBluetooth += "\t";
break;
//though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
//send reset signal for bluetooth
if(recording) {
launchSaveDialog();
}
recording = false;
watch.setText("" + timer.toString());
break;
default:
break;
}
}
};
private BluetoothDevice mDevice;
public void launchSaveDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to save that run?")
.setTitle("Save confirmation");
AlertDialog.Builder builder1 = builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Entry entry = new Entry();
entry.setDate(MySQLiteHelper.getCurrentDateTime(context));
entry.setRiderId(getIntent().getExtras().getLong("RIDER_ID"));
//TODO: loop to pull values from bluetooth transmission
//String fromBluetooth = "5\t1\t3\t2\t5\t3\t3\t4";
String tempString = fromBluetooth;
tempString = fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
entry.setForceAndTimeTabSeparated(tempString);
MainActivity.riderdb.addEntry(entry);
Toast.makeText(getApplicationContext(),
"Run saved!", Toast.LENGTH_SHORT).show();
showGraph(entry);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void showGraph(Entry entry){
Intent immediateGraphIntent = new Intent(this, ImmediateGraph.class);
final int result = 1;
//Just getEntry on next intent instead of storing extras.
immediateGraphIntent.putExtra("ENTRY_ID", entry.getId());
//immediateGraphIntent.putExtra("PASSTIME", timeArray);
//immediateGraphIntent.putExtra("PASSFORCE", forceArray);
startActivity(immediateGraphIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.session_start_page);
Button startButton = (Button) findViewById(R.id.startsessionbutton);
Button endButton = (Button) findViewById(R.id.endsessionbutton);
watch = (TextView)findViewById(R.id.watch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
final ConnectThread mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//START recording stuff.
recording = true;
while(mConnectThread.mConnectedThread == null){
}
mConnectThread.mConnectedThread.write("begin".getBytes());
mHandler.sendEmptyMessage(MSG_START_TIMER);
}
});
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//END recording stuff
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
});
}
public class Stopwatch {
private long startTime = 0;
private boolean running = false;
private long currentTime = 0;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.running = false;
}
public void pause() {
this.running = false;
currentTime = System.currentTimeMillis() - startTime;
}
public void resume() {
this.running = true;
this.startTime = System.currentTimeMillis() - currentTime;
}
//elaspsed time in milliseconds
public long getElapsedTimeMili() {
long elapsed = 0;
if (running) {
elapsed =((System.currentTimeMillis() - startTime)/100) % 10 ;
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed = 0;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000) % 60;
}
return elapsed;
}
//elaspsed time in minutes
public long getElapsedTimeMin() {
long elapsed = 0;
if (running) {
elapsed = (((System.currentTimeMillis() - startTime) / 1000) / 60 ) % 60;
}
return elapsed;
}
//elaspsed time in hours
public long getElapsedTimeHour() {
long elapsed = 0;
if (running) {
elapsed = ((((System.currentTimeMillis() - startTime) / 1000) / 60 ) / 60);
}
return elapsed;
}
public String toString() {
return String.format("%1$02d:%2$02d:%3$02d.%4$01d", getElapsedTimeHour(), getElapsedTimeMin(), getElapsedTimeSecs(), getElapsedTimeMili());
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private ConnectedThread mConnectedThread;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "\n".getBytes()[0]) {
mHandler.obtainMessage(MSG_UPDATE_TIMER, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Any thoughts on this? I'm completely out of ideas on what is causing this to crash... something with the bluetooth connectivity, maybe?
Thanks,
John
fromBluetooth is null, and you can't call indexOf(...) on a null String.
You must therefore ensure that fromBluetooth isn't null (good) or handle the case where fromBluetooth is null (better) (e.g. if (fromBluetooth != null) execute logic).
Enjoy
Replace your code
if(fromBluetooth!=null){
tempString = fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
}
with
fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
because you not checking string is null or not and directly findvalue using indexOf();

change the direction of chapters typing

I want to change direction of typing letter from Left To RIGHT
this is Image of this game
this is image of the game:
http://img11.hostingpics.net/pics/357754Capturedcran20150407103535.png
Normally when i type letter it will be in left case , I want to change it to right case
package com.gkcrop.riddlemethat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.loopj.android.image.SmartImageView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class TheGame extends Activity {
// Variables
InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
Context mContext;
String TextFile,Ribbon;
TextView txt_ribon,txt_riddle;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean isLast=false;
StringBuilder sb;
private int winSound;
private int failureSound;
private int clickSound;
SoundPool sounds;
EarnCoin coin;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
coin=new EarnCoin(getApplicationContext());
initSounds();
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
txt_riddle=(TextView)findViewById(R.id.txt_riddle);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
if(!isLast)
{
txt_riddle.setText(TextFile);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
if (Integer.parseInt(lvl) % Integer.parseInt(getString(R.string.number_of_stage_ad)) == 0) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intertestial_id));
interstitial.loadAd(new AdRequest.Builder().build());
interstitial.show();
if (!interstitial.isLoaded()) {
AdRequest adRequest1 = new AdRequest.Builder()
.build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest1);
}
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
interstitial.show();
}
});
}
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
File imagepath=new File(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagepath));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initSounds()
{
setVolumeControlStream(3);
sounds = new SoundPool(4, 3, 0);
winSound = sounds.load(this,R.raw.win, 1);
failureSound = sounds.load(this, R.raw.failure, 1);
clickSound = sounds.load(this, R.raw.click2, 1);
}
private void playSound(int i)
{
if (coin.isSoundEnabled())
{
sounds.play(i, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x].toUpperCase());
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
playSound(clickSound);
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord += word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
playSound(winSound);
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
playSound(failureSound);
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
TextFile=level.getTextId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
}

DatagramSocket.receive only receives the first two Datagrams

I am sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.

Categories

Resources