How can i only show a webview Fragment once loading has complete - java

Is there anyway of showing only my webview once loading has complete? at the moment i have a little webview Fragment on my homescreen but it takes a while to load.I want to show only once loading completes because at the moment its a white screen until loading completes.This does not look the greatest. I tried to add a progress bar but for some reason that does not work in my fragment either.
Ive tried to add the code posted as an answer but it makes no difference. i think its because it a fragment that im having the issues as the progress par works in my main activity webviews.
public class WebViewFragment extends Fragment {
WebView wv;
private String NEWS = "mywebsite goes here";
#Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getContext(), "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getContext(), "portrait", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProgressBar Pbar;
View view = inflater.inflate(R.layout.webviewfrag, null, false);
if (savedInstanceState == null) {
((WebView )view.findViewById(R.id.NewsFeedWbview)).restoreState(savedInstanceState);
wv = (WebView) view.findViewById(R.id.NewsFeedWbview);
wv.setScrollbarFadingEnabled(false);
Pbar = (ProgressBar) view.findViewById(R.id.pBwvf);
final TextView tv = (TextView) view.findViewById(R.id.tV69);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
Pbar.setVisibility(ProgressBar.VISIBLE);
tv.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if (progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
tv.setVisibility(View.GONE);
}
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if (Build.VERSION.SDK_INT >= 19) {
// chromium, enable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
wv.canGoBackOrForward(5);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.setPadding(0, 0, 0, 0);
wv.loadUrl(NEWS);
}
return view;
}
}

Here my code:
Activity:
public class WebViewActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
WebViewActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
WebViewActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.web_view, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
Layout:
<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"
tools:context=".WebViewActivity" >
<LinearLayout
android:id="#+id/urlContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="Enter URL to open" />
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Open" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/urlContainer" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/progressBar" />
</RelativeLayout>

Use below code
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});

Related

Text doen't appear after speech in adroid studio

Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?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=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.

Using switch button to set text visibility in another activity

