i am programming a little bit android and i have a problem with adding and calling contacts.
my idea was to add two contacts and when the call-button was pressed the user can decide which one he wants to call.. and my two problems are, that on my AVD the code is working until i have to call somebody. so i can choose 2 contacts and these contacts are safed... on the phone of my friend i cant even choose contacts.. the programm just says: "The Application Contacts_SPrefs stopped working"...
well i think there is a problem in my code.. but i dont know where it is and how i could fix it, because in my previous version the code works...
So in this part of the app you can add 2 contacts and choose the button call which opens the other intent which is described below
Main Activity
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private String contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
//-------- > this thing here opens the contacts view < ------
//later its waiting until the user clicks on a number of his contacts
contact = "Brah1";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contact = "Brah2";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.call)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), OpenMenu.class);
startActivity(intent);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//after he clicked a number its getting to this point
//in the uri it saves some number and all this things where the contact is
//so this is for the location
Uri uri = data.getData();
if (uri != null) {
//get more data
//in this cursor all the values of the contacts are going to be safed
//c is for the contact
Cursor c = null;
try {
//here all datas from the contact are going to be safed in c
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//c is the phone number in very special code types and stuff like that
//in c is everything from the contact saved
//now c is going to be converted into a string -> everything that stays is the phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
showSelectedNumber(type, number);
save(contact, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
public void save(String type, String number) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(type, number);
edit.commit();
}
#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);
}
}
so.. as you can see.. i dont know really much about the topic Intent and its specifications.. anyway... heres the second part of the app, in which the call-command is.. and this command doesent work either...
OpenMenu
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class OpenMenu extends Activity {
private String nr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_menu);
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah1", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah2", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
}
public void showSelectedNumber(String number) {
Toast.makeText(this, "Took Nr : " + number, Toast.LENGTH_LONG).show();
}
public String load(String brahNr, String number) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getString(brahNr, number);
return sharedNumber;
}
#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.get
ItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
....well... this is a lot of code(for me).. and i thank everybody who helps me :)
edited lateron
i just forgot the permissions... so this is also needed
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
vZ
Related
I work simple android app for sending sms. I have 2 activities. One is main for sending 2 different messages with 2 different content but messages send to same number. On secund activity i have 3 fields: one is for input number to send messages, and other two are for message content. When I click save button app save user input and go back to main activity. And here start my problem. How can i send users input for number to send messages and messages content to main activity to send sms with saved user input? I am totally beginner with android developing so please help! Here is my MainActivity.java:
package com.example.davor.light;
import android.content.Intent; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.telephony.SmsManager; import
android.telephony.SmsMessage; import android.view.Menu; import
android.view.MenuItem; import android.view.View; import
android.widget.Button; import android.widget.ImageView; import
android.widget.TextView; import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GUMBI INFORMACIJE
Button ukljuci = (Button) findViewById(R.id.ukljuci);
Button iskljuci = (Button) findViewById(R.id.iskljuci);
Button postavke = (Button) findViewById(R.id.postavke);
final ImageView slika = (ImageView) findViewById(R.id.slika);
// INFORMACIJA O PORUCI
final String broj = "097";
final String ukljuciPoruka = "Uključi";
final String iskljuciPoruka = "Isključi";
// KLIK NA GUMB ISKLJUČI
iskljuci.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(broj, null, iskljuciPoruka, null, null);
Toast.makeText(getApplicationContext(), "Isključeno! poslano na broj " + broj, Toast.LENGTH_LONG).show();
slika.setImageResource(R.drawable.off);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Nemoguće isključiti!",Toast.LENGTH_LONG).show();
}
}
});
postavke.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent PostavkeActivity = new Intent(MainActivity.this,
Postavke.class);
startActivity(PostavkeActivity);
}
});
}
#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);
} }
And here is code for my second activity from witch I want to pull users input to MainActivity:
package com.example.davor.light;
import android.app.Activity; import android.content.Intent; import
android.content.SharedPreferences; import
android.preference.PreferenceManager; 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
android.widget.EditText; import android.widget.TextView; import
android.widget.Toast;
public class Postavke extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postavke);
gumbZaPovratak();
SharedPreferences loadSettings = PreferenceManager.getDefaultSharedPreferences(this);
String ucitajBroj = loadSettings.getString("spremiBroj", "");
String ucitajUkljuci = loadSettings.getString("spremiUkljuci", "");
String ucitajIskljuci = loadSettings.getString("spremiIskljuci", "");
final EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
postavkeBroj.setText(ucitajBroj);
final EditText postavkeUkljuci = (EditText) findViewById(R.id.postavkeUkljuci);
postavkeUkljuci.setText(ucitajUkljuci);
final EditText postavkeIskljuci = (EditText) findViewById(R.id.postavkeIskljuci);
postavkeIskljuci.setText(ucitajIskljuci);
Button spremi = (Button) findViewById(R.id.postavkeSpremi);
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
spremiPostavke("spremiBroj", postavkeBroj.getText().toString());
spremiPostavke("spremiUkljuci", postavkeUkljuci.getText().toString());
spremiPostavke("spremiIskljuci", postavkeIskljuci.getText().toString());
Toast.makeText(getApplicationContext(), "Spremljeno", Toast.LENGTH_LONG).show();
finish();
}
});
}
private void postavkeBroj() {
EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
}
private void spremiPostavke (String ključ, String vrijednost) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(ključ, vrijednost);
editor.commit();
}
private void gumbZaPovratak(){
Button nazad = (Button) findViewById(R.id.nazad);
nazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#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_postavke, 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);
} }
You can use startActivityForResult()
You can refer this link:
http://hmkcode.com/android-startactivityforresult/
In Activity1
Intent myIntent = new Intent(this,Activity2.class);
myIntent.putExtra("var", variable_to_pass);
startActivity(myIntent);
In Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
intentExtra = extras.getString("var"); // retrieving variable
}
You can add data to an intent like this :
String messageContent = (EditText) findViewById(yourMessageContentId).getText().toString();
String messageNumber = (EditText) findViewById(yourMessageNumberId).getText().toString();
intent.putExtra("com.example.davor.light.MESSAGE_CONTENT", messageContent);
intent.putExtra("com.example.davor.light.MESSAGE_NUMBER", messageNumber);
And then get it on the MainActivity :
Intent intent = getIntent();
String messageNumber = intent.getStringExtra("com.example.davor.light.MESSAGE_NUMBER");
String messageContent = intent.getStringExtra("com.example.davor.light.MESSAGE_CONTENT");
you can send information from one activity to other activity like bellow
Intent postavkeActivity = new Intent(MainActivity.this,
Postavke.class);
Bundle bundle=new Bundle();
bundle.putString(|"messageKey1", "message content1");
bundle.putString(|"messageKey2", "message content2");
postavkeActivity.putExtras(bundle);
startActivity(PostavkeActivity);
in main activity get bundle data like bellow
Bundle b=getIntent.getExtras();
String smsContent=b.getString("messageKey1");
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 programming for android an app and i want to call a random phone number from this app... so i got this, that you can enter a contact and his number is going to be saved in sharedPreferences.. dont know for what but it looks cool :D.. now i am trying to call the latest contact which the user added, but i dont know how to do that... i already copied much code of other questions in my programm without success...
hope you can help me adding a call function
ummm... ya i copied nearly the whole code.. so dont ask me pls what for some statements are... (i wont have anything against an explenation)
package com.example.getcontacts;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
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;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final String EXTRA_MESSAGE = "com.example.getcontacts";
private TextView tv;
private int i = loadI();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
load(tv, i);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.pick_person)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
//get all saved phone numbers
((Button)findViewById(R.id.allNr)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(null, Contacts.class);
inte.putExtra(EXTRA_MESSAGE, i);
startActivity(inte);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//get some datas... ?
Uri uri = data.getData();
if (uri != null) {
//get more data
Cursor c = null;
try {
//initializing something
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//initializing phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
//save in shared preferences and show the latest nr
int i = save(number);
showSelectedNumber(type, number);
load(tv, i);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
#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);
}
public String load(TextView tv, int i) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String c = Integer.toString(i);
sharedNumber = sp.getString(c, "");
tv.setText("Number: " + sharedNumber);
return sharedNumber;
}
public int save(String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
int i = 0;
String c;
c = Integer.toString(i);
edit.putString(c, value);
edit.commit();
i =Integer.parseInt(c);
i++;
saveI("savedI", i);
return i;
}
public void saveI(String key, int value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putInt(key, value);
edit.commit();
}
public int loadI() {
int sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getInt("savedI", 0);
return sharedNumber;
}
}
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");
Im using intents to pass the noteId from my database to a different activity for displaying the information it was working and i went to work on another part of the project and now it seems to only pass one value and from playing about i have found that seems to be whatever is the next highest object on the ListView. Sorry if this is badly worded, Im not very good at explaining these things
ViewNote Class
package com.hardy.passnotes;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewNote extends Activity {
EditText NewNoteTitle;
EditText NewNoteContent;
TextView tvNoteId;
DBTools dbTools = new DBTools(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_note);
NewNoteTitle = (EditText)findViewById(R.id.ETNewNoteTitle);
NewNoteContent = (EditText)findViewById(R.id.ETNewNoteContent);
Intent n = getIntent();
String NoteId = n.getStringExtra("noteId");
Toast.makeText(getApplicationContext(), NoteId,
Toast.LENGTH_LONG).show();
HashMap<String, String> NoteList = dbTools.getNoteInfo(NoteId);
if(NoteList.size() != 0)
{
setTitle("Note: " + NoteList.get("noteTitle"));
NewNoteTitle.setText(NoteList.get("noteTitle"));
NewNoteContent.setText(NoteList.get("noteContent"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.action_Editnote:
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(getApplication(),EditNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
case R.id.action_DelNote:
Intent intent1 = getIntent();
String NoteId = intent1.getStringExtra("noteId");
dbTools.deleteNote(NoteId);
Intent i = new Intent(getApplication(),MyNotes.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
MyNote Class:
package com.hardy.passnotes;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MyNotes extends ListActivity {
DBTools dbTools = new DBTools(this);
TextView tvNoteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_notes);
Log.i("Tag", "OnCreate Started As Normal");
setTitle("My Notes");
ArrayList <HashMap<String, String>> NoteList = dbTools.getAllNotes();
if(NoteList.size() != 0)
{
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(MyNotes.this,ViewNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
Log.i("Tag", "if Started As Normal");
}
});
ListAdapter Adapter = new SimpleAdapter(MyNotes.this,NoteList,R.layout.notes_list, new String[]{"noteId","noteTitle",}, new int[]{R.id.NoteId,R.id.NoteTitle} );
setListAdapter(Adapter);
Log.i("Tag", "Arrey Started As Normal");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_notes, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.action_Add:
Intent i = new Intent(getApplicationContext(),CreateNote.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
Thanks in advance been searching around and debugging for hours with no luck.
Hi I think the problem is that you use the findViewById() method inappropriately in your onItemClick listener.
You should use:
tvNoteId = (TextView)view.findViewById(R.id.NoteId);
Notice that I call the findViewById method on the view given by the onItemClick method because you want to find the view with the id NoteId from the pressed item and not from the entire's activity content view.. the way you do it will search in the content view of your activity for the first id equal with NoteId ...
I think your note get deleted on the moment edit is clicked from the options menu.
At the end of case R.id.action_Editnote nothing is returned nor break is called so case R.id.action_Delnote will be executed as well. This is where you delete the note from your database.
In your switch, put a break:
switch (item.getItemId())
{
case R.id.action_Editnote:
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(getApplication(),EditNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
break;
case R.id.action_DelNote:
Intent intent1 = getIntent();
String NoteId = intent1.getStringExtra("noteId");
dbTools.deleteNote(NoteId);
Intent i = new Intent(getApplication(),MyNotes.class);
startActivity(i);
finish();
break;
}