-1

how can i get a string from the non activity java class ! i have used interface to send string from non activity java class to activity!

from this class file i have to pass the string Url.

public abstract class  CustomTabsURLSpan extends URLSpan implements Parcelable{

    String url;

    public CustomTabsURLSpan(String url) {
        super(url);
    }

    public void getLink(String url){
        this.url = url;
    }

    private OnSendUrl onSendUrl;

    public interface OnSendUrl{
        void singleUrl(String url);
    }

    @Override
    public void onClick(View widget) {
        Log.d("link",getURL()+"");
        url= getURL();
        onSendUrl.singleUrl(url); // throws null pointer Exception
    }

}

i need to get string here->>

public class MainActivity extends AppCompatActivity implements CustomTabsURLSpan.OnSendUrl{


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

    @Override
    public void singleUrl(String url) {
        Log.d("url",url);
    }

}

1 Answers1

1

The initial problem in your code is that onSendUrl was not initialised. This brings us to how you will initialise it, which may also raise another issue of how to know if the instance you are assigning to it is valid. A simple way to achieve that is to introduce a variable that can be cast and assigned to onSendUrl. In my simple implementation, I use a Context as an implementation of the OnSendUrl interface and the use case you gave also happens to be an Activity, which has a Context. My simple implementation is shown below:

public CustomTabsURLSpan(Context context,  String url) {
        super(url);
        this.context = context;
        if (context instanceof OnSendUrl) {
                mListener = (OnSendUrl) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement OnSendUrl");
            }
    }