How to make a View object in Java in Android Studio? - android-studio

In my program I have a class called GameView that is a View meaning it has Context and attrs attached to it. I have several non static methods and variables in this class that I would like to call in my MainActivity class but since it takes context and attrs I cant seem to figure out how to properly create an object in this situation. I have tried creating Context and SetAttribute variables in MainActivity to fill in the missing gaps but I think it makes it have a null exception and the app crashes as a result. I really need help on this since if I get this fixed I think my program will work really well. Below is a simplified version of my issue.
This is what I tried doing in the MainActivity to create object of GameView and to call the Method:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GameView gv = new GameView(context, attrs);
gv.myMethod();
This is what is in the GameView Class:
public class GameView extends View {
public GameView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public void MyMethod() {
//stuff happens here
}

it is okay for me
public class GameView extends View {
public GameView(Context context) {
super(context);
}
public GameView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public GameView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void MyMethod() {
//stuff happens here
}
}
in MainActivity in onCreate:
AttributeSet attrs = new AttributeSet(){
#Override
public int getAttributeCount() {
return 0;
}
#Override
public String getAttributeName(int index) {
return null;
}
#Override
public String getAttributeValue(int index) {
return null;
}
#Override
public String getAttributeValue(String namespace, String name) {
return null;
}
#Override
public String getPositionDescription() {
return null;
}
#Override
public int getAttributeNameResource(int index) {
return 0;
}
#Override
public int getAttributeListValue(String namespace, String attribute, String[] options, int defaultValue) {
return 0;
}
#Override
public boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue) {
return false;
}
#Override
public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) {
return 0;
}
#Override
public int getAttributeIntValue(String namespace, String attribute, int defaultValue) {
return 0;
}
#Override
public int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue) {
return 0;
}
#Override
public float getAttributeFloatValue(String namespace, String attribute, float defaultValue) {
return 0;
}
#Override
public int getAttributeListValue(int index, String[] options, int defaultValue) {
return 0;
}
#Override
public boolean getAttributeBooleanValue(int index, boolean defaultValue) {
return false;
}
#Override
public int getAttributeResourceValue(int index, int defaultValue) {
return 0;
}
#Override
public int getAttributeIntValue(int index, int defaultValue) {
return 0;
}
#Override
public int getAttributeUnsignedIntValue(int index, int defaultValue) {
return 0;
}
#Override
public float getAttributeFloatValue(int index, float defaultValue) {
return 0;
}
#Override
public String getIdAttribute() {
return null;
}
#Override
public String getClassAttribute() {
return null;
}
#Override
public int getIdAttributeResourceValue(int defaultValue) {
return 0;
}
#Override
public int getStyleAttribute() {
return 0;
}
};
GameView gv = new GameView(MainActivity.this,attrs);
gv.MyMethod();
other way create attrs use below link:
https://developer.android.com/training/custom-views/create-view#java

Related

How do I make a class definition for an ArrayList<byte[]>

I am trying to make my class implement VersionedPortable.
It has a field
ArrayList<byte[]> someMessages = new ArrayList<>();
How do I specify this field in my ClassDefiniton?
I assume it would be something like
new ClassDefinitionBuilder(FACTORY_ID, MESSAGE_BUNDLE_CLASS_ID, VERSION_ID)
.addPortableArrayField("someMessages", ?? what goes here ??)
And how would I read and write them?
Arrays of arrays are not supported in the Portable format by default. However, you can use the following trick to wrap the nested array as a separate Portable type and write your field as a Portable array.
class Foo implements Portable {
private ArrayList<byte[]> messages;
#Override
public int getFactoryId() {
return 1;
}
#Override
public int getClassId() {
return 1;
}
#Override
public void writePortable(PortableWriter writer) throws IOException {
Portable[] wrappedMessages = messages.stream()
.map(ByteArrayWrapper::new)
.toArray(Portable[]::new);
writer.writePortableArray("messages", wrappedMessages);
}
#Override
public void readPortable(PortableReader reader) throws IOException {
messages = Arrays.stream(reader.readPortableArray("messages"))
.map(item -> ((ByteArrayWrapper) item).getArray())
.collect(Collectors.toCollection(ArrayList::new));
}
}
class ByteArrayWrapper implements Portable {
private byte[] array;
public ByteArrayWrapper() {
}
public ByteArrayWrapper(byte[] array) {
this.array = array;
}
#Override
public int getFactoryId() {
return 1;
}
#Override
public int getClassId() {
return 2;
}
#Override
public void writePortable(PortableWriter writer) throws IOException {
writer.writeByteArray("array", array);
}
#Override
public void readPortable(PortableReader reader) throws IOException {
array = reader.readByteArray("array");
}
public byte[] getArray() {
return array;
}
}

