I want to use the Speech Recongnition to handle commands in my application. I know
at any given point in my application what the valid commands would be
at that point so would like to limit the results that the Speech Recongnition is
matched against.
I mean in my app .. The valid words are only numbers plus alphabets. I mean number like A13FG6 something like that.
I would
like to be able to restrict the Speech recongnition to only try and match against alphaNumeric
words.. Limiting the vocabularly would enhance its chance of success..
how could i modify the given code to fulfill my requirement
Thanks in advance..
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mText = (TextView) findViewById(R.id.textView1);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getClass().getPackage().getName());
SpeechRecognizer recognizer = SpeechRecognizer
.createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
#Override
public void onResults(Bundle results) {
ArrayList<String> voiceResults = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults == null) {
Log.e(TAG, "No voice results");
} else {
Log.d(TAG, "Printing matches: ");
for (String match : voiceResults) {
Log.d(TAG, match);
mText.setText("results: " + match);
}
}
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Ready for speech");
}
#Override
public void onError(int error) {
Log.d(TAG,
"Error listening for speech: " + error);
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "Speech starting");
}
#Override
public void onBufferReceived(byte[] buffer) {
// TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
// TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle partialResults) {
// TODO Auto-generated method stub
}
#Override
public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
}
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
/* speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
sr.startListening(intent);
// startActivityForResult(intent, 1010);
Log.i("111111", "11111111");
}
});*/
}
}
You can not restrict recognition in Android Speech API, it doesn't support grammars. However, you can try CMUSphinx. See the example under link, you can define a grammar to use alpha digits only, it will work offline so the response will be very fast and you can tune accuracy for the best match too.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hi I was following a tutorial I found to make an app that plays a radio, the app works until you exit because then the sound stops. I have researched and found out that it needs to be a service but I am not sure how to change it to a service, this is the code I used.
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
I tried changing it but I am not sure how to put the functions from the main activity into a new service and then run it.
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
} // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I tried using the above code but I do not know how to start the action and whether or not it will work.
Thank you for reading :)
Call a service from your main activity.
startService(new Intent(MusicService.ACTION_PLAY));
your service class.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
return START_STICKY;
}
I need to create twitter fabric re-usable component.my first step to allow login with twitter by simply calling method from a class.
Code
CLASS
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.StatusesService;
import io.fabric.sdk.android.Fabric;
public class TwitterAuth {
private String CONSUMER_KEY;
private String CONSUMER_SECRET;
private Context context;
private TwitterAuthClient client;
private StatusesService service;
public TwitterAuth(Context context, String CONSUMER_KEY, String CONSUMER_SECRET) {
this.CONSUMER_KEY = CONSUMER_KEY;
this.CONSUMER_SECRET = CONSUMER_SECRET;
this.context = context;
configureKey();
}
public void configureKey() {
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(context, new Twitter(authConfig));
}
public void doLogin() {
client = new TwitterAuthClient();
client.authorize((Activity) context, new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
final TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
String userName = session.getUserName();
Toast.makeText(context, "TWITTER EASY LIB TEST :: Done Login With \n Username :" + userName + " \n Token :" + token + "\n Secret :" + secret, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "TWITTER EASY LIB TEST :: failure", Toast.LENGTH_SHORT).show();
}
});
}
public void doLogout() {
Twitter.getSessionManager().clearActiveSession();
}
public void publishTweet(String tweet) {
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
client.onActivityResult(requestCode, resultCode, data);
}
}
Activity
package codelynks.twitter.twitterintegration;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import com.easytweet.TwitterAuth;
public class CheckLib extends ActionBarActivity {
private Button cus;
private TwitterAuth auth;
private String CONSUMER_KEY = "", CONSUMER_SECRET = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
setContentView(R.layout.activity_main);
cus = (Button) findViewById(R.id.cusbutton);
cus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.doLogin();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
auth.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Here i will get the result on callback method
public void success(Result<TwitterSession> twitterSessionResult) {}
**or**
public void failure(TwitterException e) {}
How can i pass this result(SUCCESS/FAILURE) to activity CheckLib for doing further actions.?
any help would be appreciated :)
you can set listener for success or failure in your TwitterAuth.class and then set this listener in your activity (CheckLib.class) to notify you when success or failure, like this:
public class TwitterAuth {
private TwitterLoginListener listener;
public void setListener( TwitterLoginListener listener){
this.listener = listener;
}
Interfase TwitterLoginListener{
public void success(Result<TwitterSession> twitterSessionResult);
public void failure(TwitterException e);
}
.
.
.
in success and failure method you need to fill listener:
in success method (in TwitterAuth.class):
if(listener != null){
listener.success(twitterSessionResult);
}
in failure method (in TwitterAuth.class):
if(listener != null){
listener.failure(e);
}
then in your activity set listener:
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
auth.setListener(new TwitterLoginListener{
#Override
public void success(Result<TwitterSession> twitterSessionResult){
//login success
}
#Override
public void failure(TwitterException e){
//login failed
}
});
.
.
.
If it is a primitive type, like a boolean or a String (ok, this one is not primitive, but still), you can pass it as an Extra in an Intent which you send to the activity.
If it is a more complex object or you do not have Context access in your class, try greenrobot EventBus, a pretty cool library created exactly for such situations.
You can use interface and implement the interface method from your dologin method
check my sample
public interface sampleInterface {
// you can define any parameter as per your requirement
public void yourMethod(boolean value);
}
public void doLogin(sampleInterface si) {
public void publishTweet(String tweet) {
sampleInterface sampleIn;
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
si.yourMethod(true);
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
si.yourMethod(false);
}
});
}
}
inside your activity class
public void onClick(View v) {
auth.doLogin(new sampleInterface() {
#Override
public void yourMethod(boolean value) {
//GET your result
}
});
}
I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
In my application I'm trying to make a friendlist that's relative to the CurrentUser,I've tried looking through the docs of Parse.com and I asked a question about this on Parse.com and a Parser suggested I do it in the form of a Array column.I've done this although it seems to be relative to the CurrentUser(I made 3 accounts and made them friend eachother and the 3 accounts have different array columns retrieved from the ListView)It's not what I'm looking for since it's just the Usernames of the accounts and not their individual "rows" to make actions on the Users if you know what I mean.
So the question I'm asking is,
What would be the best practice using the Parse backend database to make a User "friendlist" based on the CurrentUser method?
Here is my 2 activities in which FindFriends is where I search for the Users and Add them to the "friendlist" and the PlayAFriend in which the friended Users would load up via an AdapterArray listview.
FindFriends Class
package com.fullfrontalgames.numberfighter;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.urbanairship.UAirship;
public class Findfriends extends Activity {
protected static final String TAG = null;
ParseObject po;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
final EditText sbar = (EditText)findViewById(R.id.PlayerSeachBar);
Button search = (Button)findViewById(R.id.Search);
Button Add = (Button)findViewById(R.id.Add);
final TextView ResultText = (TextView)findViewById(R.id.ResultTextView);
final FrameLayout ResultFrame = (FrameLayout)findViewById(R.id.ResultFrameLayout);
ResultFrame.setVisibility(View.GONE);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String username = sbar.getText().toString();
final ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
try {
ParseObject userObject = objects.get(0);
ResultText.setText(userObject.getString("username"));
ResultFrame.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Player Found",
Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(getApplicationContext(), "Username Not Found",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Friends = sbar.getText().toString();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
currentUser.add("friend", Friends);
currentUser.saveInBackground();
Toast.makeText(getApplicationContext(), "Player Has Been Added",
Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public void onStop() {
super.onStop();
}
}
PlayAFriend Class
package com.fullfrontalgames.numberfighter;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.urbanairship.UAirship;
public class PlayAFriend extends ListActivity {
private static final String TAG = null;
Cursor fFriends;
DBAdapter db;
ParseObject objects;
int from;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
ArrayList<String> friendslist = new ArrayList<String>();
final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
ListView friendlv = (ListView)findViewById(android.R.id.list);
friendlv.setAdapter(listAdapter);
String friend = currentUser.get("friend").toString();
listAdapter.add(friend);
}
}
}
I solved question myself using the ParseRelation method from the docs.Here is my example on how to add a friend to the current user!
FindFriends class
public class Findfriends extends Activity {
protected static final String TAG = null;
ParseObject po;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
final EditText sbar = (EditText)findViewById(R.id.PlayerSeachBar);
Button search = (Button)findViewById(R.id.Search);
Button Add = (Button)findViewById(R.id.Add);
final TextView ResultText = (TextView)findViewById(R.id.ResultTextView);
final FrameLayout ResultFrame = (FrameLayout)findViewById(R.id.ResultFrameLayout);
ResultFrame.setVisibility(View.GONE);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String username = sbar.getText().toString();
final ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
try {
ParseObject userObject = objects.get(0);
ResultText.setText(userObject.getString("username"));
ResultFrame.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Player Found",
Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(getApplicationContext(), "Username Not Found",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Friends = sbar.getText().toString();
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
final ParseObject friend = new ParseObject("Friends");
friend.put("username", Friends);
friend.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// TODO Auto-generated method stub
ParseRelation relation = currentUser.getRelation("Friends");
relation.add(friend);
currentUser.saveInBackground();
}
});
Toast.makeText(getApplicationContext(), "Player Has Been Added",
Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public void onStop() {
super.onStop();
}
}
PlayAFriend Class
public class PlayAFriend extends ListActivity {
private static final String TAG = null;
ParseObject objects;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
ListView friendlv = (ListView)findViewById(android.R.id.list);
Button play = (Button)findViewById(android.R.id.button1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
friendlv.setAdapter(listAdapter);
ParseRelation relation = currentUser.getRelation("Friends");
ParseQuery query = relation.getQuery();
query.whereEqualTo("username", null);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
for (int i = 0; i < objects.size(); i++) {
ParseObject r = objects.get(i);
String name = r.getString("username").toString();
listAdapter.add(name);
}
}
});
}
}
}
useing the Rest API docs approach, building on the reply you have from a parser,
you may want to link an array:friends as an object in your user class.
The friends object contains an array of pointers to the OID's in User class of all the friends of that user in the given user row.
You can update the array of pointers as you please by adding or removing objects from the array.
'{"friends":{"__op":"Add","objects":[{"__type":"Pointer",
"className":"User","objectId":"rtbhCb37tq"}]}}'
When you want to get the full , child user rows of all the friends of a given User ID ,
you just append the following to a normal query for a single row from the User table...
--data-urlencode 'include=friends'
The parse RestAPI Docs has some good examples of this technique involving Games, GameScores, and GameOpponents. You could read that.
If you want to eval the most advanced clients i would start with 'okhttp' and 'volley'.
More traditional http stuff here and here
I have reviewed your answer and I believe you may be able to improve the code a bit.
I found that you create a ParseObject friend and provide it with the attribute "username" which is retrieved with String Friends = sbar.getText().toString();, and then proceed to create a relation between that newly created ParseObject and the current ParseUser (currentUser).
The problem I found is within the Parse DB Storage. If you review your Parse DB you will find that the ParseObject friend that you are creating does not share the same ObjectID, or any of the attributes/data as the ParseUser that you are initially querying for.
You basically make a ParseObject that is no more than a copy of a ParseUser's username. I also found that you can add the same ParseObject friend multiply times, because everytime you do so you create a new ParseObject with a separate ObjectID and thus referencing a totally different ParseObject.
Ideally you would be looking to reference the ParseUser directly and I believe I have figured out how to do so.
Here is the entire Adapter that I have defined, but it allows you to create a relation with a ParseUser directly rather than having to create a ParseObject
public UserQueryAdapter(Context context, final String searchCriteria) {
// Use the QueryFactory to construct a PQA that will only show
// Todos marked as high-pri
super(context, new ParseQueryAdapter.QueryFactory<ParseUser>() {
public ParseQuery<ParseUser> create() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContains("username", searchCriteria);
return query;
}
});
}
#Override
public View getItemView(final ParseUser pUser, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.search_detail, null);
}
super.getItemView(pUser, v, parent);
ParseImageView todoImage = (ParseImageView) v
.findViewById(R.id.imageViewSearch);
ParseFile imageFile = pUser.getParseFile("photo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
// Add the title view
final TextView titleTextView = (TextView) v
.findViewById(R.id.textViewSearch);
titleTextView.setText(pUser.getUsername());
btnAdd = (ImageButton) v.findViewById(R.id.imageButtonAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Drawable background = v.getResources().getDrawable(
R.drawable.ui_border_green);
Drawable img = v.getResources().getDrawable(
R.drawable.ico_friend_add_green);
btnAdd.setBackground(background);
btnAdd.setImageDrawable(img);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
ParseRelation<ParseUser> relation = currentUser
.getRelation("Friends");
relation.add(pUser);
currentUser.saveInBackground();
}
}
}
});
return v;
}
alright so im making an android app, and basically everything is working fine expect the whole part about changing the status textview everytime "moneynum" is increased by 100. Heres my code:
package life.project;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class LifeActivity extends Activity {
/** Called when the activity is first created. */
ViewFlipper views;
int lifestatus=0;
TextView status;
Button main;
Button work;
TextView timer;
int moneynum=0;
int test=0;
Button GasStation;
Button Walmart;
Button Business;
TextView Moneycount;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
main=(Button) findViewById(R.id.button9);
views=(ViewFlipper) findViewById(R.id.viewFlipper1);
GasStation=(Button) findViewById(R.id.button13);
Walmart=(Button) findViewById(R.id.button23);
Business=(Button) findViewById(R.id.button33);
Moneycount=(TextView) findViewById(R.id.textView);
timer=(TextView) findViewById(R.id.textView3);
status=(TextView) findViewById(R.id.textView4);
work=(Button) findViewById(R.id.button1);
new CountDownTimer(1200000, 60000) {
public void onTick(long millisUntilFinished) {
timer.setText("Minutes remaining: " + millisUntilFinished / 60000);
}
public void onFinish() {
onPause();{
Intent timerends=new Intent("com.life.project.timesup");
startActivity(timerends);
finish();
}
}
}.start();
main.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
views.showPrevious();
}
});
work.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
views.showNext();
}
});
GasStation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=5;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
Walmart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=10;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
Business.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=20;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
}
}
and heres the part where its not working:
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
so everytime moneynum is increased by 100 i want lifestatus to increase by one and go through the rest of the code. But the if statement isnt executing when i run the program, and i think its because i have the arguments of the if statement wrong..can someone figure out i could make this work? sorry if this is confusing.
public .... LifeActivity
{
int moneySum = 100;
....
....
}
public void moneyCount()
{
if(moneynum>=moneySum) // Morethan incase your using looking for when moneynum passes 100 mark not when it equal exactly 100
{
lifestatus+=1;
status.setText("Status: "+lifestatus);
moneySum+=100;
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=20;
Moneycount.setText("Money:$ "+moneynum+" .00");
moneyCount();