some mistakes on creating application - android

I'm learning how to create app with android studio,
this is my code source:
package com.example.droide;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class DroideSphereRuhlmannActivity extends Activity implements OnClickListener {
private TextView logview;
private Button connect, deconnect;
private ImageView forwardArrow, backArrow, rightArrow, leftArrow, stop, topleftArrow, toprightArrow, backleftArrow, backrightArrow;
private BluetoothAdapter mBluetoothAdapter = null;
private String[] logArray = null;
private BtInterface bt = null;
static final String TAG = "Droid";
static final int REQUEST_ENABLE_BT = 3;
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String data = msg.getData().getString("receivedData");
addToLog(data);
}
};
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg) {
int status = msg.arg1;
if(status == BtInterface.CONNECTED) {
addToLog("Connected");
} else if(status == BtInterface.DISCONNECTED) {
addToLog("Disconnected");
}
}
};
private void addToLog(String message){
for (int i = 1; i < logArray.length; i++){
logArray[i-1] = logArray[i];
}
logArray[logArray.length - 1] = message;
logview.setText("");
for (int i = 0; i < logArray.length; i++){
if (logArray[i] != null){
logview.append(logArray[i] + "\n");
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_remote);
logview = (TextView)findViewById(R.id.logview);
logArray = new String[3];
connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(this);
deconnect = (Button)findViewById(R.id.deconnect);
deconnect.setOnClickListener(this);
forwardArrow = (ImageView)findViewById(R.id.forward_arrow);
forwardArrow.setOnClickListener(this);
backArrow = (ImageView)findViewById(R.id.back_arrow);
backArrow.setOnClickListener(this);
rightArrow = (ImageView)findViewById(R.id.right_arrow);
rightArrow.setOnClickListener(this);
leftArrow = (ImageView)findViewById(R.id.left_arrow);
leftArrow.setOnClickListener(this);
stop = (ImageView)findViewById(R.id.stop);
stop.setOnClickListener(this);
topleftArrow = (ImageView)findViewById(R.id.topleft_arrow);
topleftArrow.setOnClickListener(this);
toprightArrow = (ImageView)findViewById(R.id.topright_arrow);
toprightArrow.setOnClickListener(this);
backrightArrow = (ImageView)findViewById(R.id.backright_arrow);
backrightArrow.setOnClickListener(this);
backleftArrow = (ImageView)findViewById(R.id.backleft_arrow);
backrightArrow.setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.v(TAG, "Device does not support Bluetooth");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
bt = new BtInterface(handlerStatus, handler);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent moreData){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
bt = new BtInterface(handlerStatus, handler);
}
else if (resultCode == Activity.RESULT_CANCELED)
Log.v(TAG, "BT pas active");
else
Log.v(TAG, "code n'est pas valide");
}
else{
Log.v(TAG, "code n'est pas reconnu");
}
}
#Override
public void onClick(View v) {
if(v == connect) {
addToLog("Appareillage en cours");
bt.connect();
}
else if(v == deconnect) {
addToLog("connexion en cours");
bt.close();
}
else if(v == forwardArrow) {
bt.sendData("F");
}
else if(v == backArrow) {
bt.sendData("B");
}
else if(v == rightArrow) {
bt.sendData("R");
}
else if(v == leftArrow) {
bt.sendData("L");
}
else if( v == topleftArrow){
bt.sendData("I");
}
else if(v == toprightArrow){``
bt.sendData("J");
}
else if(v == backleftArrow){
bt.sendData("G");
}
else if(v ==backrightArrow){
bt.sendData("H");
}
else if(v == stop) {
bt.sendData("S");
}
Error Log:
After that, I got some error like :
"Error:(156, 10) error: reached end of file while parsing"
or
"Error:Execution failed for task ':app:compileDebugJavaWithJavac'."
So now I don't now how to solve that.

If this is your full code then your onClick method has not ending curly bracket and also your main class is not ended with curly bracket.
so add two ending curly braces at end of your code

Related

Google Achievements Unlock But Don't Save

I added achievements to my Google Play game following Google's tutorial. They unlock fine and if I display achievements in-game immediately they show up. If I quit the game and go to the Google Game's app they don't show up and they disappear from in-game also. Any ideas? I've tried multiple accounts. Thanks!
package com.b1stable.tth;
import java.io.File;
import java.io.FileFilter;
import java.util.Locale;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.FileSystems;
import java.util.Vector;
import android.os.Bundle;
import android.os.Build;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Vibrator;
import android.os.VibrationEffect;
import android.util.Log;
import android.view.Surface;
import android.view.Gravity;
import org.libsdl.app.SDLActivity;
import com.b1stable.tth.License_Viewer_Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.games.AchievementsClient;
import com.google.android.gms.games.AnnotatedData;
import com.google.android.gms.games.EventsClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.PlayersClient;
import com.google.android.gms.games.event.Event;
import com.google.android.gms.games.event.EventBuffer;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Task.*;
public class TTH_Activity extends SDLActivity
{
final static int LICENSE_REQUEST = 1;
native static void resume_after_showing_license();
native static void resume_after_showing_achievements();
native static void pause();
native static void resume();
// Client used to sign in with Google APIs
private GoogleSignInClient mGoogleSignInClient;
private AchievementsClient mAchievementsClient = null;
private boolean signin_failed = false;
// request codes we use when invoking an external activity
private static final int RC_UNUSED = 5001;
private static final int RC_SIGN_IN = 9001;
// This is so the screen is never cleared pure black, only shim::black (r:35, g:30, b:60)
static boolean paused = false;
private static final String TAG = "TTH";
#Override
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LICENSE_REQUEST) {
if (data != null) {
if (resultCode == RESULT_OK && data.getExtras().getString("MESSAGE").equals("OK")) {
show_license_result = 0;
}
else if (resultCode == RESULT_CANCELED && data.getExtras().getString("MESSAGE").equals("FAIL")) {
show_license_result = 1;
}
else {
show_license_result = 1;
}
}
else {
show_license_result = 1;
}
resume_after_showing_license();
}
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
onConnected(signedInAccount);
}
else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "An error occurred!";
}
new AlertDialog.Builder(this).setMessage(message).setNeutralButton(android.R.string.ok, null).show();
onDisconnected();
}
}
}
public void onStart() {
super.onStart();
}
#Override
public void onStop()
{
super.onStop();
pause();
}
#Override
public void onRestart()
{
super.onRestart();
resume();
}
#Override
public void onResume()
{
super.onResume();
signInSilently();
}
#Override
public void onPause()
{
super.onPause();
mAchievementsClient = null;
}
#Override
public void onPostResume()
{
super.onPostResume();
paused = true;
}
public void logString(String s)
{
Log.d("TTH", s);
}
public String getAppdataDir()
{
return getFilesDir().getAbsolutePath();
}
public String getSDCardDir()
{
File f = getExternalFilesDir(null);
if (f != null) {
return f.getAbsolutePath();
}
else {
return getFilesDir().getAbsolutePath();
}
}
static int show_license_result;
public void showLicense()
{
show_license_result = -1;
Intent intent = new Intent(this, License_Viewer_Activity.class);
startActivityForResult(intent, LICENSE_REQUEST);
}
public int getShowLicenseResult()
{
return show_license_result;
}
/*
public void openURL(String url)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
*/
public void rumble(int milliseconds)
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null && v.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
}
else {
v.vibrate(milliseconds);
}
}
}
public boolean has_touchscreen()
{
return getPackageManager().hasSystemFeature("android.hardware.touchscreen");
}
public boolean has_vibrator()
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
return v.hasVibrator();
}
else {
return false;
}
}
public void start_draw()
{
if (paused) {
paused = false;
}
}
public String get_android_language()
{
return Locale.getDefault().getLanguage();
}
private static File[] list_dir_files = null;
public void list_dir_start(String path)
{
try {
int slash = path.lastIndexOf('/');
final String glob = path.substring(slash+1).replace("*", ".*"); // +1 works even if not found (-1+1 == 0)
String dir = path.substring(0, slash);
File f = new File(dir);
list_dir_files = f.listFiles(new FileFilter() {
public boolean accept(File f)
{
try {
if (f.getName().matches(glob)) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
Log.d("TTH", "list_dir_start FileFilter throwing " + e.getMessage());
return false;
}
}
});
}
catch (Exception e) {
list_dir_files = null;
Log.d("TTH", "list_dir_start throwing " + e.getMessage());
}
}
public String list_dir_next()
{
if (list_dir_files == null) {
return "";
}
else if (list_dir_files.length == 0) {
list_dir_files = null;
return "";
}
else {
File f = list_dir_files[0];
String name = f.getName();
if (list_dir_files.length == 1) {
list_dir_files = null;
}
else {
File[] new_list = new File[list_dir_files.length-1];
for (int i = 1; i < list_dir_files.length; i++) {
new_list[i-1] = list_dir_files[i];
}
list_dir_files = new_list;
}
return name;
}
}
private static final String ARC_DEVICE_PATTERN = ".+_cheets|cheets_.+";
public boolean is_chromebook()
{
// Google uses this, so should work?
return Build.DEVICE != null && Build.DEVICE.matches(ARC_DEVICE_PATTERN);
}
private static final int RC_ACHIEVEMENT_UI = 9003;
public boolean show_achievements()
{
if (mAchievementsClient == null) {
return false;
}
mAchievementsClient.getAchievementsIntent().addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, RC_ACHIEVEMENT_UI);
resume_after_showing_achievements();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
resume_after_showing_achievements();
}
}).addOnCompleteListener(new OnCompleteListener<Intent>() {
#Override
public void onComplete(Task<Intent> task) {
resume_after_showing_achievements();
}
});
return true;
}
public void achieve(String id)
{
if (mAchievementsClient != null) {
mAchievementsClient.unlock(id);
}
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
private void signInSilently() {
if (signin_failed == true || mAchievementsClient != null) {
return;
}
GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
// Already signed in.
// The signed in account is stored in the 'account' variable.
//GoogleSignInAccount signedInAccount = account;
onConnected(account);
}
else {
// Haven't been signed-in before. Try the silent sign-in first.
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
signInClient.silentSignIn().addOnCompleteListener(
this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
onConnected(signedInAccount);
}
else {
// Player will need to sign-in explicitly using via UI.
// See [sign-in best practices](http://developers.google.com/games/services/checklist) for guidance on how and when to implement Interactive Sign-in,
// and [Performing Interactive Sign-in](http://developers.google.com/games/services/android/signin#performing_interactive_sign-in) for details on how to implement
// Interactive Sign-in.
startSignInIntent();
}
}
}
);
}
}
public void start_google_play_games_services() {
/*
runOnUiThread(new Runnable() {
public void run() {
signInSilently();
}
});
*/
}
private void onConnected(GoogleSignInAccount googleSignInAccount) {
Log.d(TAG, "onConnected(): connected to Google APIs");
GamesClient gamesClient = Games.getGamesClient(this, googleSignInAccount);
gamesClient.setViewForPopups(findViewById(android.R.id.content));
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
mAchievementsClient = Games.getAchievementsClient(this, googleSignInAccount);
}
private void onDisconnected() {
Log.d(TAG, "onDisconnected()");
mAchievementsClient = null;
signin_failed = true;
}
}

