Hi I'm trying to get names and phone numbers from contact
this is the class which extends BroadcastReceiver
public class TextMessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent)
{
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
//MainActivity.
String num = getcont( MainActivity.,msg.getOriginatingAddress());
MainActivity.updateMessageBox("Message de la part: "+msg.getOriginatingAddress()+"\n"+
"Qui vous dit: "+msg.getMessageBody()+"\n");
}
}
In the Onrecieve methode I get the sms and the the one who send it,but I'd like to get the name not the number after some researche I found this way:
public static String getcont (Context context ,String num)
{
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String numbr = null;
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(numberFieldColumnIndex);
if (number.equals(num)) {
numbr = contact;
}
}
people.close();
return numbr;
}
I have an Activity called MainActivity I try to call the method getcont()
String num = getcont( MainActivity ,msg.getOriginatingAddress());
but it show me this error
MainActivity cannot be resolved to a variable
theres an other way to call getContentResolver().query() and thnx for helping me
How about using an intent to navigate to MainActivity?
if I fully understood your requiremnet ...
Instead of doing
String num = getcont( MainActivity ,msg.getOriginatingAddress());
why not do something like this?
Intent ii=new Intent(MainActivity.this, newclass.class);
ii.putExtra("name", s);
startActivity(ii);
Related
Hi I want to recieve my string data in another activity.
I found this code on youtube:
Activity 1:
public static final String FINISHED_LEVELS = "com.example.rexan_snerficonquiz.Quiz_Fragment.FINISHED_LEVELS";
public static final String SKIPPED_LEVELS = "com.example.rexan_snerficonquiz.Quiz_Fragment.SKIPPED_LEVELS";
public static final String FAILED_LEVELS = "com.example.rexan_snerficonquiz.Quiz_Fragment.FAILED_LEVELS";
public static final String USED_HINTS = "com.example.rexan_snerficonquiz.Quiz_Fragment.USED_HINTS";
public void openActifity2(){
Intent intent = new Intent(getActivity().getApplication(), Fragment_score.class);
intent.putExtra(FINISHED_LEVELS, finishedLevels);
intent.putExtra(FAILED_LEVELS, failedLevels);
intent.putExtra(USED_HINTS, usedHints);
intent.putExtra(SKIPPED_LEVELS, skippedLevels);
startActivity(intent);
}
Activity 2:
Intent intent = getIntent();
int finishedLevels = intent.getIntExtra(Quiz_Fragment.FINISHED_LEVELS,0);
int failedLevels = intent.getIntExtra(Quiz_Fragment.FAILED_LEVELS, 0);
int skippedLevels = intent.getIntExtra(Quiz_Fragment.SKIPPED_LEVELS, 0);
int usedHints = intent.getIntExtra(Quiz_Fragment.USED_HINTS, 0);
But getIntent() doesnt work anymore. Can anyone help me?
Use this code it may work
In activity1.java
Intent intent=new Intent(Activity1.this, Activity2.class);
intent.putExtra(Key,Value);
context.startActivity(intent);
get in Activity2.java
int mValue=getIntent().getExtras().getInt(Key);
I'm stuck in a program need some help. I have a fragment class in which I have multiple functions but I need only one function from it in the other class this class is not a fragment class. I used Intent but through that I'm not able to pass any function. the sample code is below. I need the ReadData whole function in the other class. as the value of data is changing in every second so i want it in the other screen to display
public class ModeFragment extends Fragment implements TitledFragment {
public void readData(){
if(manager.getConnectedDevices().size()<=0){
Toast.makeText(ModeFragment.this.getActivity(),"No connected devices", Toast.LENGTH_LONG).show();
return;
}
device1 = manager.getConnectedDevices().get(0);
Map<String , String> reciveData = getSpecificServiceInfo(device1 , CHARACTERISTIC_READABLE);
for (Map.Entry<String, String> e : reciveData.entrySet()){
manager.read(device1, e.getKey(), e.getValue(), new BleReadCallback() {
#Override
public void onRead(byte[] data, BleDevice device) {
Toast.makeText(ModeFragment.this.getActivity(), "Read success! data: " + new String(data), Toast.LENGTH_LONG).show();
// String str = data.toString();
// List<String> data1 = Arrays.asList(str.split(","));
Intent intent = new Intent(getActivity() , BluetoothActivity.class);
intent.putExtra("data" , data.toString());
startActivity(intent);
}
#Override
public void onFail(int failCode, String info, BleDevice device) {
// Toast.makeText(ModeFragment.this.getActivity(), "Read fail! data: " + info, Toast.LENGTH_LONG).show();
}
});
}
}
private void onclick(){
Intent intent = new Intent(ModeFragment.this.getActivity() , BluetoothActivity.class);
intent.putExtra("key" , "value of Key");
startActivity(intent);}}
Other class:
public class BluetoothActivity extends AppCompatActivity {
ModeFragment modeFragment = new ModeFragment();
modeFragment.readData();
Intent intent = getIntent();
String str = intent.getStringExtra("key");
sensor_1_value.setText(str);
Toast.makeText(BluetoothActivity.this , str , Toast.LENGTH_LONG).show();
}
but through intent I only get this specific Value.
I'm using intent to pass the string value to next Activity where I use getStringExtra to get the Value. The value is is User Contact no. in 10 digit which is in numeric value. when I setText in textview then It display the correct format but when I use intent on onclicklistener to open dialpad then instead of no, some random no. appears and in 4 digit also
Here I use to pass string
intent.putExtra(MOBILE, g.getSellermobile());
and I receive it by
tutor_mobile = intent.getStringExtra(MOBILE);
when I set it in textview as
TextView contact = (TextView) findViewById(R.id.tutor_near);
contact.setText(tutor_mobile);
It display correct format eg 9868336847
but when I use intent to open dialpad as
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
I'm using below code to get the mobile no.
etMobile = (EditText) findViewById(R.id.user_mobile);
String sellermobile = etMobile.getText().toString();
and In class file I have
package com.nepalpolice.filmyduniya.maincategory;
public class location {
public String sellermobile;
// public Uri uri;
public location( String sellermobile) {
this.sellermobile = sellermobile;
// this.uri = uri;
}
public String getSellermobile() { return sellermobile;}
}
}
Then in activity I have
public static final String MOBILE = "other_mobile";
and
intent.putExtra(MOBILE, g.getSellermobile());
and in next activity I have
tutor_mobile = intent.getStringExtra(MOBILE); and
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
Then random no. in 4 digit appears.
Then in activity I have
Please Help.
Your tutor_mobile is a String value, but thr you rearrange it toString:
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
May be it's not a error, but it's strange. And what do you want to display in dialpad?
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + "string format number"));
startActivity(callIntent);
} catch (Exception e) {
Log.d("Response", e.toString());
}
I'm a beginner in Android development. What I'm trying to create is an app the speaks to you then waits for your answer so its kind of text to speech works ,then it activates speech recognition and with my code the text to speech works then it calls speech recognition.Then an erro msg is shown ,the catch block is executed.
The problem is that I have to add Speech Recognition in a separate class, then add an Object of it in the Adapter not Main Activity. Speech Recognition won't work and since all tutorials for speech recognition for Android are adding the code in Main Activity and I'm doing it as class called in the adapter is the problem ?
UPDATE startActivityForResult() method is not working
Here is the code for SpeechRecogntion class
public class SpeechRecog extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
String textResult ;
public void Start (Intent i , Context c){
i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Are You Done , yet? ");
try{
startActivityForResult(i,VOICE_RECOGNITION_REQUEST_CODE);
} catch(Exception e) {
Toast.makeText(c, "SpeechRecogntion is not avalible on your device ", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == VOICE_RECOGNITION_REQUEST_CODE)&& (resultCode== RESULT_OK)) {
textResult= data.getStringExtra(RecognizerIntent.EXTRA_RESULTS);
if (checkResult())
Toast.makeText(getApplicationContext(), "You are done ", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "You are not done ", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private boolean checkResult() {
if (textResult.equals("done")||(textResult.equals("yes")))
return true ;
return false;
}
}
And Here is the object of it in the Adapter class
private SpeechRecog mySP;
private Intent mySpIntetn ;
public ListAdapterClass(Context context) {
mytts = new TxtToSpeechClass(context);
mySP = new SpeechRecog();
}
And Here is where my problem relies ,the on clicklistener inside the Adapter class
Lh.btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if (Lh.btn.getText().equals("Play"))
{
Lh.btn.setText("Pause"); //change the btn status so user know how to stop it
List<Items> hResults=db.getAllItems(Lh.idList + 1);
for (int i = 0; i < hResults.size(); i++)
{
Items item = hResults.get(i);
String s = item.getItemname();
mytts.Talk(s,1);
mySP.Start(mySpIntetn , context ); //the code in here wont work is there something I'm missing here
Toast.makeText(context,s, Toast.LENGTH_SHORT).show();
}
mytts.Talk("Congrats ",1);// 1 means Queue_add
} else {
Lh.btn.setText("Play");
mytts.Talk("See you later", 0); // 0 means Queue_Flush
}
}
);
mySpIntetn is private. Try to change it to public in the Adapter class.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am coding a prog about SMS,i have a service,and a broadcast receiver,when a sms is sent,i get the "displayoriginatingadress,then its automaticly Resend another sms to the source number,but i have a bug/force close for Invalid Destination Address beacause when i get the source number(i am from france) its like this : "+33617890922" but i need to get it like this "0617890922",how can i do it ?
** Any Help????
public void onReceive(Context c, Intent intent) {
// TODO Auto-generated method stub
mContext = c;
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
Toast.makeText(c, "Service SMS Started OK !", Toast.LENGTH_LONG).show();
Toast.makeText(c, "SMS Received : "+messages.getMessageBody(),
Toast.LENGTH_LONG).show();
String str = messages.getMessageBody();
String num = messages.getDisplayOriginatingAddress();
String str1= PhoneNumberUtils.formatNanpNumber(num);
if(messages.getMessageBody().contentEquals("klmj")){
if (intent.getAction().equals(ACTION_RECEIVE_SMS)){
Intent serviceIntent = new Intent(mContext, ServiceLocation.class);
serviceIntent.putExtra("id", str1);
mContext.startService(serviceIntent);
}
.... .... .... ....
ok the problem is not from "+33" beacause i tried to replace the destinationadress to send sms by "+33677890098" and its work,im lost,it is the data i get from my broadcast receiver are corrupted?? here some code Also i dunno how to use an external library that i have found called "phoneutil" i think,is my problem come from my received number from my intent? i tried to put quote with no luck,also same problem using some String operation... wtf please help thanks you
UPDATE: i noticed that the String "str" is Empty when used in the "lo" method,see code modification below :
public class ServiceTe extends Service{
private final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";
private String initData;
int myLatitude , myLongitude;
private String loc;
private String str;
private String num;
public void onCreate(){
lo();
}
public int onStartCommand(Intent itn, int num1, int flag){
str = itn.getStringExtra("id");
Toast.makeText(this, "One !" +str, Toast.LENGTH_LONG).show();
return 0;
}
public void lo(){
// TODO Auto-generated method stub
Toast.makeText(this, "Two !", Toast.LENGTH_LONG).show();
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
//This Toast show : "" , Nothing...
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
if(RqsLocation(cid, lac)){
loc = (
String.valueOf((float)myLatitude/1000000)
+ " : "
+ String.valueOf((float)myLongitude/1000000));
Its doesnt work like this,Force Close , and invalid DestinationAddress error
SmsManager.getDefault().sendTextMessage(str OR this : itn.getStringExtra("id"); , null, loc, null, null);
}else{ Its work like this !
SmsManager.getDefault().sendTextMessage("+33643598356", null, "Cant Report Location", null, null);
};
OK i Fixed the Problem thanks anyways for your 'help,look code below:
public class ServiceTe extends Service{
private final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";
private String initData;
int myLatitude , myLongitude;
private String loc;
private String str;
private String num;
public void onCreate(){
}
public int onStartCommand(Intent itn, int num1, int flag){
str = itn.getStringExtra("id");
Toast.makeText(this, "One !" +str, Toast.LENGTH_LONG).show();
//Call here lo with str as argument:
lo(str);
return 0;
}
//Added a string here to receive the Data String from the intent(str)...
public void lo(String num){
// TODO Auto-generated method stub
//Thats all i have my data from my intent avaible here !
Toast.makeText(this, "Two !", Toast.LENGTH_LONG).show();
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
if(RqsLocation(cid, lac)){
loc = (
String.valueOf((float)myLatitude/1000000)
+ " : "
+ String.valueOf((float)myLongitude/1000000));
Its doesnt work like this,Force Close , and invalid DestinationAddress error
SmsManager.getDefault().sendTextMessage(str, null, loc, null, null);
}else{ Its work like this !
SmsManager.getDefault().sendTextMessage("+33643598356", null, "Cant Report Location", null, null);
};