Admob - RNAMobRewardedVideoAdModule is not abstract - reactjs

Steps:
react-native init App
npm i react-native-admob -S
react-native link
react-native run-android
Error:
Show image
error: RNAdMobRewardedVideoAdModule is not abstract and does not override abstract method onRewardedVideoCompleted() in RewardedVideoAdListener
public class RNAdMobRewardedVideoAdModule extends ReactContextBaseJavaModule implements RewardedVideoAdListener
Archive RNAdMobRewardedVideoAdModule
package com.sbugert.rnadmob;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.AdRequest;
public class RNAdMobRewardedVideoAdModule extends
ReactContextBaseJavaModule implements RewardedVideoAdListener {
RewardedVideoAd mRewardedVideoAd;
String adUnitID;
String testDeviceID;
Callback requestAdCallback;
Callback showAdCallback;
#Override
public String getName() {
return "RNAdMobRewarded";
}
public RNAdMobRewardedVideoAdModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public void onRewarded(RewardItem rewardItem) {
WritableMap reward = Arguments.createMap();
reward.putInt("amount", rewardItem.getAmount());
reward.putString("type", rewardItem.getType());
sendEvent("rewardedVideoDidRewardUser", reward);
}
#Override
public void onRewardedVideoAdLoaded() {
sendEvent("rewardedVideoDidLoad", null);
requestAdCallback.invoke();
}
#Override
public void onRewardedVideoAdOpened() {
sendEvent("rewardedVideoDidOpen", null);
}
#Override
public void onRewardedVideoStarted() {
sendEvent("rewardedVideoDidStart", null);
}
#Override
public void onRewardedVideoAdClosed() {
sendEvent("rewardedVideoDidClose", null);
}
#Override
public void onRewardedVideoAdLeftApplication() {
sendEvent("rewardedVideoWillLeaveApplication", null);
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
WritableMap event = Arguments.createMap();
String errorString = null;
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorString = "ERROR_CODE_INTERNAL_ERROR";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorString = "ERROR_CODE_INVALID_REQUEST";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorString = "ERROR_CODE_NETWORK_ERROR";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorString = "ERROR_CODE_NO_FILL";
break;
}
event.putString("error", errorString);
sendEvent("rewardedVideoDidFailToLoad", event);
requestAdCallback.invoke(errorString);
}
private void sendEvent(String eventName, #Nullable WritableMap params) {
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
#ReactMethod
public void setAdUnitID(String adUnitID) {
this.adUnitID = adUnitID;
}
#ReactMethod
public void setTestDeviceID(String testDeviceID) {
this.testDeviceID = testDeviceID;
}
#ReactMethod
public void requestAd(final Callback callback) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run () {
RNAdMobRewardedVideoAdModule.this.mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getCurrentActivity());
RNAdMobRewardedVideoAdModule.this.mRewardedVideoAd.setRewardedVideoAdListener(RNAdMobRewardedVideoAdModule.this);
if (mRewardedVideoAd.isLoaded()) {
callback.invoke("Ad is already loaded."); // TODO: make proper error
} else {
requestAdCallback = callback;
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
if (testDeviceID != null){
if (testDeviceID.equals("EMULATOR")) {
adRequestBuilder = adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
} else {
adRequestBuilder = adRequestBuilder.addTestDevice(testDeviceID);
}
}
AdRequest adRequest = adRequestBuilder.build();
mRewardedVideoAd.loadAd(adUnitID, adRequest);
}
}
});
}
#ReactMethod
public void showAd(final Callback callback) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run () {
if (mRewardedVideoAd.isLoaded()) {
showAdCallback = callback;
mRewardedVideoAd.show();
} else {
callback.invoke("Ad is not ready."); // TODO: make proper error
}
}
});
}
#ReactMethod
public void isReady(final Callback callback) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run () {
callback.invoke(mRewardedVideoAd.isLoaded());
}
});
}
}

