I'm following a guide on coding by Easy Tuto, currently on part 7 at the end where the recycler_note_item.xml would show up on the interface. In the video, he fixed the problem by adding the onStart, onStop, onResume commands and adding `noteAdapter.startListening' in between the lines as shown here: image In the video, it worked and showed the item however nothing showed up for me as can be seen here . I tried scouring the video trying to find what I did wrong. I'm pretty new to coding and I was using his video as a base to learn more about it. I added those lines myself but it diddn't work for me it seems. Can someone please help me? It would be greatly appreciated. Here is my code for MainActivity.Java:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageButton;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.Query;
public class MainActivity extends AppCompatActivity {
FloatingActionButton addNoteBtn;
RecyclerView recyclerView;
ImageButton menuBtn;
NoteAdapter noteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNoteBtn = findViewById(R.id.add_note_btn);
recyclerView = findViewById(R.id.recyler_view);
menuBtn = findViewById(R.id.menu_btn);
addNoteBtn.setOnClickListener((v)-> startActivity(new Intent(MainActivity.this,NoteDetailsActivity.class)) );
menuBtn.setOnClickListener((v)->showMenu());
setupRecyclerView();
}
void showMenu(){
//TODO Display menu
}
void setupRecyclerView(){
Query query = Utility.getCollectionReferenceForNotes().orderBy("timestamp",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query,Note.class).build();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteAdapter = new NoteAdapter(options,this);
recyclerView.setAdapter(noteAdapter);
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.stopListening();
}
#Override
protected void onResume() {
super.onResume();
noteAdapter.notifyDataSetChanged();
}
}
I think the other relevant codes is my NoteAdapter which is this:
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import io.grpc.okhttp.internal.Util;
public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteViewHolder>{
Context context;
public NoteAdapter(#NonNull FirestoreRecyclerOptions<Note> options, Context context) {
super(options);
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder holder, int position, #NonNull Note note) {
holder.titleTextView.setText(note.title);
holder.contentTextView.setText(note.content);
holder.timestampTextView.setText(Utility.timestamptoString(note.timeStamp));
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_note_item,parent,true);
return new NoteViewHolder(view);
}
class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView,contentTextView,timestampTextView;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.note_title_text_view);
contentTextView = itemView.findViewById(R.id.note_content_text_view);
timestampTextView = itemView.findViewById(R.id.note_timestamp_text_view);
}
}
}
Please tell me if there are any other relevant codes I can give to help give more context on my problem. Thanks for helping me out if anyone!
Related
I am running React Native 0.56. When I start my app, it first shows a white screen for 1 second then goes to the app. My files are:
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new BlurViewPackage(),
new OrientationPackage(),
new ReactVideoPackage(),
new RNDeviceInfo(),
new LinearGradientPackage()
);
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
and
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "CONtv";
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = new Intent("onConfigurationChanged");
intent.putExtra("newConfig", newConfig);
this.sendBroadcast(intent);
}
}
and index.js
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
How do I make the white screen not appear? This is happening on Android.
As a solution for the white screen add a splash screen.
Check with this https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565
import android.content.Context;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import java.util.Date;
import java.util.Locale;
public class Calendarpage extends AppCompatActivity {
//modify here
ActionBar actionBar = null;
CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat ("MMM- yyyy", Locale.getDefault());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
// modify here
ActionBar myActionBar = getSupportActionBar();
if (myActionBar != null) {
myActionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(null);
}
compactCalendar = (CompactCalendarView) findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
Event ev1 = new Event(Color.RED, 1514160000L, "Chirstmas Day");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
Context context = getApplicationContext();
if (dateClicked.toString().compareTo("Mon Dec 25 00:00:00 AST 2017") == 0) {
Toast.makeText(context, "Christmas Day", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "No Events Planned That Day", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getSupportActionBar.setTitle(String.valueOf(dateFormatMonth.format(firstDayOfNewMonth)));
}
});
}
}
now added the changes you made but the getSupportActionBar. is in red? its just asking me to create local variables when right clicking. very stressed with this as I can't move on until this page works.. as I still need to be able to add events to dates
Try to make this change
In your OnCreate :
ActionBar myActionBar = getSupportActionBar();
if (myActionBar != null) {
myActionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(null);
}
In your setListener
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getSupportActionBar().setTitle(String.valueOf(
dateFormatMonth.format(firstDayOfNewMonth)));
}
Good luck
EDIT try this
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
setNewTitleBar(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
private void setNewTitleBar(String newTitle) {
getSupportActionBar().setTitle(newTitle);
}
}
I have a JavaFX WebView and want to call the method "hello" of the class "JavaBridge" from "test.html" displayed in the webview.
Why doesn't this work? I making sure that the "bridge" object only be added to the window.object when the page has been fully rendered, so that is probably not the problem. I can't see any problem with the HTML either.
Here is the HTML code ("test.html"):
<html>
<head>
</head>
<body>
call java
</body>
</html>
And here is the Java Code:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
java.net.URI uri = java.nio.file.Paths.get("test.html").toAbsolutePath().toUri();
WebView root = new javafx.scene.web.WebView();
root.getEngine().load(uri.toString());
root.getEngine().
getLoadWorker().
stateProperty().
addListener(new ChangeListener < State > () {
#Override public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
System.out.println("READY");
JSObject jsobj = (JSObject) root.getEngine().executeScript("window");
jsobj.setMember("bridge", new JavaBridge());
}
}
});
primaryStage.setScene(new javafx.scene.Scene(root, 800, 600));
primaryStage.show();
}
}
class JavaBridge {
public void hello() {
System.out.println("hello");
}
}
When using this bridge feature on Java 10.0.2, I noticed that it was not working consistently. Javascript upcalls wasn't working all the times.
After researching, I found out this OpenJDK bug related to Java Garbage Collector, which seems to happen on regular JDK as well:
https://bugs.openjdk.java.net/browse/JDK-8170085
Indeed, according to https://docs.oracle.com/javase/9/docs/api/javafx/scene/web/WebEngine.html, it's recommended to store the bridge into a variable to avoid Java GC to collect the object.
After adding a private variable to the class, the JS to Java calls started to work all the time in my Application.
Your inner class should be inside the main class. And it should be public. Like this:
import java.net.URL;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
final URL url = getClass().getResource("test.html");
WebView root = new javafx.scene.web.WebView();
root.getEngine().load(url.toExternalForm());
root.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
#Override
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
System.out.println("READY");
JSObject jsobj = (JSObject) root.getEngine().executeScript("window");
jsobj.setMember("bridge", new JavaBridge());
}
}
});
primaryStage.setScene(new javafx.scene.Scene(root, 800, 600));
primaryStage.show();
}
public class JavaBridge {
public void hello() {
System.out.println("hello");
}
}
}
I had the same problem and the only way to fix it was storing the Bridge on a static variable.
this is an example to use the javafx FileChooser.
public class Controller implements Initializable {
#FXML private WebView webview;
#FXML private JFXButton btn_insertimg;
#FXML private AnchorPane anchorpane;
private WebEngine webEngine;
public static Bridge bridge; //it's important to be static
#Override
public void initialize(URL location, ResourceBundle resources) {
webEngine = webview.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(
(ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
//todo when the document is fully loaded
FileChooser fileChooser=new FileChooser();
bridge=new Bridge(webview,fileChooser);
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("myFileChooser", bridge);
System.out.println("member "+window.getMember("myFileChooser").toString());;
}//end of SUCCEEDED state
});
webEngine.load(getClass().getResource("/patient/texteditor/summernote.html").toExternalForm());
}
public class Bridge{
FileChooser fileChooser;
WebView webView;
Bridge(WebView webView,FileChooser fileChooser){
this.webView=webView;
this.fileChooser=fileChooser;
}
public void display(){
fileChooser.showOpenDialog(webView.getScene().getWindow());
}
}
}
I had Successful login to a website using jsoup and I obtained cookies from Jsoup cookies function in Map but I am struck at something.After successful login I Want to open a webpage of the website in the webview but the webpage redirects to the login page because cookies are not successfully passed to the webview and I don't know why. The page wants cookies of successful login to load that page
Here is the login page url.
http://111.68.99.8/StudentProfile/
and page I want to load after Successful Login
http://111.68.99.8/StudentProfile/PersonalInfo.aspx
Here is the MainActivity.java
package com.example.ebad.bu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends ActionBarActivity {
String url = "http://111.68.99.8/StudentProfile/";
Map<String, String> logingcookies;
HashMap<String,String> hashMap;
ProgressDialog progressDialog,progressDialoge;
Button login, personal;
TextView Enrollement, password, E;
String enrol = "";
String pass = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_button);
personal = (Button) findViewById(R.id.pers);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Enrollement = (TextView) findViewById(R.id.Enrollment);
enrol = Enrollement.getText().toString();
password = (TextView) findViewById(R.id.password);
pass = password.getText().toString();
new Title().execute();
}
});
}
private class Title extends AsyncTask<Void, Void, Void> {
String title;
String father;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Title");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Connection.Response loginForm = Jsoup.connect(url).method(Connection.Method.GET).timeout(1000).execute();
Document doc = loginForm.parse();
String viewstate = doc.select("input[name=__VIEWSTATE]").attr("value");
String stategenerator = doc.select("input[name=__VIEWSTATEGENERATOR]").attr("value");
String Eventvalidation = doc.select("input[name=__EVENTVALIDATION]").attr("value");
doc = Jsoup.connect(url)
.data("__LASTFOCUS", "")
.data("__EVENTTARGET", "")
.data("__EVENTARGUMENT", "")
.data("__VIEWSTATE", viewstate)
.data("__VIEWSTATEGENERATOR", stategenerator)
.data("__EVENTVALIDATION", Eventvalidation)
.data("ctl00$Body$ENROLLMENTTextBox$tb", enrol)
.data("ctl00$Body$ENROLLMENTTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$PasswordTextBox$tb", pass)
.data("ctl00$Body$PasswordTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$LoginButton", "Login")
.cookies(loginForm.cookies())
.post();
logingcookies = loginForm.cookies();
title = doc.select("div[id=ctl00_Accounts]").html();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
/*Intent showadditionmenu = new Intent(MainActivity.this,Per.class);
//showadditionmenu.putStringArrayListExtra("logingcookies", (ArrayList<String>) logingcookies);
showadditionmenu.putExtra("logingcookies", String.valueOf(logingcookies));
MainActivity.this.startActivity(showadditionmenu);*/
/* Intent i = new Intent(MainActivity.this,Per.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
*/
hashMap = new HashMap<String,String>(logingcookies);
Intent i = new Intent(MainActivity.this,wee.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
/* E = (TextView) findViewById(R.id.message);
E.setText(title);
progressDialog.dismiss();*/
}
}
}
I have passed the saved cookie to the activity that load the webpage in webivew.. Here is the other activity;
Wee.java
package com.example.ebad.bu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Ebad on 11/8/2015.
*/
public class wee extends Activity {
String url= "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String ,String> hashMap;
Map<String,String> map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Intent intent = getIntent();
hashMap = (HashMap<String,String>) intent.getSerializableExtra("hashMap");
WebView webView = (WebView) findViewById(R.id.webviewe);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url,hashMap);
}
}
Is there any way that I can view that webpage without logging in again to the webview?
Haven't tested it, but using CookieManager ahould work.
Usage should be something like this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie(); //optional
cookieManager.setAcceptCookie(true);
Then loop over your cookies using the setCookie method.
Note: If useing lollipop and up you should also use setAcceptThirdPartyCookies.
Good luck.
I am calling javascript function from an activity but I am getting Uncaught ReferenceError: myFunction is not defined at null:1 error. Here is my files
MainActivity.java
package com.example.androidexample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)this.findViewById(R.id.webView1);
WebSettings webSettings = webview.getSettings();
// Enable Javascript for interaction
webSettings.setJavaScriptEnabled(true);
// Make the zoom controls visible
webSettings.setBuiltInZoomControls(true);
// Allow for touching selecting/deselecting data series
webview.requestFocusFromTouch();
// Set the client
webview.setWebViewClient(new WebViewClient());
webview.setWebChromeClient(new WebChromeClient());
//webview.loadUrl("file:///android_asset/test.html");
/*String str = "<books>" +
"<book title=\"A Tale of Two Cities\"/>" +
"<book title=\"1984\"/>" +
"</books>";*/
webview.loadUrl("file:///android_asset/test.html");
webview.loadUrl("javascript:myFunction()");
//webview.loadUrl("javascript:myFunction("+str+")");
}
#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;
}
}
test.html
<html>
<body>
<script type="text/javascript" src="marknote.js"></script>
<script type="text/javascript">
function myFunction()
{
var str = '<books><book></book></books>';
var parser = new marknote.Parser();
var doc = parser.parse(str);
var bookEls = doc.getRootElement().getChildElements();
for (var i=0; i<bookEls.length; i++) {
var bookEl = bookEls[i];
alert("Element name is " + bookEl.getName());
}
}
</script>
</body>
</html>
I have seen this error occurred when I am using webview.loadUrl("javascript:myFunction()");. I want to pass a xml string from java and parse it into javascript. Please help me to find a solution.
You should execute the javascript when the page is loaded
webview.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
webview.loadUrl("javascript:myFunction()");
}
});
The code will be executed and will find your javascript function. The way you are doing now does not wait.
This one worked just need to change parameter set up sequence
package com.example.androidexample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView)this.findViewById(R.id.webView1);
WebSettings webSettings = webview.getSettings();
// Enable Javascript for interaction
webSettings.setJavaScriptEnabled(true);
// Make the zoom controls visible
webSettings.setBuiltInZoomControls(true);
// Allow for touching selecting/deselecting data series
webview.requestFocusFromTouch();
// Set the client
// webview.setWebViewClient(new WebViewClient());
// webview.setWebChromeClient(new WebChromeClient());
final String str = "<books>" +
"<book title=\"A Tale of Two Cities\"/>" +
"<book title=\"1984\"/>" +
"</books>";
// webview.loadUrl("file:///android_asset/test.html");
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:myFunction('"+str+"')");
}
}
);
webview.loadUrl("file:///android_asset/test.html");
}
#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;
}
}