0

im having trouble getting a string (containing a URL) from one activity to another. I've tried using intent but that didn't work.

I've got a main activity setting up the tabhost with tabs. There are 3 tabs, one with a barcode scanner, one with a search field and a webview.

The barcode scanner and search field create a string containing a Url i want the webview to show.

Could someone please tell me I'm missing something or how i could do this better?

My main activity

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setTabs() ;
}
private void setTabs()
{
    addTab("Home", R.drawable.tab_home, HomeActivity.class);
    addTab("Search", R.drawable.tab_search, SearchActivity.class);
    addTab("Play", R.drawable.tab_favorite, FavoriteActivity.class);
}

private void addTab(String labelId, int drawableId, Class<?> c)
{
    TabHost tabHost = getTabHost();
    Intent intent = new Intent(this, c);
    TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId); 

    View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
    TextView title = (TextView) tabIndicator.findViewById(R.id.title);
    title.setText(labelId);
    ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
    icon.setImageResource(drawableId);

    spec.setIndicator(tabIndicator);
    spec.setContent(intent);
    tabHost.addTab(spec);
}

public void switchTab(int tab){
    TabHost tabHost1 = getTabHost();
    tabHost1.setCurrentTab(tab);
}

The webview tab

public class WebviewActivity extends Activity {
WebView webView;
String url;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.favoritepage);

    url = "http://www.google.nl";

    webView = (WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
            // Handle the error
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
    webView.loadUrl(url);

    if (savedInstanceState != null)
        ((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}

protected void onSaveInstanceState(Bundle outState) {
    webView.saveState(outState);
 }
}

and the search tab

public class SearchActivity extends Activity implements OnClickListener {
Button searchButton;
TextView searchText;
TextView searchResultText;
String zoekopdracht, completeTrailerUrl, searchUrl;
String baseURL = "http://not_needed_here";
String endURL = "End_of_url";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searchpage);

    searchText=(TextView)findViewById(R.id.searchText);
    searchResultText=(TextView)findViewById(R.id.searchResultText);

    searchButton=(Button)findViewById(R.id.searchButton);
    searchButton.setOnClickListener(this);

}

@Override
public void onClick(View buttonId) {
    // TODO Auto-generated method stub
    switch (buttonId.getId()){
    case R.id.searchButton :
        zoekopdracht = searchText.getText().toString();

        StringBuilder completeURL = new StringBuilder(baseURL);
        completeURL.append(zoekopdracht + endURL);
        searchUrl = completeURL.toString();

        /**start de thread om de xml zoekopdracht te doen */
        new Thread(new Runnable() {
            public void run() {
                try {
                    URL website = new URL(searchUrl);

                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    XMLReader xr = sp.getXMLReader();

                    HandlingXMLStuff doingWork = new HandlingXMLStuff();
                    xr.setContentHandler(doingWork);
                    InputSource is=new InputSource(website.openStream());
                    xr.parse(is);

                    completeTrailerUrl = doingWork.getInformation();


                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
          }).start();
        searchResultText.setText(completeTrailerUrl);
        //I want completeTrailerUrl to be loaded in the webview
        break;
    }
}
}

In reaction to Barrel

I've changed the receiving class into this, but i think this is where i'm going wrong.

public class FavoriteActivity extends Activity {
WebView webView;
String url;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.favoritepage);

    // part submitted by Cool Compiler
    Intent t=getIntent();
    Bundle k = t.getExtras();
    url=k.getString("stringToPassOn");

    if (url != null){
        url = "http://www.google.nl";


    }

    webView = (WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
            // Handle the error
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
    webView.loadUrl(url);

    if (savedInstanceState != null)
        ((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}

protected void onSaveInstanceState(Bundle outState) {
    webView.saveState(outState);
 }
}

when running this, the webview is all black and on rotate it crashes

06-22 13:32:45.380: W/dalvikvm(1630): threadid=1: thread exiting with uncaught exception (group=0x40a51228)
06-22 13:32:45.400: E/AndroidRuntime(1630): FATAL EXCEPTION: main
06-22 13:32:45.400: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to stop activity {com.georgekroon.player/com.georgekroon.player.TUplayerV2Activity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.georgekroon.player/com.georgekroon.player.FavoriteActivity}: java.lang.NullPointerException
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3505)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3585)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3783)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.access$700(ActivityThread.java:139)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:156)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5005)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invokeNative(Native Method)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:511)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at dalvik.system.NativeStart.main(Native Method)
06-22 13:32:45.400: E/AndroidRuntime(1630): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.georgekroon.player/com.georgekroon.player.FavoriteActivity}: java.lang.NullPointerException
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:1992)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.LocalActivityManager.dispatchStop(LocalActivityManager.java:579)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityGroup.onStop(ActivityGroup.java:82)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1266)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.Activity.performStop(Activity.java:4706)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3500)
06-22 13:32:45.400: E/AndroidRuntime(1630):     ... 12 more
06-22 13:32:45.400: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException
06-22 13:32:45.400: E/AndroidRuntime(1630):     at com.georgekroon.player.FavoriteActivity.onCreate(FavoriteActivity.java:25)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:4543)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
06-22 13:32:45.400: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2158)
06-22 13:32:45.400: E/AndroidRuntime(1630):     ... 19 more
George
  • 76
  • 9

