reading the value of a document property from within a behavior - alfresco

question description and code was updated
Question 1: would be with what do I replace the dummy int attachmentid = 123; in the code below in order to read custom property sc:OpenERPattachmentID1 to get the id value stored in it?
(Question 1 was Answered by alfrescian!)
package com.openerp.behavior;
import java.util.List;
import java.net.*;
import java.io.*;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.Behaviour;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.apache.log4j.Logger;
//import com.openerp.model.scOpenERPModel;
public class DeleteAsset implements NodeServicePolicies.BeforeDeleteNodePolicy {
private PolicyComponent policyComponent;
private Behaviour beforeDeleteNode;
private NodeService nodeService;
public void init() {
this.beforeDeleteNode = new JavaBehaviour(this,"beforeDeleteNode",NotificationFrequency.EVERY_EVENT);
this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI,"beforeDeleteNode"),
QName.createQName(scOpenERPModel.NAMESPACE,scOpenERPModel.ASSET_CONTENT_TYPE), this.beforeDeleteNode);
}
public setNodeService(NodeService nodeService){
this.nodeService = nodeService;
}
#Override
public void beforeDeleteNode(NodeRef node) {
System.out.println("beforeDeleteNode!");
try {
QName attachmentID1= QName.createQName("http://www.someco.com/model/content/1.0", "OpenERPattachmentID1"); // this could/shoul be defined in your OpenERPModel-class
int attachmentid = (Integer)nodeService.getProperty(node, attachmentID1);
//int attachmentid = 123;
URL oracle = new URL("http://0.0.0.0:1885/delete/%20?attachmentid=" + attachmentid);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
//System.out.println(inputLine);
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Question 2: where do I put the DeleteAsset.class?
I'm a Java and Alfresco novice, I'd be great if someone could tell me if alfresco-4.2.c/tomcat/webapps/alfresco/WEB-INF/classes/com/openerp/behavior/ is the right folder to put the compiled DeleteAsset.class
Question 3: What should I put in NAMESPACE and ASSET_CONTENT_TYPE?
I'd like to work without the model class as I haven't had a tutorial on that yet, what do I replace scOpenERPModel.NAMESPACE,scOpenERPModel.ASSET_CONTENT_TYPE with?
This is my full custom-web-context file:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN'
'http://www.springframework.org/dtd/spring-beans.dtd'>
<beans>
<!-- Registration of new models -->
<bean id="smartsolution.dictionaryBootstrap" parent="dictionaryModelBootstrap"
depends-on="dictionaryBootstrap">
<property name="models">
<list>
<value>alfresco/extension/scOpenERPModel.xml</value>
</list>
</property>
</bean>
<!-- deletion of attachments within openERP when delete is initiated in Alfresco-->
<bean id="deletionBehavior" class="com.openerp.behavior.DeleteAsset" init-method="init">
<property name="nodeService">
<ref bean="nodeService" />
</property>
<property name="policyComponent">
<ref bean="policyComponent" />
</property>
</bean>

Well, you have a long way to go...what do you like to achieve with your "oracle" connection?
To answer your main questions: How to read a property:
Don't put the XML Model into com/openerp/model/scOpenERPModel - it should be a java class that defines constants to access your custom types, aspects & props (example: https://svn.alfresco.com/repos/alfresco-open-mirror/alfresco/HEAD/root/projects/data-model/source/java/org/alfresco/model/ContentModel.java)
But that is not mandatory - it just helps you.
To read the property
inject NodeService:
private NodeService nodeService;
public setNodeService(NodeService nodeService){
this.nodeService = nodeService;
}
in your beforeDeleteNode
QName attachmentID1= QName.createQName("your sc NS uri", "OpenERPattachmentID1"); // this could/shoul be defined in your OpenERPModel-class
int attachmentid = (Integer) nodeService.getProperty(node, attachmentID1);

Related

unresolved reference in Firestore UI and display it

am using Firebase UI for displaying data in recyler view from Firestore.And i wanna that this query will display on my app but i can't add this reference. Can anyone please guide me on this?
i do my app witch a tutorial but its expired and i try to do and lern a lot of my self but with this i cant do enything
MainACtivity.kt
package com.example.nfc
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
data class User(
val displayName: String = "",
val emojis: String = ""
)
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MainActivity : AppCompatActivity() {
private val db = Firebase.firestore
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
// Query the users collection
val query = db.collection("users")
val options = FirestoreRecyclerOptions.Builder<User>().setQuery(query, User::class.java)
.setLifecycleOwner(this).build()
val adapter = object: FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(this#MainActivity).inflate(android.R.layout.simple_list_item_2,parent,false)
return UserViewHolder(view)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int, model: User) {
val tvName: TextView=holder.itemView.findViewById(android.R.id.text1)
val tvEmojis: TextView=holder.itemView.findViewById(android.R.id.text2)
tvName.text = model.displayName
tvEmojis.text = model.emojis
}
}
uzytkownicy.adapter = adapter
uzytkownicy.layoutManager = LinearLayoutManager(this)
//end
val addButton = findViewById(R.id.addButton)as Button
addButton.setOnClickListener{
val intent = Intent(this, addtrasa::class.java)
startActivity(intent)
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/szarytlo"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
and thats my error
enter image description here
You do not assign an object to uzytkownicy anywhere in your MainActivity, so it is not clear to the compiler what type of object it is meant to be. From the context of the code, it looks like you mean for it to be a RecyclerView, and you probably want to use the one in activity_main.xml. If so, you would need to assign it as such:
val uzytkownicy: RecyclerView = findViewById(R.id.rvUsers)
Then you can go ahead and use that reference to set the adapter and layout manager as you're already attempting to do.

Problem with adding Blocks to Minecraft Mod (1.15.2)

I have spent the last few hours adding a block to my Minecraft Mod. I have looked at several tutorials and none of them work. The blocks are not added to the Creative Inventory and I can't set them by command either. Unfortunately I didn't have any bugs in the console that I could show here. At some point I gave up and tried to do armor, here the same problem. On the other hand: normal items work (You can see the Item "ruby" which woked finde).
Here the code of my main class:
package de.thom.clashOfClasses;
import de.thom.clashOfClasses.init.ArmorMaterialList;
import de.thom.clashOfClasses.init.BlockList;
import de.thom.clashOfClasses.init.ItemList;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
#Mod("clashofclasses")
public class ClashOfClasses {
public static ClashOfClasses instance;
public static final String modid = "clashofclasses";
public static final Logger logger = LogManager.getLogger(modid);
public ClashOfClasses() {
instance = this;
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientRegistries);
MinecraftForge.EVENT_BUS.register(this);
}
public void setup(final FMLCommonSetupEvent event) {
logger.info("Setup method complete");
}
public void clientRegistries(final FMLClientSetupEvent event) {
logger.info("ClientRegistries method complete");
}
#Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void registerItems(final RegistryEvent.Register<Item> event) {
logger.info("Item Registry started");
event.getRegistry().registerAll(
ItemList.RUBY,
ItemList.ruby_block = new BlockItem(BlockList.ruby_block,new Item.Properties().group(ItemGroup.MISC)).setRegistryName(BlockList.ruby_block.getRegistryName())
);
logger.info("Items registerd");
}
#SubscribeEvent
public static void registerBlocks(final RegistryEvent.Register<Block> event) {
logger.info("Block Registry started");
event.getRegistry().registerAll
(
BlockList.ruby_block = new Block(Block.Properties.create(Material.IRON).hardnessAndResistance(2.0f,3.0f).lightValue(5).sound(SoundType.METAL)).setRegistryName(location("ruby_block"))
);
logger.info("Blocks registerd");
}
private static ResourceLocation location(String name){
return new ResourceLocation(ClashOfClasses.modid, name);
}
}
}
Here is the code of BlockList
package de.thom.clashOfClasses.init;
import net.minecraft.block.Block;
public class BlockList {
public static Block ruby_block;
}
Here is the code of ItemList:
package de.thom.clashOfClasses.init;
import de.thom.clashOfClasses.ClashOfClasses;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.ResourceLocation;
public class ItemList
{
//Test Items
public static Item RUBY = new Item(new Item.Properties().group(ItemGroup.MATERIALS)).setRegistryName(location("ruby"));
public static Item ruby_block;
private static ResourceLocation location(String name){
return new ResourceLocation(ClashOfClasses.modid, name);
}
}
A block in the world and a “block” in an inventory are very different things. A block in the world is represented by an IBlockState, and its behavior defined by an instance of Block. Meanwhile, an item in an inventory is an ItemStack, controlled by an Item. As a bridge between the different worlds of Block and Item, there exists the class ItemBlock. ItemBlock is a subclass of Item that has a field block that holds a reference to the Block it represents. ItemBlock defines some of the behavior of a “block” as an item, like how a right click places the block. It’s possible to have a Block without an ItemBlock. (E.g. minecraft:water exists a block, but not an item. It is therefore impossible to hold it in an inventory as one.)
When a block is registered, only a block is registered. The block does not automatically have an ItemBlock. To create a basic ItemBlock for a block, one should use new ItemBlock(block).setRegistryName(block.getRegistryName()). The unlocalized name is the same as the block’s. Custom subclasses of ItemBlock may be used as well. Once an ItemBlock has been registered for a block, Item.getItemFromBlock can be used to retrieve it. Item.getItemFromBlock will return null if there is no ItemBlock for the Block, so if you are not certain that there is an ItemBlock for the Block you are using, check for null.
from https://mcforge.readthedocs.io/en/latest/blocks/blocks/.
I short, if everything works, your blocks shoudnt appear in your
#ObjectHolder(modid)
#Mod.EventBusSunscriber(modid = modid, bus = Bus.Mod)
public class BlockInit {
public static final Block example_block = null;
#SubscribeEvent
public static void registerBlocks(final RegistryEvent.Register<Block> event) {
event.getRegistry().register(new Block(Block.Properties.create(Material)).setRegistry("example_block"));
}
#SubscribeEvent
public static void registerBlockItems(final RegistryEvent.Register<Item> event){
event.getRegistry().register(new BlockItem(example_item, new Item.Properties().group(ItemGroup)).setRegistry("example_block"));
}
That works for me just replace example_block with the name of your block and add more properties if you want
for another block just repeat the event.getRegistry stuff and use the name of your new block instead of example_block.
and don't forget to do the json files

Jsoup to parse multiple websites for links published today

I am currently using jsoup (below) to output a .csv of links which include a string date format in the url from just one website.
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.jsoup.nodes.Element;
public class readAllLinks {
public static Set<String> uniqueURL = new HashSet<String>();
public static String my_site;
public static String published = ("20180731");
public static void main(String[] args) {
readAllLinks obj = new readAllLinks();
my_site = ("news24.com/SouthAfrica/News");
obj.get_links("https://www.news24.com/SouthAfrica/News/");
}
private void get_links(String url) {
try {
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a");
FileOutputStream fout=new FileOutputStream("links.csv");
PrintStream csv=new PrintStream(fout);
links.stream().map((link) -> link.attr("abs:href")).forEachOrdered((this_url) -> {
boolean add = uniqueURL.add(this_url);
if (add && this_url.contains(my_site) && this_url.contains(published)) {
System.out.println(this_url);
get_links(this_url);
}
if (this_url.contains(published))
csv.println(this_url);
} );
} catch (IOException ex) {
}
}
}
Instead I would like to make a csv of links published today (i.e using today's date) from multiple websites.
How do you specify the .select for the newly published links to get the date contained in a span?
And how do you parse multiple websites from a list?
Many thanks for your help.
This will select all links that contains value of variable 'published'.
Elements links = doc.select("a[href*="+published+"]");

Convert xml string to treeview with nodes in Java FX

I have a String that contains an xml like this:
<root>
<type>
<element>
<thing>
<otherthing>...</otherthing>
</thing>
</element>
</type>
<type>
<element>
<thing>
<otherthing>...</otherthing>
</thing>
</element>
</type>
<type>
<element>
<thing>
<otherthing>...</otherthing>
</thing>
</element>
</type>
</root>
I need a treenode in my treeview for each indentation so I can expand and contract it when I want cause there is so much information in each node, how can I do it?
The result should be like this:
ROOT
---+type
--------+element
----------------+thing
----------------------+otherthing
---+type
--------+element
----------------+thing
----------------------+otherthing
---+type
--------+element
----------------+thing
----------------------+otherthing
Thank you!
Use a xml parser to parse the data, create a TreeItem representing it and use a TreeView to display the data.
Example:
private static class TreeItemCreationContentHandler extends DefaultHandler {
private TreeItem<String> item = new TreeItem<>();
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// finish this node by going back to the parent
this.item = this.item.getParent();
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// start a new node and use it as the current item
TreeItem<String> item = new TreeItem<>(qName);
this.item.getChildren().add(item);
this.item = item;
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
String s = String.valueOf(ch, start, length).trim();
if (!s.isEmpty()) {
// add text content as new child
this.item.getChildren().add(new TreeItem<>(s));
}
}
}
public static TreeItem<String> readData(File file) throws SAXException, ParserConfigurationException, IOException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
TreeItemCreationContentHandler contentHandler = new TreeItemCreationContentHandler();
// parse file using the content handler to create a TreeItem representation
reader.setContentHandler(contentHandler);
reader.parse(file.toURI().toString());
// use first child as root (the TreeItem initially created does not contain data from the file)
TreeItem<String> item = contentHandler.item.getChildren().get(0);
contentHandler.item.getChildren().clear();
return item;
}
// display data for file "data/tree.xml" in TreeView
TreeItem<String> root = readData(new File("data/tree.xml"));
TreeView<String> treeView = new TreeView<>(root);

