Intent not working, crashes the application - android

I am building this app and I can't make it work. Here is the code and if you find the problem please post the solution.
This is the Main Activity
package in.isuru.caf;
//imports imported here. removed to simplify the code.
public class MainList extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] main_items_array = getResources().getStringArray(R.array.main_items);
setListAdapter(new ArrayAdapter<String>(MainList.this, android.R.layout.simple_list_item_1, main_items_array));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList = (String) (lv.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), selectedFromList, Toast.LENGTH_SHORT).show();
if(selectedFromList.contains("Top 20 Questions")){
Intent mainIntent = new Intent(MainList.this, in.isuru.caf.Top20Questions.class);
startActivity(mainIntent);
}
}
});
}
}
This is the second activity.
package in.isuru.caf;
import in.isuru.caf.R;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class Top20Questions extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.forums.catholic.com/forumdisplay.php?f=4&daysprune=-1&order=desc&sort=views");
setContentView(R.layout.top_20_questions);
}
}
This is the AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.isuru.caf"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".MainList" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Top20Questions"></activity>
</application>
</manifest>
And I am getting this error.
01-21 12:18:44.231: E/AndroidRuntime(1767):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{in.isuru.caf/in.isuru.caf.Top20Questions}:
java.lang.NullPointerException

You must call the setContentView() method before trying to access any resources.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.top_20_questions);
WebView myWebView = (WebView) findViewById(R.id.webview);
...
...
}

Try this:
Intent mainIntent = new Intent(MainList.this, Top20Questions.class);
startActivity(mainIntent);

The problem is in the order of the instructions:
setContentView(R.layout.top_20_questions);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("...");
You have to set the content view first, then look for a view with a given id.

you need to fix your second activity.
see below:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.top_20_questions);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.forums.catholic.com/forumdisplay.php?f=4&daysprune=-1&order=desc&sort=views");
}

you need to call setContentView(..) before trying find any views. So put your setContentView(..) just after super.onCreate(..) in your second activity and it should work fine.

You forgot the following line on your Top20Questions class:
setContentView(R.layout.your_layout);

First Set content view by using setContentView then try to use IDs from it . then only above code will work

you need to setContentView(R.layout.top_20_questions);

Related

How to remove the white screen before the webview load?

I am creating an app that loads a website through the webview, and before it shows a splash screen. The problem is that after the splash screen a white screen appear and then the webview loads.
I don't want to use a timer in the splash scree, I want it to be gone once the webview is loaded. I saw that I need to move the splash activity to the main activity, but I am not sure how. I am a beginner with android studio.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.atlasdatabase">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".SplashActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
<activity
android:name=".MainActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
</activity>
</application>
</manifest>
MainActivity.java:
package app.atlasdatabase;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import static app.atlasdatabase.R.style.AppCompatAlertDialogStyle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
WebView myWebView = (WebView) findViewById(R.id.atlasdatabase);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
/**
* Exit the app if user select yes.
*/
private void doExit() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this, AppCompatAlertDialogStyle);
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exitmsg);
alertDialog.setNegativeButton(R.string.no, null);
alertDialog.show();
}
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.atlasdatabase);
if(webView.canGoBack()){
webView.goBack();
}else{
/* Close the app without the Dialog
super.onBackPressed();
*/
/* Use the dialog to Exit the App */
doExit();
}
}
}
SplashActivity.java:
package app.atlasdatabase;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
tools:context="atlasdb.atlasdatabase.MainActivity">
<WebView
android:id="#+id/atlasdatabase"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
background_splash.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<item android:drawable="#color/colorPrimary"/>
<!-- Image at the center of the screen -->
<item>
<bitmap android:gravity="center" android:src="#drawable/splash"/>
</item>
</layer-list>
I found the simplest answer in
How to manage the Blank White Loading screen of an Android Webview?, which helped me to solve the problem I was facing without any Splash activity Screen:
In Android manifest:
<activity android:name=".MainActivity"
android:theme="#style/Splash">
...
and on Activity, after creating webView, set the background to be transparent.
myWebView = (WebView)findViewById(R.id.webView);
myWebView.setBackgroundColor(Color.TRANSPARENT);
(I have added progress bar popup and killed on pageFinished for users to know loading is in progress.)
Here in the answer you can see comments where you need to concern.
You don't need a SplashActivity for this.
You can keep a view which is match_parent to the root view (so it will go full screen) and add your image or whatever to that.
When your Activity loads make sure it is visible/or like in the code given # onPageStarted if the view is not loaded yet, you can display your logo..
When the web view is ready as in the comment # onPageFinished make your splashView invisible or view gone!
for these tasks you can use android:visibility="gone" in Xml, yourRootViewWithImage.setVisibility(View.VISIBLE);
yourRootViewWithImage.setVisibility(View.GONE); use these lines in proper places!
Credit goes to this post, example :
public class MainActivity extends AppCompatActivity {
private boolean loadingFinished = true;
private boolean redirect = false;
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
myWebView = (WebView) findViewById(R.id.atlasdatabase);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("file:///android_asset/index.html");
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(
WebView view, WebResourceRequest request) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
myWebView.loadUrl(request.getUrl().toString());
return true;
}
#Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED // HIDE YOUR SPLASH/LOADING VIEW
} else{
redirect = false;
}
}
});
}
/// below code ..
}
I've experienced this problem before and this is just a hack , but i had the same problem and for some reason that i'm still reading why but changing the web view from opening from a fragment to an activity made the white screen at the start of loading the web view went away.

