Variables losing data between activities and I don't know why? - java

I am currently creating an android app that scans a network and outputs results in a ListView but I am trying to make it to where I tap on the network and it saves the data in a database then sends you to a page to show you what you selected but when I click an item it substrings the values correctly and displays work fine on the main activity but when I try to use the variables on my display page activity there values are set null.
Here is the main activity in the click listener:
networklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String grabItemInfo = wifis[position];
Network_Info info1 = new Network_Info();
info1.setMainBSSID( grabItemInfo.substring(grabItemInfo.indexOf('#') +1, grabItemInfo.lastIndexOf('#')));
info1.setMainSSID( grabItemInfo.substring(0,(grabItemInfo.indexOf('#'))));
info1.setMainCAP( grabItemInfo.substring(grabItemInfo.lastIndexOf('#')+1, grabItemInfo.length()));
Toast toastTest = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
Toast toastTest2 = Toast.makeText(getApplicationContext(), info1.getMainBSSID(), Toast.LENGTH_SHORT);
Toast toastTest3 = Toast.makeText(getApplicationContext(), info1.getMainCAP(), Toast.LENGTH_SHORT);
toastTest.show();
toastTest2.show();
toastTest3.show();
ContentValues dbv = new ContentValues();
dbv.put("SSID", info1.getMainSSID());
dbv.put("BSSID", info1.getMainBSSID());
dbv.put("CAPABILITIES", info1.getMainCAP());
netDataBase.insert("netDataTable", "NULL", dbv);
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
startActivity(intent);
}
});
Here is my display page:
public class Attack_Page extends Network_List {
protected void onCreate(Bundle SavedIS){
super.onCreate(SavedIS);
setContentView(R.layout.attack_page);
TextView SSIDview = (TextView) findViewById(R.id.SSIDView);
TextView BSSIDview = (TextView) findViewById(R.id.BSSIDView);
TextView CAPview = (TextView) findViewById(R.id.CAPView);
Button backButton = (Button) findViewById(R.id.backbutton);
Intent intent = getIntent();
//String MainSSIDP = intent.getStringExtra(getMainSSID());
Network_Info info1 = new Network_Info();
Toast testToast = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
testToast.show();
//Cursor IDselect = netDataBase.rawQuery("SELECT SSID FROM netDataTable WHERE SSID = "+getMainSSID()+"", wifis);
//SSIDview.setText(IDselect.toString());
backButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent bintent = new Intent(getApplicationContext(), Network_List.class);
startActivity(bintent);
}
});
}
}
Here is my setters and getters class:
public class Network_Info {
private String mainCAP;
private String mainSSID;
private String mainBSSID;
public void setMainSSID(String newMainSSID){
mainSSID = newMainSSID;
}
public void setMainBSSID(String newMainBSSID){
mainBSSID = newMainBSSID;
}
public void setMainCAP(String newMainCAP){
mainCAP = newMainCAP;
}
public String getMainSSID(){
return mainSSID;
}
public String getMainBSSID(){
return mainBSSID;
}
public String getMainCAP(){
return mainCAP;
}
}

Figured out you have to pass the variable with the intent:
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
intent.putExtra("EXTRA_SSID", info1.getMainSSID());
intent.putExtra("EXTRA_BSSID", info1.getMainBSSID());
intent.putExtra("EXTRA_CAP", info1.getMainCAP());
startActivity(intent);
Then use the key that you set in putExtra()
String MainSSIDP = intent.getStringExtra("EXTRA_SSID");
Thanks for the help though!

Related

Facing the problem from updating the data and delete data in android

