unable to update back4app database in android studio - parse-platform

So I've linked my android app to back4app parse server. According to their documentation when I run the following code a class is supposed to be created in the database. However Android studio shows the following errors:
cannot resolve symbol SaveCallback
Method does not override method from its superclass
package com.example.android.beastt;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.parse.ParseObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseUser;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParseObject soccerPlayers = new ParseObject("SoccerPlayers");
// Store an object
soccerPlayers.put("playerName", "A. Wed");
soccerPlayers.put("yearOfBirth", 1997);
soccerPlayers.put("emailContact", "a.wed#email.io");
soccerPlayers.addAllUnique("attributes", Arrays.asList("fast", "good conditioning"));
// Saving object
soccerPlayers.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success
} else {
// Error
}
}
});
}
}

Related

Google sign in integration

i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help
this is my main Activity
package com.example.todo;
import static android.content.ContentValues.TAG;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.identity.BeginSignInRequest;
import com.google.android.gms.auth.api.identity.SignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
private TextView todo;
private ImageView googleBtn;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todo = findViewById(R.id.todo);
googleBtn = findViewById(R.id.googleBtn);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null){
navitgateToSecondActivity();
}
googleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = gsc.getSignInIntent();
startActivityForResult(signInIntent,1000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
task.getResult(ApiException.class);
navitgateToSecondActivity();
} catch (ApiException e) {
Toast.makeText(this, "Google Auth failed", Toast.LENGTH_SHORT).show();
}
}
}
}
void navitgateToSecondActivity(){
finish();
Intent intent = new Intent(this,secondActivity.class);
startActivity(intent);
}
}
this is the second activity
package com.example.todo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
public class secondActivity extends AppCompatActivity {
private Button signOut;
private DrawerLayout drawer;
private NavigationView navigationView;
private MaterialToolbar toolbar;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
private TextView profileName;
ImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct!=null){
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
Uri personPhoto = acct.getPhotoUrl();
profileName.setText(personName);
profilePic.setImageIcon(Icon.createWithContentUri(personPhoto));
}
initViews();
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,R.string.drawer_open,R.string.drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
}
void initViews(){
drawer = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
toolbar = findViewById(R.id.toolbar);
signOut = findViewById(R.id.signOut);
}
void logout(){
gsc.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
finish();
startActivity(new Intent(secondActivity.this,
MainActivity.class));
}
});
}
}
i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help, i tried all that expecting to get a sign in but it keeps telling me failed

com.sun.proxy.$Proxy16 Error while execution

I'm trying my first exercise on Cucumber with Java. Getting error NullPointer and com.sun.proxy.$Proxy16 while executing.
Tried upgrading, downgrading various dependencies.
package com.cucu.runner;
import org.junit.runner.RunWith;
//import cucumber.api.CucumberOptions;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions
(
features= {".//src/main/java/com/cucu/feature/"},
glue="com.cucu.stepdef",
dryRun=false,
monochrome=true,
plugin= {"pretty","html:test-output"}
)
public class TestRunner_Cucumber {
}
Feature: LoginPage
Scenario: Successful Login with Valid Credentials
Given User launch the URL
When Page title should be "Welcome, please sign in!"
When User enters valid Username "admin#yourstore.com" and valid Password "admin"
When User clicks on LogIn button
Then User lands on the homepage and verifies the text
package com.cucu.stepdef;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import com.cucu.configprop.TestBase;
import com.cucu.pages.LoginPage;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions extends TestBase{
LoginPage loginPage = new LoginPage(driver);
#Before
public static void Start()
{
initialization();
}
#Given("User launch the URL")
public void user_launch_the_URL() {
launchURL();
}
#When("Page title should be \"([^\"]*)\"")
public void Page_title_should_be(String Title) {
String ActTitle = loginPage.titleValidation();
System.out.println(ActTitle);
Assert.assertSame(Title, ActTitle);
}
#When("User enters valid Username {string} and valid Password {string}")
public void user_enters_valid_Username_and_valid_Password(String username, String password) {
loginPage.enterEmail(username);
loginPage.enterPassword(password);
}
#When("User clicks on LogIn button")
public void user_clicks_on_LogIn_button() {
loginPage.clickLogIn();
}
#Then("User lands on the homepage and verifies the text")
public void user_lands_on_the_homepage_and_verifies_the_text() {
String DisplayText = loginPage.HeaderValidation();
Assert.assertSame("Incorrect Text", "Dashboard", DisplayText);
}
}
package com.cucu.configprop;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.cucu.pages.CreateOrdersPage;
import com.cucu.pages.CreateUsersPage;
import com.cucu.pages.HomePage;
import com.cucu.pages.LoginPage;
public class TestBase {
public static WebDriver driver;
public static LoginPage loginPage;
public static HomePage homePage;
public static CreateUsersPage createUsersPage;
public static CreateOrdersPage createOrdersPage;
public static WebDriverWait waitTime;
public static Properties prop;
public TestBase()
{
try {
prop = new Properties();
FileInputStream inp = new FileInputStream("F:\\Azar\\Cucumber_Practice\\"
+ "src\\main\\java\\com\\cucu\\configprop\\config.properties");
prop.load(inp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization(){
String browserName = prop.getProperty("browser");
if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver","F:\\Installation\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}
}
public static void launchURL()
{
driver.get(prop.getProperty("url"));
}
public static void waitDriver()
{
waitTime = new WebDriverWait(driver, 2000);
}
}
When Page title should be "Welcome, please sign in!" # StepDefinitions.Page_title_should_be(String)
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy16.getText(Unknown Source)
at com.cucu.pages.LoginPage.titleValidation(LoginPage.java:39)
at com.cucu.stepdef.StepDefinitions.Page_title_should_be(StepDefinitions.java:31)

How can I register JSR-356 Websocket in PAX-Web? (In bundle, not WAR)

I have a problem with the PAX-Web. I've tried to register a Websocket service as declrarative, but it is unaccessible from web. I've tried the given websocket-jsr356-6.0.3.war and it works fine. As I see the WAR file handles differently the org.osgi.service.http.HttpContext. I've tried the following scenarios:
Scenario 1 - OSGi R6 Whiteboard HTTP method
Creating a ServletContextHelper:
package hu.blackbelt.judo.common.rest.regular;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.http.context.ServletContextHelper;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
#Component(immediate = true)
#Service(ServletContextHelper.class)
#Properties(value = {
#Property(name = HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, value = "chat"),
#Property(name = HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, value = "/test")
})
public class ChatServletContext extends ServletContextHelper {
}
And adding the Websocket Endpoint:
package hu.blackbelt.judo.common.rest.regular;
import lombok.extern.slf4j.Slf4j;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import javax.websocket.EncodeException;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
#Component(immediate = true)
#Service(Object.class)
#Properties(value = {
#Property(name = HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
value = "=(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=chat)")
})
#Slf4j
public class ChatEndpoint {
public static final String ROOM = "room";
#OnOpen
public void onOpen(final Session session, #PathParam(ROOM) final String room) {
LOGGER.info("session openend and bound to room: " + room);
session.getUserProperties().put(ROOM, room);
}
#OnMessage
public void onMessage(final Session session, final ChatMessage chatMessage) {
String room = (String) session.getUserProperties().get(ROOM);
try {
for (Session s : session.getOpenSessions()) {
if (s.isOpen()
&& room.equals(s.getUserProperties().get(ROOM))) {
s.getBasicRemote().sendObject(chatMessage);
}
}
} catch (IOException | EncodeException e) {
LOGGER.warn("onMessage failed", e);
}
}
}
The logs show me that the Endpoint is catched. I've debugged and Pax-Web is registering it.
The log shows the following line:
2017-05-04 02:36:02,698 | INFO | Thread-70 | WebSocketTracker | 330 - org.ops4j.pax.web.pax-web-extender-whiteboard - 6.0.3 | found websocket endpoint!!
But the websocket is unaccessible with the following URL: ws://localost:8181/test/chat/testroom
Scenario 2 - Pax-Web properties on registered HttpContext (with JAX-RS it works)
Creating HttpContext instance: (Utilizing the OSGi given Helper abstract class):
package hu.blackbelt.judo.common.rest.regular;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.context.ServletContextHelper;
#Component(immediate = true)
#Service(HttpContext.class)
#Properties(value = {
#Property(name = "httpContext.id", value = "chat"),
#Property(name = "httpContext.path", value = "test")
})
public class ChatHttpContext extends ServletContextHelper implements HttpContext {
}
And the Websocket Endpoint:
package hu.blackbelt.judo.common.rest.regular;
import lombok.extern.slf4j.Slf4j;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
import javax.websocket.EncodeException;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
#SuppressWarnings({"checkstyle:missingctor", "checkstyle:illegaltoken"})
#Component(immediate = true)
#Service(Object.class)
#Properties(value = {
#Property(name = "httpContext.id", value = "chat")
})
#ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)
#Slf4j
public class ChatEndpoint {
public static final String ROOM = "room";
#OnOpen
public void onOpen(final Session session, #PathParam(ROOM) final String room) {
LOGGER.info("session openend and bound to room: " + room);
session.getUserProperties().put(ROOM, room);
}
#OnMessage
public void onMessage(final Session session, final ChatMessage chatMessage) {
String room = (String) session.getUserProperties().get(ROOM);
try {
for (Session s : session.getOpenSessions()) {
if (s.isOpen()
&& room.equals(s.getUserProperties().get(ROOM))) {
s.getBasicRemote().sendObject(chatMessage);
}
}
} catch (IOException | EncodeException e) {
LOGGER.warn("onMessage failed", e);
}
}
}
But the websocket is unaccessible with the following URL: ws://localost:8181/test/chat/testroom
How can I achive that webcsocket be available? I do not want to repackage my bundle as WAB. Is there any way?