Android Main activity with 2 button to open the 2nd activity in webview

Hi I am new to android.
My main activity has show 2 buttons. If user click button 1 it to open google website in webview and for button 2 to open yahoo website in webview. I do not want open in any other browser.
Here is my code; but it is not working can any one please tell me what am I doing wrong here.
package com.jo.mavselect;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class SelectRm extends Activity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_rm);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_rm, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called when the user clicks the Send button */
public void sendMessage(View v) {
if(v.getId()==R.id.B9)
{
message ="www.google.com.au";
}
else
if(v.getId()==R.id.B10)
{
message ="www.google.com.au";
}
Intent intent = new Intent(this, MavisActivity.class);
intent.putExtra("msg",message);
startActivity(intent);
}
}
**MavisActivity **
package com.jo.mavselect;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;
public class MavisActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
setContentView(mWebView);
mWebView =(WebView) findViewById(R.id.Webview);
mWebView.setWebViewClient(new WebViewClient());
// web page to fit to the screen
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
// Not to cache
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setAppCacheEnabled(false);
// Enable Java script
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// No to cache
mWebView.clearCache(true);
//Clears any saved data for web forms.
mWebView.clearFormData();
//Tells this WebView to clear its internal back/forward list.
mWebView.clearHistory();
Intent intent = getIntent();
String ur = intent.getExtras().getString("msg");
mWebView.loadUrl(ur);
final Activity activity = this;
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
}
});
}
}
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jo.mavselect" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jo.mavselect.MavisActivity"
android:label="MavisActivity"
android:parentActivityName="com.jo.mavselect.SelectRm" >
// android:label="#string/app_name" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jo.mavselect.SelectRm" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
activity xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".SelectRm/">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Goole"
android:id="#+id/B9"
android:layout_marginTop="60dp"
android:layout_alignParentTop="true"
android:onClick="sendMessage" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yahoo"
android:id="#+id/B10"
android:layout_toEndOf="#+id/B9"
android:layout_marginLeft="84dp"
android:layout_alignTop="#+id/B9"
android:layout_toRightOf="#+id/B9"
android:onClick="sendMessage" />
<WebView
android:id="#+id/Webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You make totally wrong way.
You should try to fix your layout. Remove this line code mWebView = new WebView(this);
setContentView(mWebView); And replace with setContentView(R.layout.activity_xml); In xml file add this line code in your web view element. android:layout_below="#id/B9"
You must add onClickListener method for those buttons. In this listener set what page to open with web view.
Add method in your activity class:
public void sendMessage(View v)
{
if(v.getId() == R.id.B9){
mWebView.loadUrl("http://www.google.com");
}
if(v.getId() == R.id.B10) {
mWebView.loadUrl("http://www.yahoo.com");
}
}

Not able to play video in Web View