Create Remote HttpServer using nanoHttpd

I am creating a httpserver using NanoHttpd library. When I am running it on local it is working fine. but when i am trying to create httpserver using Hostname.This is giving following Error.
bind failed: EADDRNOTAVAIL (Cannot assign requested address)
Here is My MainActivity
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final int DEFAULT_PORT = 8080;
private AndroidWebServer androidWebServer;
private BroadcastReceiver broadcastReceiverNetworkState;
private static boolean isStarted = false;
private CoordinatorLayout coordinatorLayout;
private EditText editTextPort;
private FloatingActionButton floatingActionButtonOnOff;
private View textViewMessage;
private TextView textViewIpAccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setElevation(0);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
editTextPort = (EditText) findViewById(R.id.editTextPort);
textViewMessage = findViewById(R.id.textViewMessage);
textViewIpAccess = (TextView) findViewById(R.id.textViewIpAccess);
setIpAccess();
floatingActionButtonOnOff = (FloatingActionButton) findViewById(R.id.floatingActionButtonOnOff);
floatingActionButtonOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isConnectedInWifi()) {
if (!isStarted && startAndroidWebServer()) {
isStarted = true;
textViewMessage.setVisibility(View.VISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this, R.color.colorGreen));
editTextPort.setEnabled(false);
} else if (stopAndroidWebServer()) {
isStarted = false;
textViewMessage.setVisibility(View.INVISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this, R.color.colorRed));
editTextPort.setEnabled(true);
}
} else {
Snackbar.make(coordinatorLayout, getString(R.string.wifi_message), Snackbar.LENGTH_LONG).show();
}
}
});
initBroadcastReceiverNetworkStateChanged();
}
private boolean startAndroidWebServer() {
if (!isStarted) {
int port = getPortFromEditText();
try {
if (port == 0) {
throw new Exception();
}
androidWebServer = new AndroidWebServer(8080);
androidWebServer.start();
return true;
} catch (Exception e) {
Log.e("this is exception", e.getMessage());
}
}
return false;
}
private boolean stopAndroidWebServer() {
if (isStarted && androidWebServer != null) {
androidWebServer.stop();
return true;
}
return false;
}
private void setIpAccess() {
textViewIpAccess.setText(getIpAccess());
}
private void initBroadcastReceiverNetworkStateChanged() {
final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
broadcastReceiverNetworkState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setIpAccess();
}
};
super.registerReceiver(broadcastReceiverNetworkState, filters);
}
private String getIpAccess() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
return "http://" + formatedIpAddress + ":";
}
private int getPortFromEditText() {
String valueEditText = editTextPort.getText().toString();
return (valueEditText.length() > 0) ? Integer.parseInt(valueEditText) : DEFAULT_PORT;
}
public boolean isConnectedInWifi() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()
&& wifiManager.isWifiEnabled() && networkInfo.getTypeName().equals("WIFI")) {
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent evt) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isStarted) {
new AlertDialog.Builder(this)
.setTitle(R.string.warning)
.setMessage(R.string.dialog_exit_message)
.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.show();
} else {
finish();
}
return true;
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
stopAndroidWebServer();
isStarted = false;
if (broadcastReceiverNetworkState != null) {
unregisterReceiver(broadcastReceiverNetworkState);
}
}
}
This is my class how I am starting HttpServer
import android.os.Environment;
import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.request.Method;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class AndroidWebServer extends NanoHTTPD {
public AndroidWebServer(int port) {
super(port);
}
public AndroidWebServer(String hostname, int port) {
super(hostname, port);
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
String msg = "<html><body><h1>This is all you should know</h1>\n";
return Response.newFixedLengthResponse(msg);
}
private Response uploadImage() { // this method you can use to upload file(audio,Video aur image)
FileInputStream fis = null;
File file = null;
try {
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg");
fis = new FileInputStream(file.getAbsoluteFile());
return new Response(Status.OK, "image/jpg", fis, file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}

How to get google default tts language in android

i already set google tts language to hindi.And in my code i am setting that hindi as a default language by tts.setLanguage(Locale.getDefault()),my code working fine.But when i am using Locale.getDefault().getDisplayLanguage() to get default language,logcat shows English.
I want to set language according to user.
package com.example.texttospeech;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("unused")
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
EditText ed1,ed2;
Button b1,b2;
AudioManager audioManager;
static final int READ_BLOCK_SIZE = 100;
protected static final int PICKFILE_RESULT_CODE = 1;
protected static final int ACTIVITY_TTS_PASS=1;
#SuppressWarnings("static-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
b1=(Button)findViewById(R.id.button1);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tts = new TextToSpeech(this, this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
audioManager.setStreamVolume(audioManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);
audioManager.setSpeakerphoneOn(true);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked",Toast.LENGTH_SHORT).show();
try {
if(ed1.getText().toString()==null || ed1.getText().toString().matches(""))
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file.txt/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}else
{
savefile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// openfile();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
Locale.getDefault().getDisplayLanguage();
Log.e("--f----f-----f-- ",""+Locale.getDefault().getDisplayLanguage());
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.getDefault());
Log.e("--g----g-----g--",""+result);
tts.setLanguage(new Locale("hi_IN"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED)
{
Log.e("TTS", "This Language is not supported");
}
else {
b1.setEnabled(true);
try {
savefile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void savefile() throws IOException {
String text = ed1.getText().toString();
FileOutputStream fos = null;
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MynewText/" );
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, "newtest" + ".txt");
if (!myFile.exists())
{
myFile.createNewFile();
}
fos = new FileOutputStream(myFile);
fos.write(text.getBytes());
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!",Toast.LENGTH_SHORT).show();
tts.setSpeechRate(0);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
try {
// Read text from file
File sdcard = Environment.getExternalStorageDirectory();
File file1 = new File(sdcard,"MynewText/newtest.txt");
//Read text from file
StringBuilder text1 = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file1));
String line;
while ((line = br.readLine()) != null)
{
text1.append(line);
text1.append('\n');
}
ed2.setText(text1);
br.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case ACTIVITY_TTS_PASS:
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(getApplicationContext(), this);
int availability = tts.isLanguageAvailable(new Locale("hin-IND"));
switch(availability)
{
case TextToSpeech.LANG_AVAILABLE:
Log.d("TTS", "Language available");
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
Log.d("TTS", "Language not supported");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
break;
case TextToSpeech.LANG_MISSING_DATA:
Log.d("TTS", "Language missing data");
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
Log.d("TTS", "Contry available");
break;
default:
Log.d("TTS", "default");
}
}
else {
Log.d("TTS", "fail");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
}
break;
default:
Log.d("TTS", "case default");
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
For getting Default language set in setting > Language and Input > Google-Text-To-Speech default language set , i used :
tts.getLanguage();

Google Real-time Multiplayer on Android

I am having trouble with my app that uses Google's Real-time Multiplayer. When you launch the app, it just crashes. I added the crash log at the bottom...
I was able to find out that the problem was when I called mGoogleApiClient.connect();
Here is my code:
//(Your package here:)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.birdprograms.multiplayer.BaseGameUtils.src.main.java.com.google.example.games.basegameutils.BaseGameUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesStatusCodes;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Participant;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessageReceivedListener;
import com.google.android.gms.games.multiplayer.realtime.Room;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateListener;
import com.google.android.gms.games.multiplayer.realtime.RoomUpdateListener;
import com.google.android.gms.plus.Plus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener, RealTimeMessageReceivedListener, RoomUpdateListener, RoomStatusUpdateListener, OnInvitationReceivedListener{
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingConnectionFailure = false;
private boolean mSignInClicked = false;
private boolean mAutoStartSignInFlow = true;
String mRoomId = null;
ArrayList<Participant> mParrticipants = null;
String mMyId = null;
byte[] mMsgBuf = new byte[2];
private TextView textView;
private TextView myscoretxt;
private TextView urscoretxt;
final static int[] CLICKALBES = {
R.id.button,R.id.button2,R.id.button3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
for (int id : CLICKALBES){
findViewById(id).setOnClickListener(this);
}
}
private void startQuickGame(){
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS,0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
changedisplay(1);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
Games.RealTimeMultiplayer.create(mGoogleApiClient,rtmConfigBuilder.build());
}
#Override
public void onActivityResult(int requestCode, int responseCode,Intent intent){
super.onActivityResult(requestCode,responseCode,intent);
switch(requestCode){
case RC_SIGN_IN:
mSignInClicked = false;
mResolvingConnectionFailure = false;
if(responseCode == RESULT_OK){
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this, requestCode, requestCode, R.string.signin_other_error);
}
break;
};
super.onActivityResult(requestCode,responseCode,intent);
}
#Override
public void onStop(){
leaveRoom();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
changedisplay(0);
}
super.onStop();
}
#Override
public void onStart(){
changedisplay(0);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()){
} else {
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e){
if (keyCode == KeyEvent.KEYCODE_BACK && findViewById(R.id.button).getVisibility() == View.VISIBLE){
leaveRoom();
return true;
}
return super.onKeyDown(keyCode, e);
}
void leaveRoom(){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
if(mRoomId != null){
Games.RealTimeMultiplayer.leave(mGoogleApiClient, this, mRoomId);
mRoomId = null;
findViewById(R.id.button).setVisibility(View.VISIBLE);
changedisplay(0);
textView = (TextView)findViewById(R.id.textView3);
myscoretxt = (TextView)findViewById(R.id.textView);
urscoretxt = (TextView)findViewById(R.id.textView2);
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.button2:
startQuickGame();
startGame(true);
break;
case R.id.button3:
scoreOnePoint();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure){
return;
}
if (mSignInClicked || mAutoStartSignInFlow){
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = BaseGameUtils.resolveConnectionFailure(this,mGoogleApiClient,connectionResult,RC_SIGN_IN,getString(R.string.signin_other_error));
}
changedisplay(1);
}
void updateRoom(Room room){
if(room != null){
mParrticipants = room.getParticipants();
}
if (mParrticipants != null){
updatePeerScoresDisplay();
}
}
#Override
public void onConnectedToRoom(Room room) {
mRoomId = room.getRoomId();
mParrticipants = room.getParticipants();
mMyId = room.getParticipantId(Games.Players.getCurrentPlayerId(mGoogleApiClient));
}
#Override
public void onDisconnectedFromRoom(Room room) {
mRoomId = null;
showGameError();
}
void showGameError(){
BaseGameUtils.makeSimpleDialog(this,getString(R.string.game_problem));
changedisplay(0);
}
#Override
public void onJoinedRoom(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
}
#Override
public void onRoomConnected(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
updateRoom(room);
}
int mSecondsLeft = -1;
final static int GAME_DDURATION = 20;
int mScore = 0;
void resetGameVars(){
mSecondsLeft = GAME_DDURATION;
mScore = 0;
mParticipantScore.clear();
mFinishedParticipants.clear();
}
void startGame(boolean multiplayer){
updateScoreDisplay();
broadcastScore(false);
changedisplay(1);
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (mSecondsLeft <= 0)
return;
gameTick();
h.postDelayed(this, 1000);
}
}, 1000);
}
void gameTick(){
if(mSecondsLeft > 0)
--mSecondsLeft;
textView.setText("Time Left: "+mSecondsLeft+" seconds");
if (mSecondsLeft <= 0){
changedisplay(0);
broadcastScore(true);
}
}
void scoreOnePoint(){
if(mSecondsLeft <= 0)
return;
++mScore;
updateScoreDisplay();
updatePeerScoresDisplay();
broadcastScore(false);
}
Map<String, Integer> mParticipantScore = new HashMap<String, Integer>();
Set<String> mFinishedParticipants = new HashSet<String>();
#Override
public void onRealTimeMessageReceived(RealTimeMessage realTimeMessage) {
byte[] buf = realTimeMessage.getMessageData();
String sender = realTimeMessage.getSenderParticipantId();
if(buf[0] == 'F' || buf[0] == 'U'){
int existingScore = mParticipantScore.containsKey(sender) ?
mParticipantScore.get(sender) : 0;
int thisScore = (int) buf[1];
if(thisScore > existingScore){
mParticipantScore.put(sender, thisScore);
}
updatePeerScoresDisplay();
if((char) buf[0] == 'F'){
mFinishedParticipants.add(realTimeMessage.getSenderParticipantId());
}
}
}
void broadcastScore(boolean finalScore){
mMsgBuf[0] = (byte) (finalScore ? 'F' : 'U');
mMsgBuf[1] = (byte) mScore;
for(Participant p : mParrticipants){
if(p.getParticipantId().equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
if (finalScore){
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient, null, mMsgBuf, mRoomId, p.getParticipantId());
} else {
Games.RealTimeMultiplayer.sendUnreliableMessage(mGoogleApiClient, mMsgBuf, mRoomId, p.getParticipantId());
}
}
}
void updateScoreDisplay(){
myscoretxt.setText("Your Score: "+fomatScore(mScore));
}
String fomatScore(int i){
if(i<0)
i=0;
String s = String.valueOf(i);
return s.length() == 1 ? "00" + s : s.length() == 2 ? "0" + s : s;
}
void updatePeerScoresDisplay(){
if(mRoomId != null){
for (Participant p : mParrticipants){
String pid = p.getParticipantId();
if(pid.equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
int score = mParticipantScore.containsKey(pid) ? mParticipantScore.get(pid) : 0;
urscoretxt.setText("Opponents Score: "+fomatScore(score));
}
}
}
void changedisplay(int i){
if(i == 0){
findViewById(R.id.button).setVisibility(View.VISIBLE);
findViewById(R.id.button2).setVisibility(View.VISIBLE);
findViewById(R.id.button3).setVisibility(View.GONE);
findViewById(R.id.textView).setVisibility(View.GONE);
findViewById(R.id.textView2).setVisibility(View.GONE);
findViewById(R.id.textView3).setVisibility(View.GONE);
}
else{
findViewById(R.id.button).setVisibility(View.GONE);
findViewById(R.id.button2).setVisibility(View.GONE);
findViewById(R.id.button3).setVisibility(View.VISIBLE);
findViewById(R.id.textView).setVisibility(View.VISIBLE);
findViewById(R.id.textView2).setVisibility(View.VISIBLE);
findViewById(R.id.textView3).setVisibility(View.VISIBLE);
}
}
}
I have removed several callbacks for readers sake that did not cause the problem for sure!
If you read the whole thing, then thank you for your patience. :)
Any help, or suggestions would be helpful. Thanks!
-Nathan
Edit
Here is the crash log:
04-22 09:28:00.320 19247-19247/com.birdprograms.multiplayerdemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.birdprograms.multiplayerdemo, PID: 19247
java.lang.IllegalStateException: A fatal developer error has occurred. Check the logs for further information.
at com.google.android.gms.internal.jl$h.b(Unknown Source)
at com.google.android.gms.internal.jl$h.g(Unknown Source)
at com.google.android.gms.internal.jl$b.hy(Unknown Source)
at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5323)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
Your manifest is missing
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
// this is required if your RequestedClients is using AppStateManager.SCOPE_APP_STATE
<meta-data
android:name="com.google.android.gms.games.appstate.APP_ID"
android:value="#string/app_id" />