2 Answers2

3

Use a Bundle.

In your activity add something like

Bundle bundle = new Bundle ();
bundle.putSerializable("stringToPassOn", YOUR_STRING);

Intent xxx;
xxx.putExtras (bundle);
startActivityForResult (xxx, 0);

And you retrieve the information later on via:

Bundle bundle = this.getIntent().getExtras();
String myText = (String) bundle.getSerializable ("stringToPassOn");
barrel
  • 974
  • 7
  • 16
  • I've tried that, but the webview does not seem to respond to it – George Jun 22 '12 at 08:57
  • This answer is found in some other allmost similar problems and I did try this first. The webview remains a black screen (not even white) and crashes on rotation – George Jun 22 '12 at 09:12
  • The first part is done just before you call a new activity. I.e. you click on a button, you create the intent, put the bundle on it and then and start the new intent. In the 'onCreate' of the new intent, you can then retrieve the information by the second part of the code examples. Is this what you have done? Do you have a stacktrace? – barrel Jun 22 '12 at 10:49
  • I think the problem is that i got the second (receiving part) in the onCreate part.. It should be receiving it just when it is submitted, not just onCreate, putting something together now and will submit it again – George Jun 22 '12 at 11:30
  • Line 25 of your FavoritAction, which line is it? Your check on whether the URL != null is incorrect, it should be 'if (url == null)'. In your code the URL will be overwritten if it already has a value. If it is null, it remains null. Might this be the cause of the Nullpointer? – barrel Jun 22 '12 at 11:47
  • indeed, good one.. but not THE one screen is still black and crash on rotate (null pointer) – George Jun 22 '12 at 12:23
  • at com.georgekroon.player.FavoriteActivity.onCreate(FavoriteActivity.java:25) Which one is line 25? What exactly does it say? – barrel Jun 22 '12 at 12:26
  • line 25 says url=k.getString("stringToPassOn"); line 27 is if (url == null){ – George Jun 22 '12 at 12:36
  • If think you initiiate the activity in an incorrect way. The forementioned code works if you start the activity by creating the intent and then start the activity with this intent (startActivityForResult (your_intent, 0)). I have added this line to the code example – barrel Jun 22 '12 at 12:50
  • but the activity is initially started by the tabhost, so that is why that activity crashes right? – George Jun 22 '12 at 13:07
  • Indeed. Check this link for more information: http://stackoverflow.com/questions/5221940/using-bundle-and-intent-with-tabhost – barrel Jun 22 '12 at 13:10
0

you need to use bundles.. and it must work fine then. eg.;

                     s=new Intent(Format1.this, Format17.class);
                    d=new Bundle();
                    d.putString("userId", userId);
                    d.putString("surveyId", surveyId);
                    d.putInt("quesNo", ques_no);
                    s.putExtras(d);
                    startActivity(s);

now in next class you can retrieve values like this

Intent t=getIntent();
    Bundle k=t.getExtras();
    surveyId=k.getString("surveyId");
    userId=k.getString("userId");
    ques_no=k.getInt("quesNo");

Try this....

Cool Compiler
  • 857
  • 2
  • 9
  • 20
  • sorry, but what are the Format1 and Format17 pointing to? besides, this looks like the answer "barrel" gave – George Jun 22 '12 at 10:13
  • format1 is the name of the current activity and format17 is the name of next activity where you want to send the string. in your case instead of format17 u will write WebviewActivity. – Cool Compiler Jun 22 '12 at 10:54