Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.
Related
I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm trying to get videos to play on my Android app back-to-back and only after each video's been watched in its entirety.
I've come up with the following code:
package com.davekelley;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class Watch extends Activity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch);
player = new MediaPlayer();
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
int i = 0;
if (i < 2) {
i++;
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
}
else i=0;
}
});
player.start();
}
private void playVideo(String filename) {
try {
player.setDataSource(filename);
player.prepare();
player.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.watch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
But I can't even run it because Eclipse tells me that "The method setOnCompletionListener(MediaPlayer.OnCompletionListener) in the type MediaPlayer is not applicable for the arguments (new OnCompletionListener(){})".
What is causing this? How about the rest of my code...would it achieve what I'm trying to make? Thanks.
copy this lines
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
after
player = new MediaPlayer();
Try to play first video and set OnCompletionListener for media player which give you call back when first video completed then try to check for second video with new player instance in your case you never set data source for first video just intialize player instance and set OnCompletionListener which never called becz not set first video data source.
private MediaPlayer player;
private int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playVideo("http://domain.com/videos/"+i+".mp4\"");
}
public void playVideo(String path){
try{
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(path);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
player = null;
if(i<2){
playVideo("http://domain.com/videos/"+(++i)+".mp4");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
I don't know whats going wrong with my app i followed so many tutorials, any hint/help/advise would be appreciated, I am new on android. i am getting error as in onserviceregistrationfailed function of listner.
package com.example.ravinetworkapplication;
import java.io.IOException;
import java.net.ServerSocket;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.pm.ServiceInfo;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
NsdManager mNsdManager;
Context context;
NsdManager.DiscoveryListener mDiscoveryListner=null;
NsdManager.RegistrationListener mRegistrationListener=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mNsdManager= (NsdManager) this.getSystemService(Context.NSD_SERVICE);
final ServerSocket mServerSocket;
final ArrayList<String> listName = new ArrayList<String>();
Integer localPort = 0;
final ListView list = (ListView) findViewById(R.id.listView1);
listName.add("arunima");
listName.add("abhishek");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1,listName);
list.setAdapter(adapter);
try {
mServerSocket = new ServerSocket(0);
localPort = mServerSocket.getLocalPort();
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
Log.v("service registrd", "i am on folks");
Toast.makeText(getApplicationContext(), "Registerd", Toast.LENGTH_LONG).show();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
Log.v("service registration fail", "can not register service kumar ravi");
}
};
mDiscoveryListner = new NsdManager.DiscoveryListener() {
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("cannot stop service", "service discovery failed");
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("can not start", "Can not start discovery kumar ravi "+errorCode);
}
#Override
public void onServiceLost(NsdServiceInfo service) {
// TODO Auto-generated method stub
}
#Override
public void onServiceFound(NsdServiceInfo service) {
// TODO Auto-generated method stub
Log.v("service found", "we found the service");
if(!service.getServiceType().equals("_myapp.tcp.")){
}
else if(service.getServiceName().equals("kumar")){
}
else {
listName.add(service.getServiceName());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "Finally found the service "+service.getServiceName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
// TODO Auto-generated method stub
}
#Override
public void onDiscoveryStarted(String serviceType) {
// TODO Auto-generated method stub
Log.v("Service Discovery Started", "Searching of Service Discovery");
}
};
Log.v("registerd port", localPort.toString());
final NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(localPort);
serviceInfo.setServiceName("kumar");
serviceInfo.setServiceType("_myapp.tcp.");
//mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
Button startBroadcast = (Button) findViewById(R.id.button1);
Button startListen = (Button) findViewById(R.id.button2);
startBroadcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
});
startListen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.discoverServices("_myapp.tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListner);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListner);
Log.v("Stopped", "Scanning stopped"); }
catch(Exception e){
Log.v("some error in unregistring service", e.toString());
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
I have an Android app which uses tabs and fragments for navigation. The app works fine when launched, but after I change the orientation the menu items and the widgets in the fragments stop working. The app works if I put
android:configChanges="orientation|screenSize"
in the manifest, but in the Android documentation it says that this should be a last resort, so I'm wondering if there is a better solution. Here's the code for the host activity and one of the fragments.
package com.mynews;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//stopService(new Intent(this, FindArticlesService.class));
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar.newTab()
.setText("Articles")
.setTabListener(new TabListener<Articles>(this, "articles", Articles.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Websites")
.setTabListener(new TabListener<UserSites>(this, "websites", UserSites.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Add a website")
.setTabListener(new TabListener<AddSites>(this, "add a site", AddSites.class));
actionBar.addTab(tab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
////Intent intent = new Intent(this, FindArticlesService.class);
//this.startService(intent);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
Fragment fragment;
final Activity activity;
final String tag;
final Class<T> mClass;
public TabListener(Activity a, String s, Class<T> c){
activity = a;
tag = s;
mClass = c;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment == null){
fragment = Fragment.instantiate(activity, mClass.getName());
ft.add(android.R.id.content, fragment, tag);
}else{
ft.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment != null){
ft.detach(fragment);
}
activity.closeContextMenu();
}
}
}
My Fragment Class
package com.mynews;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddSites extends Fragment {
public AddSites(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_add_sites);
// Show the Up button in the action bar.
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.add);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
UserSitesFunc usf = new UserSitesFunc(); //create a new UserSitesFunc to hold
try{ //the list of sites
FileInputStream fis = getActivity().openFileInput("MySites.ser");//check if there's a file
ObjectInputStream ois = new ObjectInputStream(fis);//with a USF object
usf = (UserSitesFunc) ois.readObject(); //if there is, deserialize it and use it
ois.close();//instead of a brand new object
}catch(IOException e){ //catch various exceptions
e.printStackTrace();
}catch(Exception ep){
ep.printStackTrace();
}finally{
try{ //do this with either the new object or the deserialised one
EditText website = (EditText) getActivity().findViewById(R.id.editText1);//get the input
EditText keywords = (EditText) getActivity().findViewById(R.id.editText2);//from the user
String web = website.getText().toString(); //store it in strings
String key = keywords.getText().toString();
String[] kwords = key.split(", ");
ArrayList<String> newKeywords = new ArrayList<String>();
for(String s:kwords){
newKeywords.add(s);
}
Sites s = new Sites(web, newKeywords);//create a new site from the input
if(usf.siteList.contains(s)){
showContainedDialog();
return;
}
usf.addSite(s);//add it to the user's list of sites
FileOutputStream fs = getActivity().openFileOutput("MySites.ser", Context.MODE_PRIVATE);//save it
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(usf);
oos.close();
Toast.makeText(getActivity(), web + " added to Tracked Websites", Toast.LENGTH_LONG).show();
website.setText("");
keywords.setText("");
}catch(MalformedURLException mue){
showDialog();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_add_sites, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.add_sites, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#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
//
return true;
}
return super.onOptionsItemSelected(item);
}
public static class NotAWebsiteDialog extends DialogFragment {
public static NotAWebsiteDialog newInstance(){
NotAWebsiteDialog notAWebsite = new NotAWebsiteDialog();
Bundle args = new Bundle();
notAWebsite.setArguments(args);
return notAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("Please enter a vaild web address")
.create();
}
}
public void showDialog(){
DialogFragment dialog = NotAWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Not A Website");
}
public static class AlreadyContainsWebsiteDialog extends DialogFragment {
public static AlreadyContainsWebsiteDialog newInstance(){
AlreadyContainsWebsiteDialog containsAWebsite = new AlreadyContainsWebsiteDialog();
Bundle args = new Bundle();
containsAWebsite.setArguments(args);
return containsAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("This website is already being tracked")
.create();
}
}
public void showContainedDialog(){
DialogFragment dialog = AlreadyContainsWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Contains this Website");
}
}
Kudos for not taking the easy way... keep up your programming efforts!
Refer to my answer here regarding the use of Menus and their host Fragments.
I am trying to make a read aloud menu option here. This is the code I have written. But it doesn't really read aloud the text on the card. The doc says that if there is any text set on the card it will read aloud. My card has some text on it :
newcard.setText("text");
My MenuActivity which is called looks like this.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuActivity extends Activity {
public Object json(int menuid)
{
JSONObject obj = new JSONObject();
try {
System.out.println("goes into try of json");
obj.put("text", "Hello World");
obj.put("menuItems", new JSONObject().put("action", "READ_ALOUD"));
System.out.println(obj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection.
switch (item.getItemId()) {
case R.id.read_aloud_menu_item:
System.out.println("goes itno read aloud case");
json(item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
// Nothing else to do, closing the activity.
finish();
}
}
I am really not sure wheteher I can pass the JSON like this. If not like this, how else can I do this?
I am not sure where you read that Glass would automatically read this aloud...
You should use TextToSpeech as in the gdk-compass-sample provided by Google.
Create a field in your Activity
public class MenuActivity extends Activity {
private TextToSpeech mSpeech;
...
}
Initialise in OnCreate
#Override
public void onCreate() {
super.onCreate();
...
mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// Do nothing.
}
});
}
Call the speak function in your onOptionsItemSelected event
mSpeech.speak(json(item.getItemId()).text, TextToSpeech.QUEUE_FLUSH, null);
Close everything down in the onDestroy event
#Override
public void onDestroy() {
mSpeech.shutdown();
mSpeech = null;
super.onDestroy();
}