How can I see all data with RecyclerView?

I cannot show all datas to RecyclerView.I keep getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.cdirect.weatherapp.MyLocations.onCreate(MyLocations.java:50)
MyLocations.java: 50:
rcView.setAdapter(adapter);
MyLocations.java code:
public class MyLocations extends AppCompatActivity {
BottomNavigationView altNav;
RecyclerView rcView;
ArrayList<Locations> locationsList;
DatabaseReference dbRef;
Adapter adapter;
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(MyLocations.this,MainActivity.class));
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbRef = FirebaseDatabase.getInstance().getReference("Locations");
altNav = (BottomNavigationView) findViewById(R.id.altNav);
rcView = findViewById(R.id.rvLocations);
locationsList = new ArrayList<>();
adapter = new Adapter(MyLocations.this, locationsList);
rcView.setAdapter(adapter); //ERROR LINE
rcView.setLayoutManager(new LinearLayoutManager(this));
Adapter.java codes:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
ArrayList<Locations> locationsArrayList;
Context context;
public Adapter (Context context, ArrayList<Locations> locationsArrayList){
this.locationsArrayList=locationsArrayList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.recycler_view_row,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Locations loc = locationsArrayList.get(position);
holder.location.setText(loc.getLocation());
holder.temperature.setText(loc.getTemp());
}
#Override
public int getItemCount() {
return locationsArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView location, temperature;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
location = itemView.findViewById(R.id.tvLocation);
temperature= itemView.findViewById(R.id.tvTemp);
}
}
}
Locations.java code:
public class Locations {
String location;
String temp;
String id;
public Locations(String location, String temp, String id) {
this.location = location;
this.temp = temp;
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I cannot solve where is the problem. Can you help me?

how to get all values added to recyclerview and send it to ion lib

so im trying to get recyclerview data list added and send it to ion lib when i use method below i only get one element as ill have to change string inside for() to String fav =null ouside of for() and log.d only shows the last result. i need get all so i can send to senddata() to ion lib
FavModelClass
private String fav;
private String user_id;
public FavModelClass(String fav, String user_id) {
this.fav = fav;
this.user_id = user_id;
}
public String getFav() {
return fav;
}
public void setFav(String fav) {
this.fav = fav;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
adapter
public class FavAdapter extends
RecyclerView.Adapter<FavAdapter .MyViewHolder> {
private List<FavModelClass> favModelClassList;
private Context beddingContext;
public FavAdapter (List<FavModelClass> favModelClassList, Context
beddingContext) {
this.favModelClassList= favModelClassList;
this.beddingContext = beddingContext;
}
#NonNull
#Override
public FavAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amenitylayout,parent,false);
FavAdapter .MyViewHolder holder = new FavAdapter .MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull FavAdapter.MyViewHolder holder, int i) {
final FavModelClassdata = favModelClassList.get(i);
holder.ac_bedding_type.setText(data.getFav()+" "+"MAX:"+data.getUser_id());
holder.delete_entry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeAt(holder.getAdapterPosition());
}
});
}
public void removeAt(int position) {
favModelClassList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, favModelClassList.size());
}
#Override
public int getItemCount() {
return favModelClassList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView ac_bedding_type;
private ImageButton delete_entry;
public MyViewHolder(#NonNull View v) {
super(v);
ac_bedding_type = v.findViewById(R.id.ac_amenity_name);
delete_entry = v.findViewById(R.id.delete_amenity_entry);
}
}
}
Main activity
fav_recycler = findViewById(R.id.fave_recycler);
GridLayoutManager layoutManager1 = new GridLayoutManager(getApplicationContext(), 2,GridLayoutManager.VERTICAL, false);
fav_recycler.setHasFixedSize(true);
fav_recycler.setLayoutManager(layoutManager1);
favModelClassList= new ArrayList<>();
addfavamenity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
favModelClassList.add(new FavModelClass(
amenityET.getText().toString(),
user_idET.getText().toString()
));
amenityET.setText("");
user_idET.setText("");
FavAdapter adapter = new FavAdapter (favModelClassList, getApplicationContext());
adapter.notifyDataSetChanged();
fav_recycler.setAdapter(adapter);
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
final String fav= data.getFav();
final String user_id = data.getUser_id();
Log.d(TAG, "onClick: "+ fav);
}
}
});
ArrayList d = new ArrayList();
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
d.add(data.getFav());
}
Log.d(TAG, "onClick: " + d);

Website Scraping html class identification issues