Am a beginner in android development and am desperately looking for a solution for a challenge i encountered while working on a quiz app.
I have a switch in my SettingsActivity which toggle set a particular text in another activity visible and invisible.
However i have been having problems finding the right logic to reference that text from my SettingsActivity in other to toggle its visibility.
QuizActivity.java
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
}
}
SettingsActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/explanationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:fontFamily="cursive"
android:layout_marginBottom="25dp"
android:textColor="#color/settings_text"
android:text="#string/explanation"/>
<Switch
android:id="#+id/explanationSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:checked="true"
android:layout_gravity="center"/>
</LinearLayout>
SettingsActivity.java
private Switch mExplanationSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_settings);
mExplanationSwitch = (Switch) findViewById(R.id.explanationSwitch);
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
}
MainActivity.java
//This is where i start Quiz Activity
private Button startQuiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startQuiz = (Button) findViewById(R.id.start);
startQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startQuiz = new Intent(this, QuizActivity.class);
startActivity(beginnerIntent);
});
}
Save Setting in Shared Preferences
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
Editor editor = preferences.edit();
if(isChecked){
editor.putBoolean("ntoificatoin",isChecked);
}
else
{
editor.putBoolean("ntoificatoin",isChecked);
}
editor.apply();
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
In Your QuizActivity
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
boolean b=preferences.getBoolean("ntoificatoin",false);//it returns stored boolean value else returns false
if(b){
//return true from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
else
{
//return false from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
}
}
if you are looking for how to pass extra info to the QuizActivity here how to use the extra in the intent :
Intent intent = new Intent();
intent.putExtra("stateOfTheSwitch","clicked");
startActivity(intent);
and in the QuizActivity you can retrieve the extra like this :
if(getIntent().getExtras.getString("stateOfTheSwitch").equals("clicked")
//do something
else
//do something else

Android studio E/RecyclerView: No adapter attached; skipping layout

I have tried every solution I found on-line and anywhere. But I still can't solve this problem. It keeps giving me this error "E/RecyclerView: No adapter attached; skipping layout". I tried to use breakpoint to test each code. From the result, I get that data is successfully retrieved from firebase and save in ArrayList and the size of mItems is correct. But this is the result I get.Please somebody help me.
The Result I get
My firebase structure
ShowBookedSlotActivity.java
public class ShowBookedSlotActivity extends AppCompatActivity {
private static final String TAG ="Show Booked Activity" ;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_booked_slot);
setTitle("Booked Gym Slot");
Log.d(TAG, "on create");
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setHomeButtonEnabled(true);
auth = FirebaseAuth.getInstance();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new ListBookedSlotFragment();
Bundle bundle = new Bundle();
bundle.putString("UID", auth.getCurrentUser().getUid());
fragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ShowBookedSlotActivity.this, UserHomeActivity.class));
finish();
}
}
ListBookedSlotFragment.java
public class ListBookedSlotFragment extends Fragment {
private final String TAG = "ListBookedSlotFragment";
private ArrayList<BookedSlot> mItems;
private ArrayList<String> mItemsKey;
private RecyclerView mItemRecyclerView;
private ItemAdapter mAdapter;
private DatabaseReference mItemRef;
private DatabaseReference mDatabase;
private String UID;
private Query mBookedSlotQuery;
private DatabaseReference mBookedSlotRef;
private ValueEventListener mBookedSlotQueryVEL;
#SuppressLint("LongLogTag")
#Override
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
Log.d(TAG, "UID: " + UID);
mDatabase = FirebaseDatabase.getInstance().getReference();
mItems = new ArrayList<>();
if (UID != null) {
mItemsKey = new ArrayList<>();
mBookedSlotQuery = mDatabase.child("booked_slot").orderByChild("UserID").equalTo(UID);
Log.d(TAG, "mItemRef:" + mBookedSlotQuery);
mBookedSlotQueryVEL = mBookedSlotQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
BookedSlot bookedSlot = d.getValue(BookedSlot.class);
Log.d(TAG, "bookedSlot:" + bookedSlot.getUserID());
mItems.add(bookedSlot);
mItemsKey.add(d.getKey());
}
updateUI();
/* TextView infoTextTextview = (TextView) getActivity().findViewById(R.id.info_text); //show_booked_slot.xml
if (mItems.isEmpty()) {
infoTextTextview.setText(R.string.Empty);
} else {
// infoTextTextview.setVisibility(View.GONE);
infoTextTextview.setText("Size: ".concat(Integer.toString(mItems.size())));
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "show booked slot databaseError: " + databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public void onDetach() {
super.onDetach();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_booked_slot, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view); //in fragment_list_item_booked_slot.xml
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI() {
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder {
BookedSlot mItems;
TextView mNameTextView;
TextView mDateTextView;
TextView mTimeTextView;
ItemHolder(final View itemView) {
super(itemView);
//refer list_booked_gym_slot.xml
mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
mDateTextView = (TextView) itemView.findViewById(R.id.textview_date);
mTimeTextView = (TextView) itemView.findViewById(R.id.textview_time);
if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Slot?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteSlot(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
void bindData(BookedSlot s){
mItems = s;
mNameTextView.setText(s.getUsername());
mDateTextView.setText(s.getBookedDate());
mTimeTextView.setText(s.getBookedTime());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<BookedSlot> mItems;
ItemAdapter(ArrayList<BookedSlot> Items){
this.mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_booked_gym_slot,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
BookedSlot s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
private void deleteSlot(final BookedSlot itemClicked) {
mDatabase.child("booked_slot").child(UID).child(mItemsKey.get(mItems.indexOf(itemClicked))).removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
Toast.makeText(getActivity(), itemClicked.getBookedDate() + " " + itemClicked.getBookedTime() +" Slot Deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ShowBookedSlotActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.AppBarLayout>
<TextView
android:id="#+id/info_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity"
tools:showIn="#layout/activity_show_booked_slot">
</RelativeLayout>
</LinearLayout>
fragment_list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
list_booked_slot.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="wrap_content"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textview_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
<TextView
android:id="#+id/textview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
The Fragment Life Cycle is as follows :
1. constructor
2. onAttach
3. onCreate
4. onCreateView
So you cant call updateUI() method to set data to RecyclerView before setting LayoutManager.
Only after setting LayoutManager should you give data to RecyclerView

What is wrong in this jsoup code? (Android)

This is the code:
public class MainActivity extends Activity
{
private TextView textView2;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView2=(TextView)findViewById(R.id.textView1);
button2=(Button)findViewById(R.id.button1);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url="http://stackoverflow.com/";
try{
Document doc=Jsoup.connect(url).get();
Elements elem=doc.select("meta[name=twitter:domain]");
String title1=elem.attr("content");
textView2.setText(title1);
}
catch(Exception e){
}
}
});
}}
This is the xml code:
<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="com.example.jsouptest.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="111dp"
android:text="TextView"
android:textSize="100dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="34dp"
android:text="Display" />
It isn't displaying the content in the textview on clicking the
button.
I have added permission for internet in the manifest file.
You can not call Network on main thread. You must call async task to make network calls. When you click on button execute a async task and then do your stuff there.
Below Code will Help:
public class MainActivity extends Activity {
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetStringTask().execute();
}
});
}
private class GetStringTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = "http://stackoverflow.com/";
Document doc = null;
try {
doc = Jsoup.connect(url).get();
Elements elem = doc.getElementsByTag("title");
String title1 = elem.html();
return title1;
} catch (IOException e) {
e.printStackTrace();
return "Exception";
}
}
#Override
protected void onPostExecute(String title) {
textView1.setText(title);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
the code above sets the TextView label to "Stack Overflow".

Android, WebView not playing YouTube videos [duplicate]

YouTube Video not playing in WebView.
It my first app ,I Want to do a webview.
When I open YouTube the video not playing, is loading but not playing.
Is loading all the time.
Thank you so much for helping.
Java:
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
} }
Xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Seems like duplicate of play youtube video in WebView and YouTube Video not playing in WebView - Android
To make it work via WebView, I used the following two steps (version 4.2.2/Nexus 4):
On shouldOverrideUrlLoading I added webview.setWebChromeClient(new WebChromeClient());
In AndroidManifest.xml for activity tag I added android:hardwareAccelerated="true"
AndroidManifest.xml should also contain Internet permission.
While exact steps with playing video via WebView can be specific to device and Android version, there are also other alternatives to WebView, like VideoView or using Youtube Android Player API.
EDIT1
As for pause and full screen, this is actually a second link I mentioned in the beginning. To make it easier, I am posting code that worked on my Nexus.
In activity_main.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=".MainActivity" >
<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" />
</LinearLayout>
</RelativeLayout>
In MainActivity class:
public class MainActivity extends Activity {
private WebView mWebView;
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
#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;
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.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;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
EDIT2 - adding back button support
public class MainActivity extends Activity {
private WebView mWebView;
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#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();
}
#Override
public void onHideCustomView()
{
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
#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;
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
#Override
protected void onStop() {
super.onStop();
if (mCustomView != null)
{
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (mCustomView != null)
{
mWebChromeClient.onHideCustomView();
} else
{
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Adding webchrome client solves the issue,
web = (WebView) vi.findViewById(R.id.offer_webView1);
web.loadUrl(getResources().getString(R.string.videolink));
web.getSettings().setJavaScriptEnabled(true);
// web.getSettings().setDomStorageEnabled(true);
web.getSettings().setAllowContentAccess(true);
WebSettings webSettings = web.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
web.canGoBack();
web.setWebChromeClient(new WebChromeClient() {});

Categories