Android Studio Webview in a Fragment shows nothing and empty - java

I wish to implement a webview in the fragment_home_screen without covering the BottomNavigationView. However, even I followed everything on an online tutorial by setting up the webview in the Fragment_Home.java onCreateView() method. Nothing has showed up. I tried adding a button in the fragment_home_screen.xml to ensure the fragment DID showed up. It ended up showing the BUTTON ONLY.
I have been trying to fix this issues for hours and still couldn't figuring what's wrong with my code. Got any idea?
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.exercise.myApplication">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".Activity_Map"
android:exported="false"
android:label="#string/title_activity_map" />
<activity
android:name=".Activity_Login"
android:exported="false" />
<activity
android:name=".Activity_SignUp"
android:exported="false" />
<activity
android:name=".Activity_Home"
android:exported="false"
android:label="Main" />
<activity
android:name=".SplashScreen"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Activity_Home.java
package android.exercise.myApplication;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class Activity_Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
BottomNavigationView bottomNav = findViewById(R.id.bottomNavigationView);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectFragment = null;
switch(item.getItemId()){
case R.id.homeScreen:
selectFragment = new HomeFragment();
break;
case R.id.userScreen:
selectFragment = new Fragment_User();
break;
case R.id.driverScreen:
selectFragment = new Fragment_Driver();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectFragment).commit();
return true;
}
};
}
Fragment_Home.java
package android.exercise.myApplication;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Fragment_Home#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment_Home extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Fragment_Home() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Fragment_Home.
*/
// TODO: Rename and change types and number of parameters
public static Fragment_Home newInstance(String param1, String param2) {
Fragment_Home fragment = new Fragment_Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String url = "https://pastebin.com/";
View v = inflater.inflate(R.layout.fragment_home_screen, container, false);
WebView myWebview = (WebView) v.findViewById(R.id.webview);
myWebview.getSettings().setJavaScriptEnabled(true);
myWebview.getSettings().setDomStorageEnabled(true);
myWebview.setWebViewClient(new WebViewClient());
myWebview.loadUrl("https://en.wikipedia.org/");
myWebview.setWebViewClient(
new SSLWebViewClient()
);
myWebview.clearView();
myWebview.measure(100, 100);
myWebview.getSettings().setUseWideViewPort(true);
myWebview.getSettings().setLoadWithOverviewMode(true);
return v;
}
}
activity_main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_Home" >
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu"/>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/fragment_container"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_home_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment_Home">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</WebView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintStart_toStartOf="#+id/webview"
app:layout_constraintTop_toTopOf="#+id/webview" />
</RelativeLayout>
As for the logcat, filtered with warnings there's only one line of error:
022-01-19 21:45:53.557 7053-7053/android.exercise.myApplication E/chromium: [ERROR:gl_surface_egl.cc(549)] eglChooseConfig failed with error EGL_SUCCESS

I tried your code and it works fine you just need to comment out some code in Fragment_Home.java as below:
#Override
public View onCreateView(....){
.....
..........
//remove or comment this part.
// myWebView.setWebViewClient(new SSLWebViewClient());
.....
}

Related

My webview doesn't start after creating progress bar

I created my new webapp. It worked well. But I wanted to add a progress bar. The progress bar works, but my webview doesn't show anynore. I don't understand why. Can someone may help, please?
I tried all the codes I found online. They are ok for the others, but not for me.
Here my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:fullBackupOnly="true"
android:icon="#drawable/donorionepng"
android:label="PCDO GENOVA"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.PCDOPCDOGENOVA"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:exported="true"/>
<activity
android:name=".SplashActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here my MainActivity.java
package it.donorionegenova.pcdopcdogenova;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ClientCertRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.res.ResourcesCompat;
import com.onesignal.OneSignal;
import android.annotation.SuppressLint;
public class MainActivity extends AppCompatActivity {
private static final String ONESIGNAL_APP_ID = "........ de2";
private SwipeRefreshLayout swipeRefreshLayout;
private WebView webView;
ProgressBar progressBar;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.prBar);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.donorione-genova.it/home-app");
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress == 100) {
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
webView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
});
TextView textView = findViewById(R.id.textview);
textView.postDelayed(() -> textView.setText("loading..."), 500); // delay of 2 seconds before setting a text to textView
textView.postDelayed(() -> textView.setVisibility(View.GONE), 2000);
// Enable verbose OneSignal logging to debug issues if needed.
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDisplayZoomControls(false);
settings.supportZoom();
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
// settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setDomStorageEnabled(true);
settings.setLoadsImagesAutomatically(true);
webView.clearHistory();
webView.clearCache(true);
registerForContextMenu(webView);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.donorione-genova.it/home-app");
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView View, WebResourceRequest request) {
final Uri uri = request.getUrl();
if (uri.toString().startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else {
//Handle Web Urls
webView.loadUrl(uri.toString());
}
return true;
}
});
//per fare il refresh
swipeRefreshLayout = findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(() -> {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(() -> {
swipeRefreshLayout.setRefreshing(false);
webView.reload();
}, 2000);
});
swipeRefreshLayout.setColorSchemeColors(
ResourcesCompat.getColor(
getResources(), R.color.holo_blue_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_orange_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_green_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_red_dark, null));
}
public void gohome(View v)
{
webView.loadUrl("https://donorione-genova.it/home-app");
}
public void clickexit(View v)
{
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else
super.onBackPressed();
}
}
And here my ActivityMain:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/prBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="visible" >
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<Button
android:id="#+id/button"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:background="#0063B1"
android:onClick="clickexit"
android:text="#string/Chiudi"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="#+id/button2">
</Button>
<Button
android:id="#+id/button2"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:background="#0063B1"
android:onClick="gohome"
android:text="#string/Home"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toStartOf="parent">
</Button>
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#0000ff"
android:textSize="40sp"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
I didn't use SwipeRefreshLayout, but the documentation says you need to include another layout inside it. As you added a second view inside, you are now using it as a default ViewGroup, which is probably not working as expected. Put a LinearLayout or whatever inside the SwipeRefreshLayout and your components inside your LinearLayout.

