How to show google profile name in another activity - java

Hello i am building one app which will take google profile name and then it will be displayed in another activity as EditText.
ActivityGoogle
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
textView_name.setText(personName);
textView_email.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ 400;
new LoadProfileImage(imageView_profile_image).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
any idea how to take name from this and display it in EditText
ActivityUser
profilename = (EditText)findViewbyId(R.id.profilename);

(I posted it as a comment but I think it solved the issue, so I post it as answer and add some explanation)
Have a look at these links : 1 2 3. A Bundle is exactly what you need.
This code is taken from one of the links and it's what you need. It saves a value on the Bundle:
ActivityGoogle
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value); // <-- key is the same
Then, on your ActivityUser add the following (note that key variable must be the same in both Activity):
ActivityUser
String value = getIntent().getExtras().getString(key); // <-- as the key here

Related

Can I use 2 bundle in one Activity (Android Studio)?

My app is a quiz app with two levels, so I have 3 Activities:
"beginner level", "advance level" and "result".
I want the "result" Activity to take the result from the "beginner" and "advance" activities .
I try this code on "beginner" activity :
Intent in = new Intent(getApplicationContext(),resultBage.class);
in.putExtra("correct",correct);
in.putExtra("wrong",wrong);
startActivity(in);
on "advance" activity :
Intent a = new Intent(getApplicationContext(),resultBage.class);
a.putExtra("correct2",correct2);
a.putExtra("wrong2",wrong2);
startActivity(a);
on "result" activity :
Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);
}
Bundle bundle2 = getIntent().getExtras();
if(bundle2 != null){
int correct2 = bundle2.getInt("correct2",0);
int wrong2 = bundle2.getInt("wrong2",0);
corText.setText("correct = "+correct2);
wrongTex.setText("wrong = "+wrong2);
}
The problem is it's work fine if I use just one bundle what can I do?
note : I also try StringBuffer but it's same problem
StringBuffer bcResult = new StringBuffer();
bcResult.append("Correct answers: " + beginner.correct + "\n");
StringBuffer brResult = new StringBuffer();
brResult.append("Wrong Answers: " + beginner.wrong + "\n");
corText.setText(bcResult);
wrongTex.setText(brResult);
You can't get extra data from one activity into a 3-level activity like you're trying to do. You can use shared preferences to save the data in one activity and then access any other activity you wish.
BTW, you can achieve in the following way what you're looking for.
You have to pass data from one activity to another and then another into the next including the data from 1st activity.
In your 2nd activity, you have to do like this:
Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);
}
Intent a = new Intent(getApplicationContext(),resultBage.class);
a.putExtra("correct",correct);
a.putExtra("wrong",wrong);
a.putExtra("correct2",correct2);
a.putExtra("wrong2",wrong2);
startActivity(a);
This doesn't work due to the same non-null Bundle being returned in both cases. You should use Bundle.containsKey to check which keys are present to figure out which of the two sets of parameters is being passed.
Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
int correct2 = bundle2.getInt("correct2",0);
int wrong2 = bundle2.getInt("wrong2",0);
if(correct !=null && wrong !=null){
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);}else{
corText.setText("correct = "+correct2);
wrongTex.setText("wrong = "+wrong2);}
}

Passing phone number or CONTACT_ID from android contact details to activity (whatsapp like)

What I'm trying to achieve is to add shortcut to my app in android book contact details, similar to what whatsapp is doing.
I've been following this tutotial: http://blogs.quovantis.com/syncing-contacts-with-an-android-application-2/ and it works well but the author doesn't show how to pass data from contact details to ViewingActivity: https://github.com/ajkh35/ContactsDemo/blob/master/app/src/main/java/com/example/ajay/contacts_4/ViewingActivity.java
There was some comments below the article but no specific answer from the author, can't find anything useful in
Uri data = getIntent().getData(); //content://com.android.contacts/data/1169
List<String> params = data.getPathSegments();
String first = params.get(0);
String second = params.get(1);
there is some number passed in second param but it's not CONTACT_ID or RAW_CONTACT_ID. Any help?
Ok, so it seems the Uri you're getting from the Contacts app is a Data uri.
Data rows contain info about a specific data-item (like a phone number or an email) of a specific RawContact, so a single Data row "belongs" to a single RawContact which "belongs" to a single Contact.
Luckily, the ContactsContract API allows for implicit joins when querying the Data table, so you can do something like this:
Uri dataUri = getIntent().getData(); //content://com.android.contacts/data/1169
String[] projection = new String[]{
Data.CONTACT_ID,
Data.RAW_CONTACT_ID,
Data.DISPLAY_NAME,
Data.MIMETYPE,
Data.DATA1};
Cursor cur = getContentResolver().query(dataUri, projection, null, null, null);
cur.moveToFirst(); // there should always be exactly one result, since we have a specific data uri here
Log.i("Contact Info", "Got info: id=" + cur.getLong(0) + ", raw-id=" + cur.getLong(1) + ", " + cur.getString(2) + ", " + cur.getString(3) + ", " + cur.getString(4));
cur.close();
I know this is a very late response but checkout the following code.
class MessageActivity : AppCompatActivity() {
private val TAG: String = javaClass.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_message)
if(intent != null && intent.data != null) {
Log.e(TAG, intent.data.toString())
var contactName = ""
val cursor = contentResolver.query(intent.data!!,
arrayOf(ContactsContract.Data.DATA1,ContactsContract.Data.DATA2,ContactsContract.Data.DATA3),
null,null,null)
if(cursor != null && cursor.moveToFirst()) {
do{
Log.e(TAG, cursor.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Data.DATA1)))
contactName = cursor.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Data.DATA2))
Log.e(TAG, contactName)
Log.e(TAG, cursor.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Data.DATA3)))
}while (cursor.moveToNext())
cursor.close()
}
messaging_text.text = getString(R.string.messaging) + " $contactName"
}
}}
So when you register a contact you set some Data1, Data2 and Data3 values. Data3 is what gets displayed in the contacts. You can set Data1 and Data2 some value you like and then retrieve it like in the code I mentioned above.
You can also checkout my blog here. Look for the "Sync Service" section, towards the end you will find the MessageActivity.
Thanks & regards