java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v4.app.Fragment

I get this error java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v4.app.Fragment when I try to open my activity CuteCollection.java in my app. The strange part is that when I click on the first line (FragmentPagerAdapter.java:122) in the logcat error, it shows me a line from a file in the v4.support library. I cannot edit that code, so there must be something in my code I can change.
To get to this activity, I click a button in my HomeFragment.java fragment, which is a fragment in my navigation drawer, which also has the android.support.v4.app.Fragment extension, just like all items do in my navigation drawer.
I think it might be something to do with my FragmentPagerAdpater. Although I did change all of my android.app.Fragment to android.support.v4.app.Fragment, but still the same error.
UPDATE: When I click on the first line in the support.v4 library, called FragmentPagerAdapter, it brings up that class and shows Fragment fragment = (Fragment)object; highlighted, which is part of this method (although I can't edit this, since it's from Android):
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (fragment != mCurrentPrimaryItem) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setMenuVisibility(false);
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
mCurrentPrimaryItem = fragment;
}
}
Any tips or advice? Thanks.
CuteCollectionFragment.java
package org.azurespot.cutecollection;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
import org.azurespot.R;
/**
* Created by mizu on 1/26/15.
*/
public class CuteCollection extends ActionBarActivity {
private static final int PHOTO_TAB = 0;
private static final int VIDEO_TAB = 1;
private static final int AUDIO_TAB = 2;
private static final int TEXT_TAB = 3;
PhotoTab photoTab;
TextTab textTab;
VideoTab videoTab;
AudioTab audioTab;
public CuteCollection(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_cute_collection);
// Instantiate tabs
photoTab = new PhotoTab();
textTab = new TextTab();
videoTab = new VideoTab();
audioTab = new AudioTab();
// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(new TabsAdapter(getSupportFragmentManager()));
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip)
findViewById(R.id.tabs);
tabs.setViewPager(pager);
}
private class TabsAdapter extends FragmentPagerAdapter {
public TabsAdapter(FragmentManager fm) {
super(fm);
}
/**
* #return the number of pages (tabs) to display
*/
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Photos";
case 1:
return "Videos";
case 2:
return "Sounds";
case 3:
return "Poems";
}
return null;
}
/**
* #return true if the value returned from
* {#link #instantiateItem(ViewGroup, int)} is the same object
* as the {#link View} added to the {#link ViewPager}.
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch(position){
case PHOTO_TAB:
Bundle photoBundle = new Bundle();
photoBundle.putInt("page_position", position + 1);
PhotoTab pt = new PhotoTab();
pt.setArguments(photoBundle);
return pt;
case VIDEO_TAB :
Bundle videoBundle = new Bundle();
videoBundle.putInt("page_position", position + 1);
VideoTab vt = new VideoTab();
vt.setArguments(videoBundle);
return new VideoTab();
case AUDIO_TAB:
Bundle audioBundle = new Bundle();
audioBundle.putInt("page_position", position + 1);
AudioTab at = new AudioTab();
at.setArguments(audioBundle);
return new AudioTab();
case TEXT_TAB:
Bundle textBundle = new Bundle();
textBundle.putInt("page_position", position + 1);
TextTab tt = new TextTab();
tt.setArguments(textBundle);
return new TextTab();
}
return null;
}
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.pager_item,
container, false);
// Add the newly created View to the ViewPager
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
TextView title = (TextView) view.findViewById(R.id.item_title);
title.setText(String.valueOf(position));
// Return the View
return view;
}
/**
* Destroy the item from the {#link ViewPager}. In our case this is
* simply removing the {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
fragment_cute_collection.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#2198bb" >
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
custom:pstsTextColorSelected="#ffffff"
custom:pstsUnderlineColor="#ffffff"
custom:pstsIndicatorColor="#ffffff"
android:textColor="#2198bb"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:background="#android:color/white" />
</RelativeLayout>
Logcat
03-07 18:35:42.669 6340-6340/org.azurespot E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: org.azurespot, PID: 6340
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v4.app.Fragment
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:122)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:17619)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:17619)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5428)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17619)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5428)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:17619)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5428)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17619)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5428)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:17619)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5428)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2588)
at android.view.View.measure(View.java:17619)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2317)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1412)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1613)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1270)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6691)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
at android.view.Choreographer.doCallbacks(Choreographer.java:613)
at android.view.Choreographer.doFrame(Choreographer.java:583)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5731)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Your current code seems to run into trouble unless you fix the Exception error. There is a working sample code from Google, and this is quite similar to your code design and meets your vision. I have tried it, and it works. Link at SlidingTabsBasic . One warning is that you will have to change your Gradle build file. If you choose this route, then I can post my build file.
Another similar sample on the same webpage is SlidingTabsColors, which sounds good since I end up in customizing colors for any GUI I make. The SDKs are possibly available on your local drive if you installed it.
If you decide on this route, just accept it as best answer, and post whatever issues you may come up with. At least, I know the sample code works.
Just to let you know, there is an interesting reading at Creating Swipe Views with Tabs, which meets your vision also, and the code seems simpler than what I recommend above. But...it uses ActionBar.TabListener which is deprecated for Lollipop, API version 21. Your choice...
There may be 2 different solutions/parts.
Part 1)
In your posted Java file, do this:
import android.support.v4.app.Fragment ;
remove or comment out:
import android.app.Fragment;
The reason is you are using android.support.v4.app.Fragment. And this is not compatible with your current import android.app.Fragment. Also all your imports reference android.support.v4, so you know you should do it anyway to be consistent :-)
Unfortunately the compiler does not detect this incompatibility.
Part 2)
Since you're using ActionBarActivity, there may be an issue with the build file or settings. The problem is confirmed by others in Stackoverflow # ActionBarActivity cannot resolve a symbol and Error inflating class from library. I know your error sounds different but I think the problem may be the same. Basically you can check your build gradle file (assuming you're using it):
dependencies {
compile "com.android.support:support-v4:21.0.2"
}
The idea is to use compile "com.android.support:support-v4..."

Resources