I'm trying to learn the android and need your help!
Problem 1:
I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
Once I update that only create new data but not a data update
Problem 2
Once I delete the data will delete whole data but not only the specific data.
This is my timetable.java.
public class Timetable extends AppCompatActivity{
//View
RecyclerView timeTable;
RecyclerView.LayoutManager layoutManager;
DatabaseReference counterRef,currentRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ttable);
timeTable = (RecyclerView)findViewById(R.id.timeTable);
timeTable.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
timeTable.setLayoutManager(layoutManager);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
toolbar.setTitle("Time Table");
setSupportActionBar(toolbar);
counterRef = FirebaseDatabase.getInstance().getReference("Time");
currentRef = counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//online list here
updateList();
}
private void updateList() {
FirebaseRecyclerAdapter<Time, ListTimeViewHolder> adapter = new FirebaseRecyclerAdapter<Time, ListTimeViewHolder>(
Time.class,
R.layout.time_table,
ListTimeViewHolder.class,
currentRef
) {
#Override
protected void populateViewHolder(final ListTimeViewHolder viewHolder, final Time model, int position) {
viewHolder.txtEmail.setText("Time (" +model.getTime()+ ")");
viewHolder.itemClickListenener1 = new ItemClickListenener1() {
#Override
public void onClick(View view, int position) {
showUpdateDeleteLog(model.getEmail(),model.getTime());
//alert dialog
// AlertDialog alertDialog = new AlertDialog.Builder(Timetable.this).create();
//
// // Setting Dialog Title
// alertDialog.setTitle("Message");
//
// // Setting Dialog Message
// alertDialog.setMessage("Unable to click");
//
// alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // Write your code here to execute after dialog closed
// Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
// }
// });
//
// // Showing Alert Message
// alertDialog.show();
}
private void showUpdateDeleteLog(String email, String time) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Timetable.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(email);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editTextName.getText().toString().trim();
if (!TextUtils.isEmpty(name)) {
updateArtist(model.getEmail(),name);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteArtist(model.getEmail(),model.getTime());
b.dismiss();
}
});
}
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//removing artist
dR.removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//updating artist
Time artist = new Time(email,time);
dR.push().setValue(artist);
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
};
}
};
adapter.notifyDataSetChanged();
timeTable.setAdapter(adapter);
}
}
Thanks for help! I'm newbie in Android need pro to help me up! Thanks guys and this platform!
First of all, why do you need to push() after Uid? As Uid is always unique, you can remove that to easily access the child node like below:
-Time
-UID
-email
-time
Problem 1: I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
You need to get the reference of that particular node to update. For that, you can store the push Id along with email and time. Also, you don't need to push while updating.
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//updating artist
Time artist = new Time(email,time);
dR.updateChildren(artist); // instead use updateChildren
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
Once I delete the data will delete whole data but not only the specific data
Same goes for problem 2, you need that particular node to delete,
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//removing artist
dR.getRef().removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}

How to use a variable in a new activity?

I added a variable that pass form the first activity to the second one.
I want to use the info that has accepted from the first activity, at the new activity, and will save it on new double variable, display it as permanent on a textView.
Now, it appears only when I am clicking on the regular button that start the new activity.
As first step, I guess, I need to remove - "startActivity(intent1);".
How should I move on from here?
Java code:
First Activity (Name : settings.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void onClick (View v){
Intent intent = new Intent(settings.this, WaitressRecord.class);
startActivity(intent);
}
protected void onClickWait (View v) {
//--- Casting & Converting EditText "etSalaryWaitress" to Double "doubleSW".
btnWaitress =(Button)findViewById(R.id.btnWaitress);
etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
doubleSW = Double.parseDouble(etSalaryWaitress.getText().toString());
//---Casting Radio Button(s).
rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
rbShekel = (RadioButton)findViewById(R.id.rbShekel);
if (doubleSW < 100 ) {
if (rbPercentage.isChecked()) {
HafrashaP = 1 - (doubleSW / 100.0);
strHafPer = String.valueOf(HafrashaP);
Toast.makeText(settings.this, strHafPer, Toast.LENGTH_SHORT).show();
// start the SecondActivity
Intent intent1 = new Intent(this, WaitressRecord.class);
intent1.putExtra(Intent.EXTRA_TEXT, strHafPer);
startActivity(intent1);
} else if (rbShekel.isChecked()) {
HafrashaS = -doubleSW;
strHafShek = String.valueOf(HafrashaS);
Toast.makeText(settings.this, strHafShek, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(settings.this, "לא הוזנה סוג ההפרשה", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(settings.this, "מספר שגוי", Toast.LENGTH_SHORT).show();
}
}
New Activity: (Name : WaitressRecord.java)
public class WaitressRecord extends AppCompatActivity {
String strHafPer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitress_record);
// get the text from MainActivity
Intent intent1 = getIntent();
strHafPer = intent1.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(strHafPer);
}
}
//First Activity
Intent intent= new Intent(this, SecondActivity.class);
Bundle extra = new Bundle();
mBundle.putString(VARIABLE_KEY, value);
intent.putExtras(mBundle);
startActivity(intent);
//on the second Acitivty
intent intent = getIntent();
Bundle bundleExtra;
//Null Checking
if (intent != null ) {
bundleExtra = getIntent().getExtras();
// Be sure your check your "VARIABLE KEY SAME AS in THE FIRST ACTIVITY
String resultString = extras.getString("VARIABLE_KEY");
}

Cant find a way to work with Alarm manager in taskAdapter

My question is simple, I have made a bit of a mess in my TaskAdapter and now I am facing a problem with an onCreate method because I dont have it in my TaskAdapter (obviously).
Now if You could give Me some ideas on how to implement my alarmManager and link the ALARM_SERVICE so the code would work.
Heres my BaseAdapter:
'public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
AlarmManager alarmManager;
PendingIntent pendingIntent;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return 0;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+myHour+":"+myMin , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
//get all tasks from shared preferances
//the shared preferences is by key and value, therefor we will use Map collection
//we know that the key is String, but we don't know what type of value we will get. <K,?>
Map<String, ?> tasks = taskPref.getAll();
// transfer the data from map collection to list collection , single item is like the defination of the tasks <String,?>
//Entry -> record , enterSet -> set of records
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}'
I cant find a way to start
"alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE)" because I dont really know how to start it in an other way if there is a way.
Any help would be much appreciated!
Here is my AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Didnt start alarm", "Too bad...");
Intent service_intent = new Intent(context, RingtonePlayingService.class);
context.startService(service_intent);
}
}
And here is the RingtoneService:
public class RingtonePlayingService extends Service {
MediaPlayer someMedia;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("Local Services", "Received start id "+ startId+": "+intent);
someMedia = MediaPlayer.create(this, R.raw.skyrim);
someMedia.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "On destroy called!", Toast.LENGTH_SHORT).show();
}
}
Cheers.
It looks like your alarmManager field isn't being initialized.
Add this line to your TaskAdapter constructor:
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Also, you can directly call your service, no need for the BroadcastReceiver in the middle:
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
UPDATE
A service should be declared with the service tag in the manifest.
See: https://developer.android.com/guide/topics/manifest/service-element.html
<service android:name=".RingtonePlayingService" android:enabled="true"/>