How to properly append text to TextView from SharedPreferences file instead of overwriting it?

I have two classes, one class is saving weight, then in the other class/ activity I want a log that appends the weight along with the date and time, then makes a new line and displays the next weight. This way the user can keep track of their daily weight changes.
Problem is I'm brand new to Java and clearly am getting stuck on a silly problem. Each time I try append it instead just overwrites. I probably need to save it and then add it? maybe? I've tried a few different things and nothing is working all that well.
This is day 3 of Java. Apologies.
Tried making a list that is saved with sharedpreferences. Either did it wrong or it didnt work. Also tried just calling for the weight and appending it, but it overwrites it all.
My Logging activity:
public class LogActivity extends AppCompatActivity {
TextView logger;
//TextView more;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button back = findViewById(R.id.btnBack);
logger = findViewById(R.id.txtLog);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
SharedPreferences log = getSharedPreferences("MyPrefsFile", 0);
//Float value = log.getFloat("floatingLog",0);
Float value = log.getFloat("weight", 0);
//more.append(logger + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
logger.append("Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
// Adding back button
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
// SharedPreferences settings7 = getSharedPreferences("PREFS",0);
// String wordsString = settings7.getString("words","");
// String[] itemWords = wordsString.split(",");
// List<String> items = new ArrayList<String>();
// for (int i = 0; i < itemWords.length; i++){
// items.add(itemWords[i]);
// }
// for (int i = 0; i < items.size(); i++){
// Log.d("list", items.get(i));
// }
}
}
This is getting the sharedpreferences from here, in my ProfileActivity:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.txtWeight)).setText(findViewById(R.id.txtNewWeight).toString());
floatingLog = weight.toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
floatingWeight = Float.valueOf(newWeight.getText().toString());
editor.putString("floatingLog", floatingLog);
editor.putFloat("weight", floatingWeight);
editor.apply();
editor.commit();
weight.setText(String.valueOf(floatingWeight));
Hello and welcome to SO!
actually in TextView, you can access to current value via TextView#getText() and after that you can update the text value similarly using TextView#setText(String text)
so you need to write something like this:
String currentText = logger.getText();
String updatedText = currentText + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n";
logger.setText(updatedText)
tada !
UPDATE
I think your problem is with how you save your records in your sharedPrefs
in this line
editor.putFloat("weight", floatingWeight); in this part you are overwriting the existing value,
simplest approach that comes to my mind is that instead of saving weight like this, you create an array of weights and append to end of it every day and store the array.
how ever it will be far more better if you use data base for this which gives you far more flexibility.
to use database take a look at Android official orm Android Room it is very simple and straightforward

Android - Pick multiple contacts

I'm aware that there is some old answer on here regarding on how to do this but was hoping for a more updated version.
I want to let the user pick multiple contacts from their phone and add it to an array.
I'm using ContactContract with PICK_CONTENT.
So far I have got the following:
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode,resultCode,data);
switch (reqCode){
case(PICK_CONTACT):
if(resultCode == Activity.RESULT_OK){
Uri contactData = data.getData();
Cursor phone = getContentResolver().query(contactData,null,null,null,null);
PlayerDetails player = new PlayerDetails(); //TODO turn this into a loop to add each player the user picks and then display it
if(phone.moveToFirst()) {
player.name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
player.number =phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
playerListGame.addPlayer(player);
But this clicking a button to launch this activity and then :
public void showPlayerGameList(){
playerTextView = findViewById(R.id.aPlayerBox);
for(PlayerDetails i : playerListGame.myPlayers){
playerTextView.append(i.name + "\n" + i.number); //TODO sort this out so it doesnt repeat the same names
}
}
Then I loop through the array I add it to, to display the info I need.
I don't know how to get the application to allow the user to select multiple users
Thanks
I know it is late but i hope someone else or even you can implement in this way.
Launching CONTACTS intent with PICK_CONTACT will not be able to pick multiple contacts. Even if you manage to select multiple contacts on some device, It would not work on most of the other devices and versions of android systems. As i have tried in the same way before..
Then created a listview with multiple choce and given a list of contacts to adapter of the listview. Now how to get contacts list..
ContactsList = new ArrayList<String>();
ContactsNumbersList = new ArrayList<String>();
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
// Contacts Database queries
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY +" ASC");
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumber = phoneNumber.replace("-","");
phoneNumber = phoneNumber.replace(" ","");
phoneNumber = phoneNumber.replace("(","");
phoneNumber = phoneNumber.replace(")","");
if (normalizedNumbersAlreadyFound.add(phoneNumber))
{
ContactsList.add(name);
ContactsNumbersList.add(phoneNumber);
}
}
cursor.close();

Create a List of saves from one button

I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}
You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}

Categories