I am currently attempting to generate a user profile in an Android application through the users existing social network data. I am using the SocialAuth library to login and pull the data out of the application and populate some text fields in a fragment.
I am currently using Facebook and Twitter for this but I am having trouble reciving the "Location" of the profile through Facebook. Twitter is able to get location successfully but Facebook simply comes up "Null" when the get request is sent out.
To complicate things when I access the Facebook account I am testing on with the example application that SocialAuth provides it is able to get the location without any problems but despite my code being identical and Twitter running the same code it won't work within my application.
Can anyone shed some light on why I am unable to retrieve the location through Facebook in my application? I will provide my relevant classes below:
LoginActivity.java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;
import org.brickred.socialauth.Profile;
public class LoginActivity extends ActionBarActivity {
private static SocialAuthAdapter adapter;
private Button facebook_button;
private Button twitter_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
adapter = new SocialAuthAdapter(new ResponseListener());
facebook_button = (Button)findViewById(R.id.fbSignUp);
twitter_button = (Button)findViewById(R.id.twitSignUp);
facebook_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.authorize(LoginActivity.this, SocialAuthAdapter.Provider.FACEBOOK);
}
});
twitter_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.authorize(LoginActivity.this, SocialAuthAdapter.Provider.TWITTER);
}
});
}
#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_login, 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);
}
private class ResponseListener implements DialogListener {
#Override
public void onComplete(Bundle bundle) {
adapter.getUserProfileAsync(new ProfileDataListener());
}
#Override
public void onError(SocialAuthError socialAuthError) {
}
#Override
public void onCancel() {
}
#Override
public void onBack() {
}
}
private class ProfileDataListener implements SocialAuthListener<Profile> {
#Override
public void onExecute(String provider, Profile t) {
Profile profileMap = t;
Intent intent = new Intent(LoginActivity.this, HubPage.class);
intent.putExtra("provider", provider);
intent.putExtra("profile", profileMap);
startActivity(intent);
}
#Override
public void onError(SocialAuthError socialAuthError) {
}
}
}
Profile Fragment.java
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.android.SocialAuthAdapter;
public class ProfileFragment extends Fragment {
SocialAuthAdapter adapter;
Profile profileMap;
// Android Components
TextView name;
TextView location;
ImageView image;
// Variables
String provider_name;
//ImageLoader imageLoader;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hub_page, container, false);
profileMap = (Profile) getActivity().getIntent().getSerializableExtra("profile");
Log.d("Profile", "Validate ID = " + profileMap.getValidatedId());
Log.d("Profile", "First Name = " + profileMap.getFirstName());
Log.d("Profile", "Last Name = " + profileMap.getLastName());
Log.d("Profile", "Location = " + profileMap.getLocation());
Log.d("Profile", "Profile Image URL = " + profileMap.getProfileImageURL());
provider_name = getActivity().getIntent().getStringExtra("provider");
// Set title
name = (TextView) rootView.findViewById(R.id.profileName);
location = (TextView) rootView.findViewById(R.id.profileLocation);
image = (ImageView) rootView.findViewById(R.id.profilePic);
//imageLoader = new ImageLoader(ProfileActivity.this);
//imageLoader.DisplayImage(profileMap.getProfileImageURL(), image);
// Name
if (profileMap.getFullName() == null)
name.setText(profileMap.getFirstName() + profileMap.getLastName());
else
name.setText(profileMap.getFullName());
// Location
location.setText(profileMap.getLocation());
return rootView;
}
}
Any help would be much appreciated as I can't seem to find any solution despite hours of trying.
Related
I want to add a button for each item in the Firebase recycler view.
I've created the button, it's being showed, and i'm receiving the Toast when I press it.
But - How can I get the relevant item on it's list ?
For example - When I press the 'DELETE' I want to delete that certain mission 'aspodm'. (Sorry for the large picture, how do I make it smaller?)
This is how the database looks like (vfPvsk... is the user id, and 773f... is random uuid for mission id):
And that is the code of the relevant fragment. (The Toast when clicking the button is activated - I just don't know how to get to the relevant mission in order to delete it)
package com.airpal.yonatan.airpal;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
/**
* A simple {#link Fragment} subclass.
*/
public class PendingFragment_User extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mPendingList;
private DatabaseReference mMissionsDb;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
Query queries;
public PendingFragment_User() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_pending_user, container, false);
mPendingList = (RecyclerView)mMainView.findViewById(R.id.pending_recycler_user);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child(mCurrent_user_id);
queries = mMissionsDb.orderByChild("status").equalTo("Available");
mMissionsDb.keepSynced(true);
mPendingList.setHasFixedSize(true);
mPendingList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder> firebaseMissionsUserRecyclerAdapter = new FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder>(
Mission.class,
R.layout.missions_single_layout,
PendingFragment_User.MissionsViewHolder.class,
queries
) {
#Override
protected void populateViewHolder(PendingFragment_User.MissionsViewHolder missionViewHolder, final Mission missionModel, int missionPosition) {
// Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(view.getContext(), "esto es un boton"+ view.getNextFocusUpId(), Toast.LENGTH_SHORT).show();
Log.d(TAG,"The button was pressed");
}
});
}
};
mPendingList.setAdapter(firebaseMissionsUserRecyclerAdapter);
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.pending_single_button);
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
Try using a subclass rather than anonymous one. Then, you'll be able to access the getItem(int position) method of the adapter. Something along the lines of:
private class MissionAdapter extends FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder> {
public MissionAdapter(Query queries){
super(Mission.class, R.layout.missions_single_layout, PendingFragment_User.MissionsViewHolder.class, queries);
}
#Override
protected void populateViewHolder(PendingFragment_User.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Mission clickedMission = MissionAdapter.this.getItem(missionPosition);
if (clickedMission != null){ // for the sake of being extra-safe
Log.d(TAG,"The button was pressed for mission: " + clickedMission.getType());
}
}
});
}
}
I made it print a log, but you should be able to do anything you want with the retrieved Mission object in there.
I have the following situation:
I have two activities (Main Activity and ProductCard Activity)
Main Activity has a RecyclerView with items in it.
( User can add items manually. For example he add 3 items)
User click on some item and go to the ProductCard Activity
In the ProductCard Activity user click on the button (moneyOk_readylist) and go to the Main Activity
But when User do last step, RecyclerView become blank (empty).
I know that it is connected with states, but doesn't understand how.
Can anyone help me?
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Person> persons;
private RecyclerView rv;
final String LOG_TAG = "myLogs";
RVAdapter adapter;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
persons = new ArrayList<>();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
if ((savedInstanceState != null) && (savedInstanceState.getSerializable("card") != null)) {
persons.clear();
persons.addAll((List<Person>) savedInstanceState.getSerializable("card"));
adapter.notifyDataSetChanged();
Log.d(LOG_TAG, "restore card with persons" + persons);
}
adapter.setOnItemClickListener(new RVAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ProductCard.class);
startActivity(intent);
Log.d(LOG_TAG, "go to ProductCard class" + persons);
}
});
adapter.setOnItemLongClickListener(new RVAdapter.MyLongClickListener() {
#Override
public void onItemLongClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item long" + position, Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "Removed " + position);
persons.remove(position);
adapter.notifyDataSetChanged();
}
});
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
person= new Person("Emma Wilson", "23 years old", R.drawable.im_beach);
persons.add(person);
Log.d(LOG_TAG, "push add" + persons);
adapter.notifyDataSetChanged();
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
Log.d(LOG_TAG, "onresume" + persons);
}
#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 void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("card", (Serializable) persons);
Log.d(LOG_TAG, "save cards" + persons);
}
#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);
}
}
ProductCard Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Created by Dmitry on 01.11.2015.
*/
public class ProductCard extends AppCompatActivity implements AdapterView.OnItemClickListener {
final String LOG_TAG = "myLogs";
Button moneyOk_readylist;
ImageButton addPhoto;
ImageView imageView;
private static int LOAD_IMAGE_RESULTS = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_card);
moneyOk_readylist=(Button)findViewById(R.id.moneyOk_readylist);
addPhoto=(ImageButton)findViewById(R.id.add_photo);
imageView=(ImageView)findViewById(R.id.imageView);
addPhoto.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
//i.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(i,"Select picture"),1);
}
});
moneyOk_readylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
imageView.setImageURI(data.getData());
}
}
#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();
switch (id) {
case R.id.action_save_card:
Toast.makeText(ProductCard.this, "Карточка сохранена", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
Log.d(LOG_TAG, "go to Main class" );
break;
case R.id.action_delete_card:
Toast.makeText(ProductCard.this, "Карточка удалена", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#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, 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);
}
/**
* 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.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.
I am new to android development. I need a solution for the new app I am developing which takes voice input and gives output in voice by mapping with a mapping database. Current program takes voice input with onlick on button . I need a soultion which can take voice input without clicking of any button simliar to Talking Tom application . Here is my code.My main code is in speakToMe which is method called on onclick & onActivityResult
package com.example.secondprog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import com.example.secondprog.*;
//import com.example.secondprog.DatabaseHelper;
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST = 0;
//private static final int VOICE_RECOGNITION_REQUEST = 0x10101;
TextToSpeech ttobj;
String resulttxt ;
TestDBClass db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new TestDBClass(this, null, null, 1);
try {
db.loadWords();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
Toast.makeText(getApplicationContext(), "No error",
Toast.LENGTH_LONG).show();
}
}
});
//DatabaseHelper db = DatabaseHelper(this);
//dbdtls dbdtlsresult = new dbdtls();
//String message3 = db.getdtls("how are");
//String output = dbdtlsresult.new_name();
//EditText editText = (EditText) findViewById(R.id.edit_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edit_message);
String txt = editText.getText().toString();
// Toast.makeText(getApplicationContext(), txt.toUpperCase(),
// Toast.LENGTH_LONG).show();
DictonaryDAO dictonaryDAO =
db.findname(txt.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
}
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
/*#Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
*/
**public void speakToMe(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Please speak slowly and enunciate clearly.");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST && resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TextView textView = (TextView) findViewById(R.id.speech_io_text);
String firstMatch = matches.get(0);
// textView.setText(firstMatch);
DictonaryDAO dictonaryDAO =
db.findname(firstMatch.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
}
}**
#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);
}
/**
* 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;
}
}
}
Voice Recognition not working for talking tom app so you try to use noise detection with sound meter. below here link for voice/ noise detection with audio recording without click.
http://androidexample.com/Detect_Noise_Or_Blow_Sound_-_Set_Sound_Frequency_Thersold/index.php?view=article_discription&aid=108&aaid=130
Please change SoundMeter.java File
mRecorder.setOutputFile(Environment.getExternalStorageDirectory().
getAbsolutePath() + "/test.3ggp");
i was following the tutorial from facebook developer website to retrieve my profile name and show in apps but it is just return nothing but the word that i input myself in else condition. I had generate the android key hashes from my computer and put to my fb developer profile and the apps id had include in my android project as well....
package com.example.mobile_e_commerce;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
public class SignInPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in_page);
This is to open the facebook login
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
the session should be opened i think but no///
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
The user should be my name, so it should output Hello Issac but return the else condition statement!
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
else
{
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("User = Null");
}
}
});
/*
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}*/
}
to get the response from facebook activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
this part is just general android code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sign_in_page, menu);
return true;
}
this part is just general android code
#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);
}
this part is just general android code
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
this part is just general android code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_in_page,
container, false);
return rootView;
}
}
}
This happen because you are using the wrong key hash.
You should generate new hash key and use it instead of what you have now.