-2

I have 2 classes. in first one I have 2 button and 2 string.two button starts same class. but if user press first button I want to send first string into second class's string. if choose other one I want to send second string.

Main Class

public String sendedUrl;
String url = "xxx";
String url2="yyy";

  imageViews[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendedUrl=url;
            Intent intent = new Intent(getApplicationContext(),Second.class);
            startActivity(intent);
            finish();
        }
    });
    imageViews[1].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendedUrl = url2;
            Intent intent = new Intent(getApplicationContext(),Second.class);
            startActivity(intent);
            finish();
        }
    });

Second Class

MainActivity main = new MainActivity();
String Url;
Url = main.sendedUrl;
PriyankaChauhan
  • 953
  • 11
  • 26
furkan
  • 1
  • 3

3 Answers3

2

When you creating an instance of a class the members of this class are set to null if you have not assigned any value to that particular member of that class.

You can make this member static or you can use

intent.putExtra("StringName");

to pass this member to other activity.

RamenChef
  • 5,557
  • 11
  • 31
  • 43
Arun Dey
  • 186
  • 4
0

You have to use Bundle to passing values like:

imageViews[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendedUrl=url;
            Intent intent = new Intent(getApplicationContext(),Second.class);
            intent.putExtra("strUrl", url);
            startActivity(intent);
            finish();
        }
    });
    imageViews[1].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendedUrl = url2;
            Intent intent = new Intent(getApplicationContext(),Second.class);
            intent.putExtra("strUrl", url2);
            startActivity(intent);
            finish();
        }
    });  

Inside your Second Activity in OnCreate():

Bundle extras = intent.getExtras(); 
String url= extras.getString("strUrl");
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
Kuldeep Kulkarni
  • 796
  • 5
  • 20
0

If Main and Second class are Activities u can pass URL intent. e.g

Intent intent=new Intent(this,Second.class);
intent.putExtra("URL",url)//url2 on 2nd button click
startActivity(intent);
finish();

and get URL in Second Activity

Intent  intent=getIntent();
String URL=intent.getStringExtra("URL");
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
Developer
  • 183
  • 8