Some versions (don't ask which one) of com.google.android.gms.ads.reward.RewardedVideoAdListener requires onRewardedVideoCompleted function. RNAdMobRewardedVideoAdModule class implements that class.
If you don't want to manage gms versions you can just create an empty function. I can't find any javascript call to that method anyway.
RNAdMobRewardedVideoAdModule.java
#Override
public void onRewardedVideoCompleted(){
}
If your version of react-native-admob has onRewardedVideoCompleted function and you are getting 'method doesnt override' error, then remove the #override annotation from method.
Kindly refer this link for the answer https://github.com/sbugert/react-native-admob/issues/316

Related

Incompatible types. Found: 'java.util.ArrayList<java.lang.Object>', required: 'java.util.ArrayList<UserLocation>'

So I am creating a route planner app in Android Studio and its giving me the error in the title of this question
Heres my code
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.destinationrouteplanner.R;
import com.example.destinationrouteplanner.adapters.UserRecyclerAdapter;
import com.example.destinationrouteplanner.models.MarkerCluster;
import com.example.destinationrouteplanner.models.User;
import com.example.destinationrouteplanner.util.MyClusterManagerRenderer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.maps.android.clustering.ClusterManager;
import java.util.ArrayList;
public class UserListFragment extends Fragment implements OnMapReadyCallback
{
private static final String TAG = "UserListFragment";
private RecyclerView mUserListRecyclerView;
private MapView mMapView;
private ArrayList<User> mUserList = new ArrayList<>();
//private UserRecyclerAdapter mUserRecyclerAdapter;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private UserRecyclerAdapter mUserRecyclerAdapter;
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<MarkerCluster> mClusterMarkers = new ArrayList<>();
public static UserListFragment newInstance() {
return new UserListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUserList = getArguments().getParcelableArrayList(getString(R.string.intent_user_list));
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
mUserListRecyclerView = view.findViewById(R.id.user_list_recycler_view);
mMapView = view.findViewById(R.id.user_list_map);
initUserListRecyclerView();
initGoogleMap(savedInstanceState);
return view;
}
private void initGoogleMap(Bundle savedInstanceState){
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private void initUserListRecyclerView() {
mUserRecyclerAdapter = new UserRecyclerAdapter(mUserList);
mUserListRecyclerView.setAdapter(mUserRecyclerAdapter);
mUserListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void addMapMarkers()
{
if (mGoogleMap !=null)
{
if(mClusterManager == null)
{
mClusterManager = new ClusterManager<MarkerCluster>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRenderer == null)
{
mClusterManagerRenderer = new MyClusterManagerRenderer(getActivity(), mGoogleMap, mClusterManager);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for (UserLocation userLocation: mUserLocations)
{
Log.d(TAG, "AddMapMarkers: location: " + userLocation.getGeo_point().toString());
try {
String snippet = "";
if (userLocation.getUser().getUser_id().equals(FirebaseAuth.getInstance().getUid()))
{
snippet = "This is you";
}else {
snippet = "Determine route to " + userLocation.getUser().getUsername() + "?";
}
int avatar = R.drawable.cwm_logo; //Set the default avatar
try {
avatar = Integer.parseInt(userLocation.getUser().getAvatar());
}catch (NumberFormatException e)
{
Log.d(TAG, "addMapMarkers: no avatar for: " + userLocation.getUser().getUsername() + ", setting default");
}
MarkerCluster newMarkerCluster = new MarkerCluster(new LatLng(userLocation.getGeo_point().getLatitude(), userLocation.getGeo_point().getLongitude(), userLocation.getUser().getUsername(), snippet, avatar, userLocation.getUser()));
mClusterManager.addItem(newMarkerCluster);
mClusterMarkers.add(newMarkerCluster);
}catch (NullPointerException e)
{
Log.e(TAG "addMapMarkers: NullPointerException: " + e.getMessage());
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView()
{
double bottomBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double rightBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
}
}
I tired using the answer to this question but not working
Required type:
ArrayList
Provided:
ArrayList
no instance(s) of type variable(s) exist so that UserLocation conforms to Object

apache flink avro FileSink is struck at in-progress state for long time

I have below avro schema User.avsc
{
"type": "record",
"namespace": "com.myorg",
"name": "User",
"fields": [
{
"name": "id",
"type": "long"
},
{
"name": "name",
"type": "string"
}
]
}
The below java User.java class is generated from above User.avsc using avro-maven-plugin.
package com.myorg;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.data.RecordBuilder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.SchemaStore;
import org.apache.avro.specific.AvroGenerated;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.specific.SpecificRecord;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.avro.specific.SpecificRecordBuilderBase;
#AvroGenerated
public class User extends SpecificRecordBase implements SpecificRecord {
private static final long serialVersionUID = 8699049231783654635L;
public static final Schema SCHEMA$ = (new Parser()).parse("{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"com.myorg\",\"fields\":[{\"name\":\"id\",\"type\":\"long\"},{\"name\":\"name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}}]}");
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<User> ENCODER;
private static final BinaryMessageDecoder<User> DECODER;
/** #deprecated */
#Deprecated
public long id;
/** #deprecated */
#Deprecated
public String name;
private static final DatumWriter<User> WRITER$;
private static final DatumReader<User> READER$;
public static Schema getClassSchema() {
return SCHEMA$;
}
public static BinaryMessageDecoder<User> getDecoder() {
return DECODER;
}
public static BinaryMessageDecoder<User> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver);
}
public ByteBuffer toByteBuffer() throws IOException {
return ENCODER.encode(this);
}
public static User fromByteBuffer(ByteBuffer b) throws IOException {
return (User)DECODER.decode(b);
}
public User() {
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Schema getSchema() {
return SCHEMA$;
}
public Object get(int field$) {
switch(field$) {
case 0:
return this.id;
case 1:
return this.name;
default:
throw new AvroRuntimeException("Bad index");
}
}
public void put(int field$, Object value$) {
switch(field$) {
case 0:
this.id = (Long)value$;
break;
case 1:
this.name = (String)value$;
break;
default:
throw new AvroRuntimeException("Bad index");
}
}
public Long getId() {
return this.id;
}
public void setId(Long value) {
this.id = value;
}
public String getName() {
return this.name;
}
public void setName(String value) {
this.name = value;
}
public void writeExternal(ObjectOutput out) throws IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
public void readExternal(ObjectInput in) throws IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
static {
ENCODER = new BinaryMessageEncoder(MODEL$, SCHEMA$);
DECODER = new BinaryMessageDecoder(MODEL$, SCHEMA$);
WRITER$ = MODEL$.createDatumWriter(SCHEMA$);
READER$ = MODEL$.createDatumReader(SCHEMA$);
}
}
I want to write an instance of User SpecificRecord into File using apache flink`s FileSink.
Below is the program that I wrote -
import org.apache.flink.connector.file.sink.FileSink;
import org.apache.flink.core.fs.Path;
import org.apache.flink.formats.avro.AvroWriters;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import com.myorg.User;
import org.apache.flink.streaming.api.functions.sink.filesystem.OutputFileConfig;
import org.apache.flink.streaming.api.functions.sink.filesystem.bucketassigners.DateTimeBucketAssigner;
import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.OnCheckpointRollingPolicy;
import java.util.Arrays;
public class AvroFileSinkApp {
private static final String OUTPUT_PATH = "./il/";
public static void main(String[] args) throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().enableCheckpointing(5000);
env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
env.setParallelism(4);
OutputFileConfig config = OutputFileConfig
.builder()
.withPartPrefix("il")
.withPartSuffix(".avro")
.build();
DataStream<User> source = env.fromCollection(Arrays.asList(getUser(), getUser(), getUser(), getUser(), getUser(), getUser()));
source.sinkTo(FileSink.forBulkFormat(new Path(OUTPUT_PATH), AvroWriters.forSpecificRecord(User.class)).withBucketCheckInterval(5000).withRollingPolicy(OnCheckpointRollingPolicy.build())
.withOutputFileConfig(config).withBucketAssigner(new DateTimeBucketAssigner<>("yyyy/MM/dd/HH")).build());
env.execute("FileSinkProgram");
Thread.sleep(300000);
}
public static User getUser() {
User u = new User();
u.setId(1L);
u.setName("raj");
return u;
}
}
I wrote this program using this and this as reference. The project is on github here.
When I run the program, the in progress files are getting created but not checkpointing and committing the temp files. I've added Thread.sleep(300000); but couldn't see the inprogress files to avro files.
I've awaited the main thread for an hour as well but no luck.
Any idea what is stopping in-progress files moving to finished state?
This problem is mainly because Source is a BOUNDED Source. The execution of the entire Flink Job is over before the Checkpoint has been executed.
You can refer to the following example to generate User records instead of fromCollection
/** Data-generating source function. */
public static final class Generator
implements SourceFunction<Tuple2<Integer, Integer>>, CheckpointedFunction {
private static final long serialVersionUID = -2819385275681175792L;
private final int numKeys;
private final int idlenessMs;
private final int recordsToEmit;
private volatile int numRecordsEmitted = 0;
private volatile boolean canceled = false;
private ListState<Integer> state = null;
Generator(final int numKeys, final int idlenessMs, final int durationSeconds) {
this.numKeys = numKeys;
this.idlenessMs = idlenessMs;
this.recordsToEmit = ((durationSeconds * 1000) / idlenessMs) * numKeys;
}
#Override
public void run(final SourceContext<Tuple2<Integer, Integer>> ctx) throws Exception {
while (numRecordsEmitted < recordsToEmit) {
synchronized (ctx.getCheckpointLock()) {
for (int i = 0; i < numKeys; i++) {
ctx.collect(Tuple2.of(i, numRecordsEmitted));
numRecordsEmitted++;
}
}
Thread.sleep(idlenessMs);
}
while (!canceled) {
Thread.sleep(50);
}
}
#Override
public void cancel() {
canceled = true;
}
#Override
public void initializeState(FunctionInitializationContext context) throws Exception {
state =
context.getOperatorStateStore()
.getListState(
new ListStateDescriptor<Integer>(
"state", IntSerializer.INSTANCE));
for (Integer i : state.get()) {
numRecordsEmitted += i;
}
}
#Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
state.clear();
state.add(numRecordsEmitted);
}
}
}

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

Compile error with two different fragmenttransaction types

I'm using AIDE on my phone, and trying to open a fragment from the navigation drawer in-app, but I get this error when I try to build the app:
An instance of type 'android.app.fragmenttransaction' cannot be assigned to a variable of type 'android.support.v4.app.fragmenttransaction'
Here is the code in the MainActivity.Java file:
package com.nickdgreen.net.act1;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v4.widget.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar.*;
import android.app.Activity.*;
import android.content.res.Configuration.*;
import android.os.Bundle.*;
import android.support.v4.app.ActionBarDrawerToggle.*;
import android.support.v4.app.Fragment.*;
import android.support.v4.app.FragmentActivity.*;
import android.support.v4.app.FragmentManager.*;
import android.support.v4.app.FragmentTransaction.*;
import android.support.v4.widget.DrawerLayout.*;
import android.view.Menu.*;
import android.view.MenuInflater.*;
import android.view.MenuItem.*;
import android.view.View.*;
import android.widget.AdapterView.*;
import android.widget.ArrayAdapter.*;
import android.widget.ListView.*;
public class MainActivity extends FragmentActivity
{
private ActionBarDrawerToggle drawerToggle;
final String fragments[] = {
"com.nickdgreen.net.act1.MainFragment",
"com.nickdgreen.net.act1.OneFragment",
"com.nickdgreen.net.act1.TwoFragment",
"com.nickdgreen.net.act1.ThreeFragment",
};
final String menuEntries[] = {
"Main", "One", "Two", "Three"
};
public MainActivity()
{
}
public void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
drawerToggle.onConfigurationChanged(configuration);
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030000);
ArrayAdapter arrayadapter = new ArrayAdapter(getActionBar().getThemedContext(), 0x1090003, menuEntries);
final DrawerLayout drawer = (DrawerLayout)findViewById(0x7f080000);
final ListView navList = (ListView)findViewById(0x7f080002);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawer, 0x7f020000, 0x7f050003, 0x7f050002) {
final MainActivity this$0;
public void onDrawerClosed(View view)
{
}
public void onDrawerOpened(View view)
{
}
{
this$0 = MainActivity.this;
}
};
drawer.setDrawerListener(drawerToggle);
navList.setAdapter(arrayadapter);
navList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
final MainActivity this$0;
final DrawerLayout val$drawer;
final ListView val$navList;
public void onItemClick(AdapterView adapterview, View view, int i, long l)
{ {
}
drawer.closeDrawer(navList);
}
{
}
});
FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(0x7f080001, Fragment.instantiate(this, fragments[0]));
fragmenttransaction.commit();
}
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(0x7f070000, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
if (drawerToggle.onOptionsItemSelected(menuitem))
{
return true;
} else
{
return super.onOptionsItemSelected(menuitem);
}
}
protected void onPostCreate(Bundle bundle)
{
super.onPostCreate(bundle);
drawerToggle.syncState();}
private class DrawerItemClickListener
implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{ selectItem(position); }
/** Swaps fragments in the main content view */
private void
selectItem(int position) {
//Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); // args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
Intent intent = new Intent(MainActivity.this, OneFragment.class); startActivity(intent); } }
public class
ProductListActivity extends MainActivity {
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate main_menu.xml
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.mainMenuExit:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override public void onClick(Bundle b) { super.onCreate(b); setContentView(R.layout.primary);}
public void
selectItem(int position) {
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new OneFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null); transaction.commit();
break;
case 1:
newFragment = new TwoFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
newFragment = new ThreeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 3:
newFragment = new FourFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
}
//DrawerList.setItemChecked(position, true);
CharSequence[] ListTitles = null;
setTitle(ListTitles[position]);
View DrawerList = null;
}
}
}
import android.support.v4.app.FragmentTransaction.*;
This line means that you are using FragmentTransaction; note that you are using the support lib's version, not the system's.
However, later in the code, you are assigning the support lib's FragmentTransaction to the native FragmentTransaction. They are incompatible and thus won't work. (Actually, it's what the error message itself is telling you.)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// ^^^ support lib's version ^^^ this code returns a native FragmentTransaction
You should instead get the support lib's fragment manager, which will return the support FragmentTransaction.

Resources