How do I store data in an object rather than a class

I am trying to create a messaging app with several different xml views/classes:
one for the main menu (MainActivity);
one for the sending message screen (SendMsg);
one for storing sent messages (Logs).
In SendMsg, I want to store my message into an object called msgLog, which I had created in MainActivity. Just for testing, I have set SendMsg to display the Logs class upon pressing the SEND button, and the sent message does indeed appear there.
However, it is not storing it into the msgLog variable that I created, so that I can't access again from MainActivity.
How do I store it into a variable, so that it will always be there when I access it? Any help would be much appreciated.
=========================================================
public class MainActivity extends AppCompatActivity {
Logs msgLog = new Logs();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendOnClick (View view){
Intent intent = new Intent("com.example.android.attone.SendMsg");
startActivity(intent);
}
public void logsOnClick (View view){
Intent intent = new Intent(this, Logs.class);
startActivity(intent);
}
}
=========================================================
public class SendMsg extends AppCompatActivity {
EditText txtPhoneNo;
EditText txtMessage;
Button btnSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_msg);
txtPhoneNo = (EditText) this.findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) this.findViewById(R.id.txtMessage);
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// Get phone number and message sms
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
Intent writeLog = new Intent(getApplicationContext(), Logs.class);
writeLog.putExtra("link", message);
startActivity(writeLog);
// If phone number and message is not empty
if (phoneNo.length() > 0 && message.length() > 0)
{
sendMessage(phoneNo, message);
}
else
{
Toast.makeText(getBaseContext(), "Please enter both number and message", Toast.LENGTH_LONG).show();
}
}
});
}
// Function send message sms
private void sendMessage(String phoneNo, String message)
{
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
=========================================================
public class Logs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs);
String logging = getIntent().getStringExtra("link");
TextView textView = (TextView) findViewById(R.id.txtLog);
textView.setText(logging);
Button log2menu = (Button)findViewById(R.id.logToMenu);
log2menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
You can use SharedPreferences to store such data.
One more thing you can try if you don't want to save the data after the app closes is storing the data in a static variable of a separate class.

How to open dialer on phone with a selected number in android [duplicate]

This question already has answers here:
How do I get the dialer to open with phone number displayed?
(7 answers)
Closed 6 years ago.
I have made an application that uses Google Places API. Once I click on a place it returns the name of the company, the address and the number to the MainActivity. When I click on the number I can open the dialer but I can't seem to get the number that is returned on the MainActivity into the dialer. Any ideas on how I could go about doing this. Thanks
My Code is as follows
MainActivity
private TextView mName;
private TextView mAddress;
private TextView mNumber;
private static final LatLngBounds Sligo = new LatLngBounds(
new LatLng(54.27, -8.47), new LatLng(54.27, -8.47));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
mNumber = (TextView) findViewById(R.id.textView4);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(Sligo);
List<Integer> filterTypes = new ArrayList<Integer>();
filterTypes.add(Place.TYPE_CAR_REPAIR);
Intent intent = intentBuilder.build(MainActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST );
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final CharSequence formatted_phone_number = place.getPhoneNumber();
// final CharSequence car = place.TYPE_CAR_REPAIR();
//public abstract List<Integer> getTypeFilter(place.TYPE_CAR_REPAIR);
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(name);
mAddress.setText(address);
mAttributions.setText(Html.fromHtml(attributions));
mNumber.setText(formatted_phone_number);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
onClick event
public void onClickNumber(View arg)
{
Intent intent = new Intent(Intent.ACTION_DIAL);
startActivity(intent);
}
The number is at the bottom of the screen
Try This
String phone = mNumber.getText().toString();
Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.fromParts(
"tel", phone, null));
startActivity(phoneIntent);
Try this.
String number = "494498498";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" +number));
startActivity(intent);

Categories

Resources