Not Bound To TTS Engine

I'm trying to make speaking dictionary.
LogCat shows "Successfully bound to com.android.tts" but when the Speak button clicked, it shows "failed speak : not bound to tts engine".
But on AVD it runs smoothly, why?
This Is my goTranslator class:
package sk.team;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import android.content.Intent;
import android.content.res.Configuration;
import java.util.Locale;
public class goTranslator extends Activity implements TextToSpeech.OnInitListener{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private SQLiteDatabase db = null;
private Cursor translatorCursor = null;
private EditText txtSearch;
private EditText txtResult;
private AppDatabase dbtranslator = null;
private RadioButton Eng,Ind;
private Button Translate,Speak;
public static final String ENGLISH = "english";
public static final String INDONESIA = "indonesia";
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(goTranslator.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(goTranslator.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbtranslator = new AppDatabase(this);
db = dbtranslator.getWritableDatabase();
setContentView(R.layout.main);
dbtranslator.createTable(db);
dbtranslator.generateData(db);
Eng = (RadioButton) findViewById(R.id.Eng);
Ind = (RadioButton) findViewById(R.id.Ind);
Translate = (Button) findViewById(R.id.Translate);
Speak = (Button) findViewById(R.id.Speak);
txtSearch = (EditText) findViewById(R.id.txtSearch);
txtResult = (EditText) findViewById(R.id.txtResult);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
Speak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = txtResult.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(goTranslator.this, "Saying: " + text,
Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
public void Translate (View view) {
if (view == Translate) {
if (Eng.isChecked()) {
txtSearch.setHint("Masukkan Kata");
Locale loc = new Locale ("es_ES");
tts.setLanguage(loc);
String result = "";
String englishword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where ENGLISH='" + englishword
+ "' ORDER BY ENGLISH", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(2);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(2);
}
}
if (result.equals("")) {
result = "Kata Tidak Tersedia";
}
txtResult.setText(result);
}
if (Ind.isChecked()) {
txtSearch.setHint("Enter Word");
Locale loc = new Locale ("en_US");
tts.setLanguage(loc);
String result = "";
String indonesiaword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where INDONESIA='" + indonesiaword
+ "' ORDER BY INDONESIA", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(1);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(1);
}
}
if (result.equals("")) {
result = "Result Not Found";
}
txtResult.setText(result);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (translatorCursor != null) {
translatorCursor.close();
db.close();
}
}
}
Log.w(TAG, method + " failed: not bound to TTS engine");
I caused by
mServiceConnection;
Being null
Does your testing device lack an internet connection?

Categories

Resources