I want to scrape MAL for character imgurl to later display using Picasso and name of character but am having troubles accessing the correct class files.
Here is the website under inspect. TYSM in advance.
Inspect MAL
Here is my CharacterList class which identifies the HTML classes
private RecyclerView recyclerView;
private ParseAdapter adapter;
private ArrayList<ParseItem> parseItems = new ArrayList<>();
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_watch_list);
configureBackButton();
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.recyclerView_character);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ParseAdapter(parseItems, this);
recyclerView.setAdapter(adapter);
Content content = new Content();
content.execute();
}
private class Content extends AsyncTask<Void, Void,Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
progressBar.setAnimation(AnimationUtils.loadAnimation(CharacterList.this, android.R.anim.fade_in));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
progressBar.setAnimation(AnimationUtils.loadAnimation(CharacterList.this, android.R.anim.fade_out));
adapter.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected Void doInBackground(Void... voids) {
try{
//website url
String url = "https://myanimelist.net/character.php";
Document doc = Jsoup.connect(url).get();
Elements data = doc.select("tr.people");
int size = data.size();
for (int i = 0; i < size; i++){
String imgUrl = data.select("a.mr8.ml12.fl-l")
.select("img")
.eq(i)
.attr("src");
String title = data.select("tr.mt24.di-ib.information")
.select("a.fw-b.fs14")
.eq(i)
.text();
parseItems.add(new ParseItem(imgUrl, title));
Log.d("items", "img: " +imgUrl + " .title: " + title);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I believe my ParseAdapter and ParseItem are working but just in case here they are
public class ParseAdapter extends RecyclerView.Adapter<ParseAdapter.ViewHolder> {
private ArrayList<ParseItem> parseItems;
private Context context;
public ParseAdapter(ArrayList<ParseItem> parseItems, Context context){
this.parseItems = parseItems;
this.context = context;
}
#NonNull
#Override
public ParseAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.parse_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ParseAdapter.ViewHolder holder, int position) {
ParseItem parseItem = parseItems.get(position);
holder.textView.setText(parseItem.getTitle());
Picasso
//with vs get()
.with(this.context)
.load(parseItem.getImgurl())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return parseItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView_character);
textView = itemView.findViewById(R.id.textView_character);
}
}
}
public class ParseItem {
private String imgurl;
private String title;
public ParseItem(){
}
public ParseItem(String imgurl, String title) {
this.imgurl = imgurl;
this.title = title;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}}
I figured it out nevermind. Here is the class identification part in case anyone is stuck later on.
Elements data = doc.select("td.people");
int size = data.size();
for (int i = 0; i < size; i++){
String imgUrl = data.select("a.fl-l.ml12.mr8")
.select("img")
.eq(i)
.attr("data-src");
String title = data.select("div.information.di-ib.mt24")
.select("a.fs14.fw-b")
.eq(i)
.text();

ActionBar tabs with MapView

I've created app using SherlockActionBar tab. One with my tabs contains MapView (Google Maps v2). Currently I have problem when I change tabs (screen below):
enter link description here
Next tab should contain ListView. Sometimes context second tab loaded correctly. Also I have problem with swiping my MapView. Currently I can only swiping up and down direction. I hope that somebody help me.
My code:
myfragment.xml
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
TabFragment_Map.java
public class TabFragment_Map extends SherlockFragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
return view;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
}
MainActivity.java
public class MainActivity extends SherlockFragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
String TabFragment_Cafes;
String TabFragment_Details;
//Settery & gettery używane w mechanizmie przesyłania informacji pomiędzy fragmentami
public String getTabFragment_Cafes() {
return TabFragment_Cafes;
}
public void setTabFragment_Cafes(String tabFragment_Cafes) {
TabFragment_Cafes = tabFragment_Cafes;
}
public String getTabFragment_Details() {
return TabFragment_Details;
}
public void setTabFragment_Details(String tabFragment_Details) {
TabFragment_Details = tabFragment_Details;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.DISPLAY_SHOW_HOME);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Mapa"), TabFragment_Map.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Kawiarnie"), TabFragment_Cafes.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Szczegóły"), TabFragment_Details.class, null);
if (savedInstanceState != null)
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}
public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = ((SherlockFragmentActivity)activity).getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public void onPageScrollStateChanged(int arg0) {}
public void onPageScrolled(int arg0, float arg1, int arg2) {}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag)
mViewPager.setCurrentItem(i);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
}
You need a custom viewpager that intercepts the swipes
package com.ecs.google.maps.v2.component;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
// When using Maps V1
// if(v instanceof MapView){
// return true;
// }
// return super.canScroll(v, checkV, dx, x, y);
// When using Maps V2
if (v.getClass().getPackage().getName().startsWith("maps.")) {
return true;
}
return super.canScroll(v, checkV, dx, x, y);
}
}
Put this in your layout :
<com.ecs.google.maps.v2.component.CustomViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity">
And the swiping gestures should work.

Resources