简体   繁体   中英

Different Behaviors of Activity when Opened from two Different Activities in Android

Before I asked this question I really looked at different answers on StackOwerflow for days, but I couldn't find an answer.

This is my what I am doing - I have an app that has UserProfileActivity , which I want to be able to open from 2 different activities - from myContactsListActivity and from messageActivity . Data I want sent in my UserProfileActivity contains userId , userName , profilePhooto , and aboutUser . In the first case I want to pass this data via intent from myContactsListActivity , and in the second I want to pass only userId from myContactsListActivity and make a call to get data from the server.

This is how I do it right now. When it is open from myContactsListActivity , I use intents to pass the data to UserProfileActivity , and pass only userId from messageActivity , and use if else to determine what intent is called.

In short: Activity A can be opened from activity B and C. I need two different behaviors. If it is opened form B everything is passed via intent, and if it is opened from C only userId is passed and there is a call to server. How would I determine from which activity was opened, and what is the best way to set different behaviors .

Here is my code, IT WORKS , but I am not happy with it, and I am looking for a better solution:

TextView textViewUserName, textViewAbout;
ImageView imageView;
Toolbar toolbar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_profile);

    Intent intent = getIntent();
    final String userId = intent.getStringExtra("userId");
    String userName = intent.getStringExtra("userName");
    String about = intent.getStringExtra("about");
    String image = intent.getStringExtra("image");

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    textViewUserName = (TextView) findViewById(R.id.contactUsername);
    textViewAbout = (TextView) findViewById(R.id.aboutMe);

    ColorGenerator generator = ColorGenerator.MATERIAL; 
    final int color = generator.getColor(userId);
    TextDrawable.IBuilder builder = TextDrawable.builder()
            .beginConfig()
            .withBorder(1)
            .endConfig()
            .rect();

    if (userName != null) {

        String firstLetter = intent.getStringExtra("userName").substring(0, 1);

        TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
        imageView = (ImageView) findViewById(R.id.profile_image);
        imageView.setImageDrawable(textDrawable);
        Picasso.with(this)
                .load("http://192.168.0.13/mynewapp/profilephotos/" + image)
                .placeholder(textDrawable)
                .error(textDrawable)
                .centerCrop()
                .fit()
                .into(imageView);
        getSupportActionBar().setTitle(userName);

        Intent commentDescriptionIntent = new Intent(this, AboutFragment.class);
        commentDescriptionIntent.putExtra("userId", userId);
        commentDescriptionIntent.putExtra("userName", userName);
        commentDescriptionIntent.putExtra("about", about);
        setIntent(commentDescriptionIntent);

    } else {
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<ContactResponse> call = apiService.userExists(userId);
        call.enqueue(new Callback<ContactResponse>() {
            @Override
            public void onResponse(Call<ContactResponse> call, retrofit2.Response<ContactResponse> response) {
                Contact contact = response.body().getResults();

                String firstLetter = contact.getUserName().substring(0, 1);
                TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
                imageView = (ImageView) findViewById(R.id.profile_image);
                imageView.setImageDrawable(textDrawable);
                Picasso.with(getApplicationContext())
                        .load("http://localhost/mynewapp/profilephotos/" + contact.getThumbnailUrl())
                        .placeholder(textDrawable)
                        .error(textDrawable)
                        .centerCrop()
                        .fit()
                        .into(imageView);

                CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
                String userName = contact.getUserName();
                collapsingToolbarLayout.setTitle(userName);
            }

            @Override
            public void onFailure(Call<ContactResponse> call, Throwable t) {
                // Log error here since request failed
                Log.e(TAG, t.toString());
            }
        });
    }

Try using an another extra value with your Intent .

For example:

From ActivityB :

    Intent intent = new Intent(ActivityB.this, ActivityA.class);
    intent.putExtra("FROM_ACTIVITY", "B");
    // Others extra values
    startActivity(intent);

From ActivityC :

    Intent intent = new Intent(ActivityC.this, ActivityA.class);
    intent.putExtra("FROM_ACTIVITY", "C");
    // Others extra values
    startActivity(intent);

Do this in your ActivityA :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_profile);


    String fromActivity = getIntent().getStringExtra("FROM_ACTIVITY");

    if(fromActivity.equals("B")) {
        // Do something
    } else if(fromActivity.equals("C")) {
        // Do something
    }
}

Hope this will help~

This is how I would go on doing this, We can use fragments to load on activities, depending on the different state of the activity,

So you can have 2 different fragments. Will probably load the same UI/xml view, But behave differently, One just set the values coming from the intent. and Other loading stuff from an external api.

Note:

Try to use a loader to load stuff from an external api. that has its own call backs that you can use to load data after they are being received.

This is more of a high level idea, Let me know if you have any further questions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM