Canot invok "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null at pageObject.LandingPage.searchItem - selenium-webdriver

below landingpage.java code and LandingPageStepDefination.java
where to make changes so that NullPointerException issue will resolve
.................Landingpage.java.............
public class **LandingPage** {
public WebDriver driver;
By search=By.xpath("//input[#placeholder='Search for Vegetables and Fruits']");
By ProductName=By.cssSelector("h4.product-name");
By topDeals=By.xpath("//a[normalize-space()='Top Deals']");
public LandingPage(WebDriver driver)
{
this.driver=driver;
}
public void searchItem(String name)
{
driver.findElement(search).sendKeys(name);
}
public String getProductName()
{
return driver.findElement(ProductName).getText();
}
public void SelectTopDealsPage()
{
driver.findElement(topDeals).click();
}
}
...................landingpagestepDefination.java
public class LandingPageStepDefination {
public WebDriver driver;
public String landingproductName;
public String offerpageproductname;
pageObjectManager pageObjectManager;
// setups setups1;
setups setups;
LandingPage LandingPageLandingPage;
public LandingPageStepDefination(setups setups) {
this.setups = setups;
}
#Given("user in greencart landing page")
public void user_in_greencart_landing_page() {
}
#When("user search with shortname {string} and extrach actual name of product")
public void user_search_with_shortname_and_extrach_actual_name_of_product(String Shrotname)
throws InterruptedException {
LandingPage LandingPage = setups.pageObjectManager.getMeLandingPage();
LandingPage.searchItem(Shrotname);
Thread.sleep(5000);
setups.landingproductName = LandingPage.getProductName().split("-")[0].trim();
System.out.println(landingproductName);
}
}

Related

Data not inserting into the Database room Android

I'm new to android and this is the first time I'm using room in my application. Either insert operation is not performed or the database is not created or any other error.
I don't know what I'm doing wrong so I need your help.
This program is running but No result is displayed. Nothing is showing on the screen.
Here is my code-
please let me know what is wrong in this code and what I should do to correct it.
Car_details.java
#PrimaryKey
#NonNull
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("desc")
#Expose
private String desc;
#SerializedName("image")
#Expose
private String image;
CarDao.java-
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Car_Details car_details);
#Query("Select * from car_table")
LiveData<List<Car_Details>> selectAll();
CarListDatabase.java
private static CarListDatabase instance;
public abstract CarDao carDao();
public static synchronized CarListDatabase getInstance(Context context){
if(instance==null)
{
instance= Room.databaseBuilder(context.getApplicationContext(),
CarListDatabase.class,"Car_database").fallbackToDestructiveMigration()
.build();
}
return instance;
}
CarRepository.java
public void getCarList(){
CarlistInterface carlistInterface= retrofit.create(CarlistInterface.class);
Call<List<Car_Details>> carList= carlistInterface.carList();
carList.enqueue(new Callback<List<Car_Details>>() {
#Override
public void onResponse(Call<List<Car_Details>> call, final Response<List<Car_Details>> response) {
if(response.body() != null){
List<Car_Details> car_details = response.body();
for (int i = 0; i < car_details.size(); i++) {
String id=car_details.get(i).getId();
String names = car_details.get(i).getName();
String desc=car_details.get(i).getDesc();
String image= car_details.get(i).getImage();
Car_Details car = new Car_Details();
car .setId(id);
car .setName(names);
car .setDesc(desc);
car .setImage(image);
new InsertNoteAsyncTask(carDao).execute(car);
}
}
}
});
}
public LiveData<List<Car_Details>> getCarLists(){
return allCarList;
}
private static class InsertNoteAsyncTask extends AsyncTask<Car_Details,Void,Void> {
private CarDao carDao;
private InsertNoteAsyncTask(CarDao carDao){
this.carDao= carDao;
}
#Override
protected Void doInBackground(Car_Details... car_details) {
carDao.insert(car_details[0]);
return null;
}
CarViewModel.java
public CarViewModel(#NonNull Application application) {
super(application);
repository= new CarRepository(application);
carList= repository.getCarLists();
}
public LiveData<List<Car_Details>> getListLiveData() {
return carList;
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
repository = new CarRepository(this);
carViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
recyclerView= findViewById(R.id.cars_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List = new ArrayList<>();
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
carViewModel.getListLiveData().observe(this, new
Observer<java.util.List<Car_Details>>() {
#Override
public void onChanged(java.util.List<Car_Details> car_details) {
recyclerAdapter.setUserList(List);
}
});
repository.getCarList();
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter {
List<Car_Details> carList= new ArrayList<>();
public RecyclerAdapter(List<Car_Details> carList) {
this.carList = carList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater= LayoutInflater.from(parent.getContext());
View view= layoutInflater.inflate(R.layout.row_item,parent,false);
return new RecyclerAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.car_name.setText(carList.get(position).getName());
holder.car_desc.setText(carList.get(position).getDesc());
}
public void setUserList(List<Car_Details> userList) {
this.carList = userList;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
There is nothing wrong with your insert operation with room.
The way you have used live date in your application seems wrong that's why your program is running but no result is coming.
You have to check the part where you are using live data.
Hope this help you out.

EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT AT LINE 1 COLUMN 2 PATH $22

I want to access JSON array . so I created 2 Object !!Have a look at my code , Url
Url-cricapi.com/api/matches/?apikey=JimJAfsmRGOnDpCrRrqO6htlilg1
My MatchesArrayClass
package com.piyushjaiswal.jsonpractis;
public class MatchesArray {
private Matches matches;
private provider provider2;
public MatchesArray(Matches matches, provider provider2) {
this.matches = matches;
this.provider2 = provider2;
}
public Matches getMatches() {
return matches;
}
public void setMatches(Matches matches) {
this.matches = matches;
}
public provider getProvider2() {
return provider2;
}
public void setProvider2(provider provider2) {
this.provider2 = provider2;
}
}
Matches Class
package com.piyushjaiswal.jsonpractis;
import com.google.gson.annotations.SerializedName;
public class Matches {
private int unique_id;
private String date;
private String dateTimeGMT;
#SerializedName("team-1")
private String team1;
#SerializedName("team-2")
private String team2;
private String type;
private String toss_winner_team;
private boolean squad;
private boolean matchStarted;
public int getUnique_id() {
return unique_id;
}
public void setUnique_id(int unique_id) {
this.unique_id = unique_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDateTimeGMT() {
return dateTimeGMT;
}
public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getToss_winner_team() {
return toss_winner_team;
}
public void setToss_winner_team(String toss_winner_team) {
this.toss_winner_team = toss_winner_team;
}
public boolean isSquad() {
return squad;
}
public void setSquad(boolean squad) {
this.squad = squad;
}
public boolean isMatchStarted() {
return matchStarted;
}
public void setMatchStarted(boolean matchStarted) {
this.matchStarted = matchStarted;
}
}
My Provider class
package com.piyushjaiswal.jsonpractis;
public class provider {
private String source;
private String url;
private String pubDate;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
MainActivity Class
package com.piyushjaiswal.jsonpractis;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private JsonPlaceHolderApi jsonPlaceHolderApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://cricapi.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
getMatchList();
}
private void getMatchList() {
Call<List<MatchesArray>> call = jsonPlaceHolderApi.getPosts("JimJAfsmRGOnDpCrRrqO6htlilg1");
call.enqueue(new Callback<List<MatchesArray>>() {
#Override
public void onResponse(Call<List<MatchesArray>> call, Response<List<MatchesArray>> response) {
if(!response.isSuccessful()){
textView.setText(response.message() + "123");
return;
}
List<MatchesArray> list = response.body();
textView.setText(list.get(0).getMatches().getDate());
}
#Override
public void onFailure(Call<List<MatchesArray>> call, Throwable t) {
textView.setText(t.getMessage() +"22");
}
});
}
}
But output on screenshot is
"Expected BEGIB_ARRAY but was BEGIN_OBJECT at line 1 column 2 patg $2"
Your JSON syntax is wrong. The response starts with {"matches":[, this means it is an object, with the parameter matches that is of type match[].
So, you need a new class along the lines of:
public class MatchesWrapper {
private List<Matches> matches;
}
And change all your Call<List<MatchesArray>> to Call<MatchesWrapper>.
The error you received tells you this. You expected an array of Matches (Expected BEGIN_ARRAY), but instead received an object (was BEGIN_OBJECT).

How to display data in firestore with recyclerview in frgaments?

I'm new to android programming and I have a problem in displaying data from firestore. I want to display the data in fragments in the navigation drawer. I found tutorials that display it on activities but nothing in fragments. Please help me with this.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
FragmentTransaction fragmentTransaction;
private boolean shouldLoadProductFragOnBackPress = false;
public static int navItemIndex = 0;
public FirebaseAuth mAuth;
FirebaseFirestore db = FirebaseFirestore.getInstance();
private void Load_Product_fragment() {
navItemIndex = 0;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new ProductFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Productfragment_Title);
drawerLayout.closeDrawers();
}
private void Load_Service_fragment(){
navItemIndex = 1;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new ServiceFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Servicefragmnet_Title);
drawerLayout.closeDrawers();
shouldLoadProductFragOnBackPress = true;
}
private void Load_Account_fragment(){
navItemIndex = 2;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new AccountFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Accountfragment_Title);
drawerLayout.closeDrawers();
shouldLoadProductFragOnBackPress = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.Toolbar_Layout);
setSupportActionBar(toolbar);
drawerLayout=(DrawerLayout) findViewById(R.id.Drawer_Layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
drawerLayout.openDrawer(Gravity.LEFT);
Load_Product_fragment();
navigationView= findViewById(R.id.Navigation_View);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.Productsfragment_ND:
Load_Product_fragment();
item.setChecked(true);
break;
case R.id.Servicefragment_ND:
Load_Service_fragment();
item.setChecked(true);
break;
case R.id.Accountfragemnt_ND:
Load_Account_fragment();
item.setChecked(true);
break;
}
return false;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadProductFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex !=0) {
navItemIndex = 0;
shouldLoadProductFragOnBackPress = false;
Load_Product_fragment();
return;
}
}
super.onBackPressed();
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
public void del(View view) {db.collection("products").document("test")
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
This is my main-activity.It contains the requirements for a navigation drawer for 3 fragments.I have a Firestore database linked to the app. I need to display the contents of the database in these fragments.
Next i will show one fragment and the recyclerview adapter and view holder i have tried using.
I am not sure if it is the correct way to do it.Please help me with this
public class ProductFragment extends Fragment {
private static final String TAG = ProductFragment.class.getSimpleName();
private RecyclerView recipeRecyclerview;
private LinearLayoutManager linearLayoutManager;
private Product_adapter mAdapter;
private DatabaseReference mDatabaseRef;
private DatabaseReference childRef;
public ProductFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_product, container, false);
getActivity().setTitle(getString(R.string.Productfrag_title));
linearLayoutManager = new LinearLayoutManager(getActivity());
recipeRecyclerview = view.findViewById(R.id.List_recycleview);
recipeRecyclerview.setHasFixedSize(true);
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
childRef = mDatabaseRef.child("recipes");
mAdapter = new Product_adapter(Product_response.class, R.layout.list_layout, View_holder.class, childRef, getContext());
recipeRecyclerview.setLayoutManager(linearLayoutManager);
recipeRecyclerview.setAdapter(mAdapter);
return view;
}
}
This is my products-fragment. I have tried to add the recycler view.
Adapter
public class Product_adapter extends RecyclerView.Adapter {
FirebaseFirestore db = FirebaseFirestore.getInstance();
private Context context;
Query query = db.collection("products");
FirestoreRecyclerOptions<Product_response> response = new FirestoreRecyclerOptions.Builder<Product_response>()
.setQuery(query, Product_response.class)
.build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<Product_response, View_holder>(response) {
#Override
protected void onBindViewHolder(View_holder holder, int position, Product_response model) {
}
#Override
public View_holder onCreateViewHolder(ViewGroup group, int i) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.list_layout, group, false);
return new View_holder(view);
}
};
public Product_adapter(Class<Product_response> product_responseClass, int list_layout, Class<View_holder> view_holderClass, DatabaseReference childRef, Context context) {
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
View holder
public class View_holder extends RecyclerView.ViewHolder{
private static final String TAG = View_holder.class.getSimpleName();
public TextView main_text, subtext ;
public ImageView image;
public View_holder(View itemView) {
super(itemView);
main_text = (TextView)itemView.findViewById(R.id.List_maintext);
subtext = (TextView)itemView.findViewById(R.id.List_subtext);
image = (ImageView)itemView.findViewById(R.id.List_imageview);
}
}
Next i will show the response page where i used the getter and setter for the firebase
import com.google.firebase.firestore.IgnoreExtraProperties;
#IgnoreExtraProperties
public class Product_response {
private String Product;
private String Cost;
public Product_response() {
}
public Product_response(String Product, String Cost){
this.Product= Product;
this.Cost= Cost;
}
public String getProduct() {
return Product;
}
public void setProduct(String Product) {
this.Product = Product;
}
public String getCost(){
return Cost;
}
public void setCost(String Cost)
{
this.Cost = Cost;
}
}
This is how my database looks like. I need to display this products in my fragment
This is the github link of the app. Please help me complete this

How to get page object relative to another page object in Selenium WebDriver

I'm looking for solution how to get page object relative to another object in Page Object Model for selenium webdriver
Code of my test:
class StartPage {
WebDriver driver;
public HomePage(driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//a[text()='link text']")
WebElement linkInWidget;
public void clickLink() {
linkInWidget.click();
return PageFactory.initElements(driver, NextPage.class);
}
}
Next page
class NextPage {
WebDriver driver;
public HomePage(driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//input[#type='button']")
WebElement buttonInWidget;
#FindBy(id = "Index")
WebElement index;
public void clickButton() {
buttonInWidget.click();
return PageFactory.initElements(driver, NextPage.class);
}
public String getText() {
return index.getText();
}
}
Configuration class
public class ConfigureTest{
protected WebDriver driver;
protected String baseUrl;
protected StartPage startPage;
protected NextPage nextPage ;
#BeforeSuite
public void setUp() {
baseUrl = "http://webapp.com/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
}
And class of my test
public class SomeTest extends ConfigureTest {
#Test
public void testLinkAndButton() throws Exception {
startPage = PageFactory.initElements(driver, SomePage.class);
driver.get(baseUrl);
nextPage = startPage.clickLink();
nextPage.clickButton();
String data = nextPage.getText();
}
}
In both classes FirstPage and NextPage i find elements by xpath which has same first part //div[#class='widget'] it mean that all elements like buttons and links are under this widget and i have same xpath for widgets in my all pages
Problem: if only xpath of my widget will be changed i must make changes in all page objects of my test
Question: Is in any way how to improve my test for more flexibility with usage like:
page().get(Widget.class, "Widget name").get(Button.class, "Button name").click
Update: I resolve part of this problem in such way:
I create classes of my UI elements with get methods which can return objects of any class:
Class of Widget object
public class widget{
WebDriver driver;
public widget (WebDriver driver) {
this.driver = driver;
}
// Find a single element
#FindBy(xpath="//div[#class='tsf-p']")
WebElement linkInWidget;
public void click() {
linkInWidget.click();
}
public <T> T get(Class<T> expectedPage, String uiclass){
return PageFactory.initElements(driver, expectedPage);
}
}
Class of Button object
public class Button {
WebDriver driver;
public Button (WebDriver driver) {
this.driver = driver;
}
#FindBy(name="btnG")
WebElement button;
public void click() {
button.click();
}
public <T> T get(Class<T> expectedPage){
return PageFactory.initElements(driver, expectedPage);
}
}
Class of HomePage
public class HomePage {
WebDriver driver;
public HomePage(WebDriver driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//a[text()='']")
WebElement linkInWidget;
public void click() {
linkInWidget.click();
}
public <T> T get(Class<T> expectedPage, String name){
return PageFactory.initElements(driver, expectedPage);
}
}
My test
public class searchTest {
WebDriver driver;
#BeforeTest
public void setup() {
driver = new FirefoxDriver();
driver.get("https://www.google.com.ua/");
}
#Test
public void testUI() {
HomePage homePage = PageFactory.initElements(driver, HomePage.class);
widget widget = PageFactory.initElements(driver, widget.class);
homePage.get(widget.class).get(Input.class).setValue("yahoo");
homePage.get(widget.class).get(Button.class).click();
}
}
And a result is that we can compose any object by using our classes
homePage.get(widget.class).get(Input.class).setValue("yahoo");
But how to get element by it name or number for example:
homePage.get(widget.class, "Name").get(Input.class, 1).setValue("yahoo");
I have a public repository here where I have implemented PageObject and PageFactory concept with TestNG. You are probably looking for a better way to inherit BaseClasse. The common methods should be placed in BaseClass and available to all PageObjects through inheritance. I have everything placed in GitHub and it's too broad to implement here.

Provide custom rootpath to Nancy when using OWIN

I have a sample application that shows how to host Nancy on node.js.
To do that I need to change the rootpath. I ended up with something like that:
public class Startup
{
public static void Configuration(IAppBuilder app)
{
string rootpath = app.Properties["node.rootpath"] as string;
app.UseNancy(options => options.Bootstrapper = new NodeBootstrapper(rootpath));
}
}
public class NodeRootPathProvider : IRootPathProvider
{
private string rootpath;
public NodeRootPathProvider(string rootpath)
{
this.rootpath = rootpath;
}
public string GetRootPath()
{
return this.rootpath;
}
}
public class NodeBootstrapper : DefaultNancyBootstrapper
{
private string rootpath;
public NodeBootstrapper(string rootpath)
: base()
{
this.rootpath = rootpath;
}
protected override IRootPathProvider RootPathProvider
{
get { return new NodeRootPathProvider(this.rootpath); }
}
}
Is there a way to simplfy this?

Resources