Fatal error:An error occured while executing doInBackground()

I am new to android and i am getting this error.Maths1 code:
package com.materialdesign.geniusmathsandphysics;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Maths1 extends Activity{
MainActivity async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maths1);
async=new MainActivity();
Button m15,d15;
m15 = (Button) findViewById(R.id.but_m1may15);
d15 = (Button) findViewById(R.id.but_m1dec15);
m15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_May_15.pdf");
if (pdf.exists()) {
//file= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/Area.pdf");
Intent i=new Intent(Maths1.this,PdfViewer.class);
i.putExtra("FileName",pdf);
startActivity(i);
} else {
if (isNetworkConnected() == true) {
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
async.new Connect().execute("166.62.10.29", "M1_May_15.pdf");
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
d15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_Dec_15.pdf");
if (pdf.exists()) {
ViewPDF();
} else {
if (isNetworkConnected() == true) {
async.new Connect().execute("166.62.10.29", "M1_Dec_15.pdf");
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
ViewPDF();
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
public void ViewPDF()
{
Intent i=new Intent(Maths1.this,PdfViewer.class);
SavePreferences("name", "M1_Dec_15.pdf");
startActivity(i);
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
pdf viewer code:
package com.materialdesign.geniusmathsandphysics;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
public class PdfViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdfviewer);
com.joanzapata.pdfview.PDFView Pdf = (com.joanzapata.pdfview.PDFView) findViewById(R.id.pdfview1);
//String filepath=getIntent().getExtras().getString("name");
String file=showPreferences("name");
File fd = new File(file);
//Log.i("hhhhdsdada",filepath);
Pdf.fromFile(fd).defaultPage(1).swipeVertical(true).load();
}
private String showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedPref = sharedPreferences.getString(key, "");
File files= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/"+savedPref);
String file=files.toString();
return file;
}
}
this is my logcat:
FATAL EXCEPTION: AsyncTask #3 Process: com.materialdesign.geniusmathsandphysics, PID: 18871
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: PDF file is corrupted
at org.vudroid.pdfdroid.codec.PdfDocument.open(Native Method)
at org.vudroid.pdfdroid.codec.PdfDocument.openDocument(PdfDocument.java:28)
at org.vudroid.pdfdroid.codec.PdfContext.openDocument(PdfContext.java:18)
at org.vudroid.core.DecodeServiceBase.open(DecodeServiceBase.java:59)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:52)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
i am using joanzapata library to view pdf files.for that i am trenter code hereying to pass that file name from maths 1 class on button click listner. The library takes file as input so i had to convert string to file previously using intent i was getting null pointer exception but now with shared preferences i am getting this error. Please help me to solve it. Thanks in advance.

why #autowired doos not instanciate my field?

I'm using Spring boot annotation style, and I don't understand after several searches, why the annotated field returns null.
Please below my java code:
package app.ui;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
#Service
public class MyFrame extends JFrame {
private JMenu fileMenu;
private JMenuBar menuBar;
private JMenuItem openMenuItem;
#Autowired
MyDialog myDialog;
#Autowired
JdbcTemplate jdbcTemplate;
public MyFrame() {
initComponents();
setVisible(true);
}
private void initComponents() {
jdbcTemplate.toString();
this.setTitle("Vue de ma fenêtre");
this.setSize(new Dimension(300, 150));
this.setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new FlowLayout());
menuBar = new JMenuBar();
fileMenu = new JMenu();
openMenuItem = new JMenuItem();
fileMenu.setText("File");
openMenuItem.setText("Inscription");
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myDialog.setVisible(true);
}
});
fileMenu.add(openMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
//
final JButton cmd1 = new JButton("Créer Table");
getContentPane().add(cmd1);
cmd1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
jdbcTemplate.execute(
"CREATE TABLE customer(id bigint(11), nom VARCHAR(55), prenom VARCHAR(55), dnaiss date)");
cmd1.setEnabled(false);
}
});
//
in this sample, jdbcTemplate.toString() returns null, and I can't understand why, because it works below in the action Performed method
Thank you for Help.
this is the way Java initializes class , first constructor got executed later class variables got initialized . untill and unless variables are part of static block .same logic is followed by spring as well .
in your example jdbcTemplate is a class variable, jdbcTemplate.toString(); is called via default constructor , while actionperformed is called on instance of MyFrame .
to know more about class initialization please check below link
http://www.javaworld.com/article/2075796/java-platform/java-101--class-and-object-initialization.html?nsdr=true

Resources