i am not able to play video on Android web view.
I have kept the html and video file in my assets folder.
Whenever i load the html file , it gives me the error
05-01 12:31:16.092: E/MediaResourceGetter(17241): Unable to read file: file:///android_asset/MediaBook2%20(2)/2B952499A0E681.mp4
And whenever i press on the play button i get the following error
05-01 12:31:23.680: E/chromium(17241): [ERROR:webmediaplayer_android.cc(328)] Not implemented reached in virtual void content::WebMediaPlayerAndroid::setRate(double)
05-01 12:31:23.710: E/MediaPlayer(17241): error (1, -2147483648)
05-01 12:31:23.710: E/MediaPlayer(17241): Error (1,-2147483648)
Am able to load any remote video and run,But problem is when i load the local video from the assets folder
Code to load the files and setup the web view
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Remove title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_webview);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
// Keep the webview setup ready
setupWebView();
}
public void setupWebView()
{
webView = (WebView) findViewById(R.id.webView);
// progressBar = (ProgressBar) findViewById(R.id.progressBarForWebView);
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webViewSettings.setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.setSoundEffectsEnabled(true);
webView.setWebViewClient(new SLCWebViewClient());
webView.setWebChromeClient(new WebChromeClient());
loadContentsInWebView();
}
public void loadContentsInWebView()
{
String localURL = "file:///android_asset/MediaBook2 (2)/SampleForVideo.html";
logger.debug("WebView URL: {}", localURL);
try {
webView.loadUrl(localURL);
}
catch (Exception e) {
e.printStackTrace();
logger.error("Error while loading url", e);
}
}
private class SLCWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.setWebChromeClient(new WebChromeClient()
{
private View mCustomView;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
});
webView.loadUrl(url);
return true;
}
The Sample For Video.html code
<!DOCTYPE html>
<html>
<title>Testing for Video</title>
<body>
<video width="320" height="240" controls>
<source src="2B952499A0E681.mp4">
</video>
</body>
</html>
Code for the layout file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/fullscreen_custom_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"/>
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
cheers,
Saurav
Thanks to Marcin for his answer.
I could run the the html files by loading the video.
My problem was i was using /MediaBook2 (2)/SampleForVideo.html. But the '/' should be removed when loading from assets. I splitted the string by trimming off the '/' and it worked.
But that was just a sample scenario i was working on to clear my understanding.
I have a much bigger folder structure and now when the .mp4 file is eventually loaded.
The media player is shown but the player is not playing any file.
The file:///android_asset protocol is a WebView-specific thing. That is: other system components can't read those URLs.
The MediaResourceGetter doesn't use the WebView's network stack and therefore doesn't "understand" the file:///android_asset protocol.
In your other question you mentioned you use a local http server - try serving the .mp4 from that.
if have still a problems about play video on android webview in 2018, let's give a chance and try code below.
Java:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() {
document.getElementsByTagName('video')[0].play();
})()");
}
});
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://html5demos.com/video");
}
#Override
protected void onPause() {
super.onPause();
webview.onPause();
}
#Override
protected void onResume() {
webview.onResume();
super.onResume();
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.com">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:hardwareAccelerated="true"
android:allowBackup="false"
android:icon="#mipmap/logo_example"
android:label="#string/app_name"
android:roundIcon="#mipmap/logo_example"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
References:
https://gist.github.com/aprock/5913322

How to fix a webview error in android?

I'm trying to create a simple Android application that is just a webview. I've been following a tutorial (http://www.mkyong.com/android/android-webview-example/) but have adapted it to have just a webview instead of a button that opens a webview.
When I include the code, I get an error on the line saying "webview cannot be resolved or is not a field". Any ideas on how to troubleshoot? Full code is below:
Error where line occurs:
setContentView(R.layout.webview);
MainActivity.java:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Change setContentView(R.layout.webview) to setContentView(R.layout.actvity_main), or rename you xml file to webview.xml
You can do the same using xml or programaticaly as below
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //should be activity_main
webView = (WebView) findViewById(R.id.webView1);//find id of the view defined in activity_main
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}
}
OR
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(MainActivity.this);// webview in mainactivity
setContentView(webView);// set the webview as the layout
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}
}
if you are following the example as you said then in the android manifest file remove android:theme="#android:style/Theme.NoTitleBar" /> and try to run it.

Does anyone know how to get the value of edittext from one activity to a textvew in another using a button?

GET EDITTEXT INPUT TO TEXTVIEW IN ANOTHER CLASS USING A BUTTON
I am fairly new to android and I am trying to use an edittext to get user input on one screen (Activity), actually not just one edittext a few like a couple edit texts and maybe a spinner, kind of like a create a new user screen. But I know how to use a button to getText() and setText() from the edittext to the textview if they are in the same activity but can not find anywhere how to accomplish this. Here is something like what the first class's bare bones would be:
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edit = (EditText) findViewById(R.id.editText1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
Now I know the magic will be in the onClick(View v){} method, but what magic exactly do I use to 1-open a new Activity that houses the textview and 2- open the Activity?
Here is the second Activity for visual reference:
public class GetText extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
TextView view = (TextView) findViewById(R.id.textView1);
}
}
Again please if anyone can even chop up the code I will use just trying to get it to work right now. Hopefully everyone can rally and give their input as to help others out that may be stuck as well. Thanks ahead of time.
Here is what I have and if force closes on me:
Main Activity:
package com.mandam.ok;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edit = (EditText) findViewById(R.id.editText1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText edit = (EditText)
findViewById(R.id.editText1);
Intent intent = new Intent(UserInput.this, GetText.class);
intent.putExtra("com.mandam.ok.GETTEXT",
edit.getText().toString());
startActivity(intent);
}
});
}
}
Second Activity:
package com.mandam.ok;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class GetText extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
TextView view = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
String name = intent.getStringExtra("com.mandam.ok.MAIN");
//edit.setText(view.getText());
}
}
I will even attach my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Second xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mandam.ok"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".OkActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".GetText" >
<intent-filter >
<action android:name="com.mandam.ok.GETTEXT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now I know I am missing something very simple, just don't know what. I appreciate the help so far. :)
Your second activity HAS a textview... saying that it IS a textview is wrong since Activities are not Views.
Here's how you can pass arguments to a new Activity... this code would be in your first Activity's onClick:
EditText edit = (EditText) findViewById(R.id.editText1);
Intent intent = new Intent(UserInput.this, GetText.class);
intent.putExtra("com.package.name.NAME", edit.getText().toString());
startActivity(intent);
where "com.package.name" is your package name. An intent is an abstraction that performs an operation. In this case, the intent tells android to create a new Activity. The putExtra method allows you to put extra information into the intent before telling Android to create a new Activity. When you put an extra variable into an intent, you need to give it a unique string identifier that preferably starts with the package name.
Once the other Activity is created, here's how you can retrieve the string:
Intent intent = getIntent();
String name = intent.getStringExtra("com.package.name.NAME");
// do whatever you want with name

Categories

Resources