WebView in Fragment doesn't load the URL

I've read everything about this issue on the site but no solution worked for me. I am not even a beginner and try to create a 4-tab activity. First tab has a webView but it does not load the url. What is missing?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<!-- [START firebase_service] -->
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<activity
android:name=".AnaSayfa"
android:label="#string/title_activity_ana_sayfa"
android:theme="#style/Theme.AppCompat.NoActionBar"></activity>
</application>
fragment_frag_home.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.fragHome">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/pembis"
android:orientation="vertical">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:id="#+id/webView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
fragHome.java
package layout;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.sahin.spm.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link fragHome.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link fragHome#newInstance} factory method to
* create an instance of this fragment.
*/
public class fragHome extends Fragment {
private WebView myWebView;
private String Url = "http://google.com.tr";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public fragHome() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment fragHome.
*/
// TODO: Rename and change types and number of parameters
public static fragHome newInstance(String param1, String param2) {
fragHome fragment = new fragHome();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_frag_home, container, false);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com.tr");
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Thanks for your help.
Edit:
In my opinion the problem is in this lines:
View rootView = inflater.inflate(R.layout.fragment_anasayfa, container, false);
WebView myWebView = (WebView) rootView.findViewById(R.id.hWebView);
I think there is an issue with relating the defined object with the existing webview.
try overriding setUserVisibleHint like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
webView.loadUrl("http://www.google.com.tr");
}

Set image in app as wallpaper

I am not able to set an image from the app as wallpaper. On running it shows unfortunately testandroid stopped working.
I have set the permission in the manifest file and set minimum SDK to 5.
Androidmanifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="19" />
<uses-permission android:maxSdkVersion="19" android:name="android.permission.SET_WALLPAPER"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testandroid.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.testandroid.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<ImageView
android:id="#+id/imageview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/bing"
android:adjustViewBounds="true"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="27dp"
android:text="#string/btn"
android:onClick="goForNext"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn1"
android:onClick="setWallpaper"/>
</LinearLayout>
MainActivity.java
package com.example.testandroid;
import android.app.WallpaperManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imgview = (ImageView) findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void goForNext(View view){
Button but = (Button) findViewById(R.id.button1);
Intent i = new Intent(MainActivity.this, Activity.class);
startActivity(i);
}
public void setWallpaper(View view)
{
Button bt = (Button) findViewById(R.id.button2);
WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
try
{
wm.setResource(R.drawable.bing);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is the activity_main.xml file. please help me wiht it.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.testandroid.MainActivity"
tools:ignore="MergeRootFrame" />
Try removing the following from onCreate()
ImageView imgview = (ImageView) findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
And add this to your onCreateView() method in your Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ImageView imgview = (ImageView) rootView.findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
return rootView;

Android Tutorial issue

I am new to android, Eclipse and Java.
I started these tutorials from here: http://developer.android.com/training/basics/firstapp/index.html
I did all the steps from the link above...my problem is when I run this app and press the 'Send' button...nothing happens, there are no errors in my Console or LogCat.
Here is my code I ended up with:
activity_main.xml:
<LinearLayout 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:orientation="horizontal" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyFirstApp</string>
<string name="action_settings">Settings</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_display_message">My Message</string>
<string name="hello_world">Hello world!</string>
</resources>
MainActivity.java:
package com.example.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
}
DisplayMessageActivity.java:
package com.example.myfirstapp;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and activity_display_message.xml:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Has anyone else ran into the same issue as me? Any help would be appreciated.
MyFirstApp Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
</manifest>
You need to call startActivity
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent); // missing
}
Also make sure you have made an entry for the activities in manifest file.

Trying to get a brand new android project to work with SlidingMenu (jfeinstein10) and ActionbarSherlock

I created a brand new android project and added SherlockActionBar and SlidingMenu to it.
I thought that i had copied everything from the example file but it still doesn't work. It shows my main fragment but the menu doesn't show at all when i click on the icon.
What am i missing??
Here are the classes and XML. Project is empty except for these classes/xml files.
Class 1 (Main activity):
import android.os.Bundle;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class Main extends SlidingFragmentActivity {
protected MenuFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFrag = new MenuFragment();
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new SectionOneFragment())
.commit();
// set the Behind View
setBehindContentView(R.layout.activity_menu);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, mFrag)
.commit();
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setMode(SlidingMenu.LEFT);
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setSlidingActionBarEnabled(false);
}
}
Class 2 (Menu fragment):
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MenuFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_menu, null);
}
}
Class 3 (SectionOne fragment)
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SectionOneFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_main, null);
}
}
Xml 1 (res->layout->activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Xml 2 (res->layout->activity_menu.xml):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Xml 3 (res->layout->fragment_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<TextView 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:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
android:textColor="#ff00ff"
tools:context=".Main" />
Xml 4 (res->layout->fragment_menu.xml):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TEST"
android:textColor="#00ff00" />
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock" >
<activity
android:name=".Main"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Shadow.xml, dimens.xml are copied from the sample project.
Asked jfeinstein10 and i see that i forgot to add the onOptionsItemSelected method.
Correct code to open (to fix my class above):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
Should be in the MainActivity class after onCreate.

Categories