I am making classified marketplace android app. So, I have to show ads or post done by people on my home page, all is working and I am getting all my post on postman but not on my recycleview.
public class SearchFragment extends Fragment {
private static final String TAG = "SearchFragment";
private static final String BASE_URL = "http://35.188.133.114//elasticsearch/posts/post/";
private static final int NUM_GRID_COLUMNS = 2;
private static final int GRID_ITEM_MARGIN = 5;
//widgets
private ImageView mFilters;
private EditText mSearchText;
private FrameLayout mFrameLayout;
//vars
private String mElasticSearchPassword;
private String mPrefCity;
private String mPrefStateProv;
//private String mPrefCountry;
private String mPrefCollege;
private ArrayList<Post> mPosts;
private RecyclerView mRecyclerView;
private PostListAdapter mAdapter;
private ListView listView;
private String currentuser;
private String user;
private ImageView filter;
ArrayList<Card> list = new ArrayList<>();
FloatingActionButton fab;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
mFilters = (ImageView) view.findViewById(R.id.ic_search);
mSearchText = (EditText) view.findViewById(R.id.input_search);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mFrameLayout = (FrameLayout) view.findViewById(R.id.container);
filter = (ImageView) view.findViewById(R.id.filter);
currentuser = FirebaseAuth.getInstance().getUid();
filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),FiltersActivity.class);
startActivity(intent);
}
});
getElasticSearchPassword();
welcome();
init();
return view;
}
private void setupPostsList(){
RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
mRecyclerView.addItemDecoration(itemDecorator);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
mRecyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new PostListAdapter(getActivity(), mPosts);
mRecyclerView.setAdapter(mAdapter);
// CustomListAdapter adapter = new CustomListAdapter(getActivity(), R.layout.card_layout_main, list);
}
private void welcome() {
if (!currentuser.equals("")) {
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));
// String searchString = "*";
/* if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}*/
/* if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}*/
/* if(!mPrefCollege.equals("")){
searchString = searchString + " college:" + mPrefCollege;
}*/
/*if(!currentuser.equals("")){
searchString = searchString + " user_id:" + currentuser;
}*/
Call<HitsObject> call = searchAPI.search(headerMap, "AND", "*");
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try {
Log.d(TAG, "onResponse: server response: " + response.toString());
if (response.isSuccessful()) {
hitsList = response.body().getHits();
} else {
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for (int i = 0; i < hitsList.getPostIndex().size(); i++) {
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
} catch (NullPointerException e) {
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "onResponse: IOException: " + e.getMessage());
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
// return false;
}
private void init(){
mFilters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));
String searchString = "";
if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}
/* if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}*/
if(!mPrefCollege.equals("")){
searchString = searchString + " college:" + mPrefCollege;
}
/*if(!currentuser.equals("")){
searchString = searchString + " user_id:" + currentuser;
}*/
Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try{
Log.d(TAG, "onResponse: server response: " + response.toString());
if(response.isSuccessful()){
hitsList = response.body().getHits();
}else{
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for(int i = 0; i < hitsList.getPostIndex().size(); i++){
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
}catch (NullPointerException e){
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage() );
}
catch (IndexOutOfBoundsException e){
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage() );
}
catch (IOException e){
Log.e(TAG, "onResponse: IOException: " + e.getMessage() );
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage() );
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
// return false;
});
}
welcome() method is not called as i am not able to see any post but init() method is working and showing all the post when clicking on search button. And both methods are using same code, the only difference of the query that I am making, do not know why welcome() method is not showing any post.
Actually, Your method is called from onCreate() but your condition (!currentuser.equals("") is return false.
See the value of currentuser = FirebaseAuth.getInstance().getUid();
Only if you authenticate the user,then you will have this as not null else it will be empty or null.
This is issue with Firbase issue, Please check the firebase instance is configured and initialized properly in your application class. Then you should not able to get currentUser == "".
Firebase will return 401/410 error code incase of invalid user token / authentication with invalid user information.
Related
I use multiple retrofit in a service and my ui freeze,
So I try with asyncTask executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I try also with a Thread but I have the same problem.
I put only one retrofit function for example, the other function is similar.
I read this in other post : Retrofit already run in the background so it cannot block your UI. I assume it must be something else
I use the same function with socket and asyncTask and screen doesn't freeze.
So I don't find the problem
public class RestApiService extends Service {
private Retrofit retrofit;
private RetrofitInterface retrofitInterface;
private String BASE_URL = "http://******.com:8080";
****
#Override
public void onCreate() {
if (BuildConfig.DEBUG)
Log.v(Constants.TAG6,"onCreate");
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
retrofitInterface = retrofit.create(RetrofitInterface.class);
session = new SessionManager(getApplicationContext());
postemanager = new PosteManager(getApplicationContext());
contactmanager = new ContactManager(getApplicationContext());
commentmanager = new CommentManager(getApplicationContext());
groupeManager = new GroupeManager(getApplicationContext());
notifHelp = new NotificationHelper(getApplicationContext());
tinydb = new TinyDB(YuYuApplication.getAppContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*GetLists getLists = new GetLists();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
getLists.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
getLists.execute(); */
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
/* new Thread(new Runnable() {
#Override
public void run() {
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
}
}).start(); */
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
class GetLists extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
return null;
}
}
public void getListPosts(){
Call<ArrayList<PosteFromServer>> call = retrofitInterface.getListPosts(session.getPhoneSession());
call.enqueue(new Callback<ArrayList<PosteFromServer>>() {
#Override
public void onResponse(Call<ArrayList<PosteFromServer>> call, Response<ArrayList<PosteFromServer>> response) {
ArrayList<PosteFromServer> myDataList = response.body();
Poste poste = new Poste();
final JSONArray callbackList = new JSONArray();
for (int i = 0; i < myDataList.size(); i++) {
if (postemanager.CheckIsIdPostEmetAlreadyInDBorNot(myDataList.get(i).getIdPostEmet()) == false) {
int nbPostNotRead = session.getNumbrePostNotRead();
nbPostNotRead++;
int nbCmtNotRead = session.getNumbreCommentNotRead();
session.createNumbrePostNotRead(nbPostNotRead);
//Notification counter
try {
// Badges.removeBadge(getApplicationContext());
// Alternative way
Badges.setBadge(getApplicationContext(), nbPostNotRead + nbCmtNotRead);
if (BuildConfig.DEBUG) {
int Nb = nbPostNotRead + nbCmtNotRead;
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "Badges Poste ; CMT " + nbPostNotRead + " " + nbCmtNotRead);
Log.v(Constants.TAG6, "Badges Poste + CMT " + Nb);
}
}
} catch (BadgesNotSupportedException badgesNotSupportedException) {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "getListPost BADGES MSG:" + badgesNotSupportedException.getMessage());
}
}
final JSONObject callback = new JSONObject();
try {
callback.put("app_id", myDataList.get(i).getApp_id());
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "getListPost app_id " + myDataList.get(i).getApp_id());
}
/* Contact cdest = new Contact();
ArrayList<Contact> cdestList = new ArrayList<>();
cdest.setPhone(session.getPhoneSession());
cdestList.add(cdest);
sendCallback.put("destPhone",cdestList); */
callback.put("destPhone", session.getPhoneSession());
callback.put("idPostEmet", myDataList.get(i).getIdPostEmet());
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "emmetteur" + myDataList.get(i).getEmetr_phone());
}
callback.put("emetr_phone", myDataList.get(i).getEmetr_phone());
callback.put("typeOfCallback", "callBackDevice");
} catch (JSONException e) {
e.printStackTrace();
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "called emit message");
}
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "Handling friendcall");
}
//Catching IdMessages
boolean checkGroupNotification = false;
try {
if (BuildConfig.DEBUG)
Log.d(Constants.TAG6, " GROUPES " + myDataList.get(i).getGroups());
groups = Utils.convertStringToDummyObject(myDataList.get(i).getGroups().toString());
//TODO idGroup exit in TinyDB for notification purpose
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArray = tinydb.getListString("ids");
for (int j = 0; j < mIdArray.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArray.get(k).equals(groups.get(k).getId())) {
checkGroupNotification = true;
break;
}
} catch (Exception ex) {
groups = null;
}
//Catching IdMessages
boolean checkGroupSon = false;
try {
groups = Utils.convertStringToDummyObject(myDataList.get(i).getGroups().toString());
//TODO idGroup exit in TinyDB for notification purpose
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArraySon = tinydb.getListString("idGroupsSon");
for (int j = 0; j < mIdArraySon.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArraySon.get(j).equals(groups.get(k).getId())) {
checkGroupSon = true;
break;
}
} catch (Exception ex) {
groups = null;
}
try {
if (myDataList.get(i).getSansPhoto() != null) {
final String emeteur_phone = myDataList.get(i).getEmetr_phone();
String emeteur_name = null;
if (myDataList.get(i).getEmetr_name() != null) {
emeteur_name = myDataList.get(i).getEmetr_name();
}
message = myDataList.get(i).getText();
destFromServer = myDataList.get(i).getDestinataires();
idPostEmet = myDataList.get(i).getIdPostEmet();
counterDest = Integer.toString(myDataList.get(i).getCounterDest());
typePoste = myDataList.get(i).getTypePoste();
//TODO idGroup exit in TinyDB
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArray = tinydb.getListString("ids");
if (groups != null) {
for (int j = 0; j < mIdArray.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArray.get(j).equals(groups.get(k).getId())) {
checkGroupNotification = true;
break;
}
}
//Debut Test
// Session class instance
// session = new SessionManager(getApplicato());
try {
EmeteurPoste = contactmanager.getContactsByNbrPhone(Utils.AddCaractDest(emeteur_phone));
if (EmeteurPoste.getName().equals(EmeteurPoste.getPhone()) || EmeteurPoste.getName().equals("null") && emeteur_name != null) { // || !c.getName().equals(name) a utiliser pour changer le nom a mettre en place qd l emmet sera un contact et pas un string
EmeteurPoste.setName(emeteur_name);
contactmanager.updateContactName(EmeteurPoste);
}
} catch (Exception ex) {
Log.v(Constants.TAG6, ex.getMessage());
}
if (EmeteurPoste == null) {
EmeteurPoste = new Contact();
if (emeteur_name == null)
EmeteurPoste.setName(Utils.AddCaractDest(emeteur_phone));
else
EmeteurPoste.setName(emeteur_name);
EmeteurPoste.setPhone(Utils.AddCaractDest(emeteur_phone));
EmeteurPoste.setStatus(Constants.STATUS_INSCRIS_NON_ENRG_REPERTOIRE);
contactmanager.openForWrite();
EmeteurPoste.setId((int) contactmanager.createContact(EmeteurPoste));
contactmanager.close();
}
if (EmeteurPoste != null) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 3 Contact EmetPost Name" + EmeteurPoste.getName() + "EmetPost Phone" + EmeteurPoste.getPhone());
}
emeteur = EmeteurPoste.getName();
} else {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost EmetPost null");
}
emeteur = emeteur_phone;
}
// destinataires = Utils.convertStringToArray();
destinataires = contactmanager.updateAllNameAndIdDestinataireForPost(destFromServer);
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost destinataires " + destinataires);
}
//TEST L'icône sera une petite loupe
//TEST int icon = R.drawable.ic_launcher;
// Le premier titre affiché
//TEST CharSequence tickerText = "Titre de la notification";
// Daté de maintenant
long when = System.currentTimeMillis();
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost notification manager");
}
//Loading webView
/*if(Utils.linkScannerWebView(msg)!=null)
typePoste = String.valueOf(PosteAdapter.TYPE_WEB_VIEW);*/
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 4 Before getLinkPreview idPostEmet " + idPostEmet + " myDataList.get(i).getIdPostEmet() " + myDataList.get(i).getIdPostEmet() + " message " + message + " data.getString(text).toString() " + myDataList.get(i).getText());
}
if (typePoste.equals(String.valueOf(Constants.TYPE_WEB_VIEW)) || typePoste.equals(String.valueOf(Constants.TYPE_WEB_VIEW_Retry))) {
final boolean checkGrNotif = checkGroupNotification;
final boolean checkGrSon = checkGroupSon;
LinkUtil.getInstance().getLinkPreview(getBaseContext(), Utils.linkScannerWebView(message), message, EmeteurPoste, emeteur_phone, idPostEmet, destinataires, counterDest, groups, new GetLinkPreviewListener() {
#Override
public void onSuccess(final LinkPreview linkPreview) {
String img = null;
Gson gson = new Gson();
File imgFile = linkPreview.getImageFile();
try {
if (imgFile != null && imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
if (myBitmap != null) {
img = Utils.SaveImage(getBaseContext(), myBitmap, true);
}
}
} catch (Exception ex) {
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 5 after save image and description and BEFORE addLink idPostEmet " + idPostEmet + " Message " + gson.toJson(linkPreview));
}
// postemessage = addMessage(EmeteurPoste, emeteur_phone, linkPreview.getTextPoste(), destinataires, linkPreview.getIdPostEmet(), counterDest, String.valueOf(Constants.TYPE_WEB_VIEW), img, groups, checkGrNotif, checkGrSon); //gson.toJson(linkPreview)
postemessage = addLinkWebView(linkPreview, String.valueOf(Constants.TYPE_WEB_VIEW), img, checkGrNotif, checkGrSon); //gson.toJson(linkPreview)
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " 10 after save image and description and AFTER addMessage idPostEmet " + idPostEmet);
}
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 11 called emit POST WEB VIEW link: " + gson.toJson(linkPreview));
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailed(Exception var1) {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost 5 after save image and description and BEFORE addMessage idPostEmet " + idPostEmet + " Message " + message);
}
postemessage = addMessage(EmeteurPoste, emeteur_phone, message, destinataires, idPostEmet, counterDest, "0", null, groups, checkGrNotif, checkGrSon);
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost 10 after save image and description and BEFORE addMessage idPostEmet " + idPostEmet + " Message " + message);
}
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 11 called emit POST WEB VIEW FAILED message: " + message);
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
postemessage = addMessage(EmeteurPoste, emeteur_phone, message, destinataires, idPostEmet, counterDest, "0", null, groups, checkGroupNotification, checkGroupSon);
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "getListPost called emit POST MESSAGE message: " + message);
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Fin Test
}
} catch (Exception e) {
Log.d(Constants.TAG6, "getListPost friend call object cannot be parsed");
e.printStackTrace();
}
} else {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPostidPostEmet ALREADY EXIST");
}
//Sending callback if poste is already exist
JSONObject callback = new JSONObject();
try {
callback.put("app_id", myDataList.get(i).getApp_id());
/* Contact cdest = new Contact();
ArrayList<Contact> cdestList = new ArrayList<>();
cdest.setPhone(session.getPhoneSession());
cdestList.add(cdest);
callback.put("destPhone",cdestList); */
callback.put("destPhone", session.getPhoneSession());
callback.put("idPostEmet", myDataList.get(i).getIdPostEmet());
callback.put("emetr_phone", myDataList.get(i).getEmetr_phone());
callback.put("typeOfCallback", "callBackDevice");
} catch (JSONException e) {
e.printStackTrace();
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost post message called emit");
}
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "getListPost send callBackDevice callback " + callback.toString());
}
// socket.emit("callBackDevice",callback);
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost RECEIVE LISTPOSTS i " + i + " callback " + callback);
}
callbackList.put(callback);
}
/* } catch (JSONException e) {
e.printStackTrace();
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6,"3 try catch exception "+e.toString()+" myDataList.get(i).toString() "+myDataList.get(i).toString());
}
} */
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost END RECEIVE LISTPOSTS callbackList " + callbackList);
}
if(callbackList.length() > 0){
sendCallbackList(callbackList);
}else{
getListPostISentFromWeb();
}
}
#Override
public void onFailure(Call<ArrayList<PosteFromServer>> call, Throwable t) {
if (BuildConfig.DEBUG)
Log.v(Constants.TAG6, " getListPost onFailure " + t.getMessage());
}
});
}
I'm trying to use RETROFIT to get an inform about COVID-19 data. And I want to show the latest data, so I tried
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.setText(content1);
textViewResult2.setText(content2);
textViewResult3.setText(content3);
textViewResult4.setText(content4);
textViewResult5.setText(content5);
But it is not working.it didn't show any data. how can i show the latest data in JSON file with using retrofit? below is my whole code of main activity
1.MainActivity
public class COVIDActivity extends AppCompatActivity {
private TextView textViewResult;
private TextView textViewResult2;
private TextView textViewResult3;
private TextView textViewResult4;
private TextView textViewResult5;
private static final String TAG = "COVIDActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.covid_menu);
//How go_back_button works
ImageButton bo_back_Button = (ImageButton) findViewById(R.id.covid_to_main);
bo_back_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_main_covid = new Intent(COVIDActivity.this,MainActivity.class);
startActivity(move_main_covid);
}
});
textViewResult = findViewById(R.id.text_view_result_positive);
textViewResult2 = findViewById(R.id.text_view_result_death);
textViewResult3 = findViewById(R.id.text_view_result_positive_increase);
textViewResult4 = findViewById(R.id.text_view_result_death_increase);
textViewResult5 = findViewById(R.id.today_date);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://covidtracking.com/api/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<COVID_Post_Data>> call = jsonPlaceHolderApi.get_covid_post();
call.enqueue(new Callback<List<COVID_Post_Data>>() {
#Override
public void onResponse(Call<List<COVID_Post_Data>> call, Response<List<COVID_Post_Data>> response) {
if (!response.isSuccessful()) {
textViewResult.setText(("Code: " + response.code()));
return;
}
List<COVID_Post_Data> posts = response.body();
//Give message if fail, TAG is COVIDActivity so that it will show log in this activity
if(posts == null) {
Log.w(TAG,"Did not receive any valid response body");
return;
}
for (COVID_Post_Data covid_post_data : posts) {
String content1,content2,content3,content4,content5 = "";
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.append(content1);
textViewResult2.append(content2);
textViewResult3.append(content3);
textViewResult4.append(content4);
textViewResult5.append(content5);
}
}
2.get JSON file
public interface JsonPlaceHolderApi {
//get data from json about US infection
#GET("us/daily.json")
Call<List<COVID_Post_Data>> get_covid_post();
//get data from json about states infection
#GET("states/daily.json")
Call<List<COVID_Post_Data>> get_covid_post_state();
}
3.getter function
public class COVID_Post_Data {
private String dataChecked;
private int positiveIncrease;
private int negativeIncrease;
private int deathIncrease;
private String state;
private int positive;
private int death;
private int date;
//if the variable is matched with name in json file no need to put #SerializedName here
public String getDataChecked() {
return dataChecked;
}
public int getPositiveIncrease() {
return positiveIncrease;
}
public int getNegativeIncrease() {
return negativeIncrease;
}
public int getDeathIncrease() {
return deathIncrease;
}
public String getState() {
return state;
}
public int getPositive() {
return positive;
}
public int getDeath() { return death; }
public int getDate() {
return date;
}
}
Trying to retrieve data and place it into RecyclerView. But i always end up getting a null adapter error. My List Adapter is not being recognized.
I have initialized adapter and recyclerview in OnCreate(), OnViewCreated() nothing changed except app-crash.
Can you guys shed any light please?
My List Adapter:
public class PostListAdapter extends RecyclerView.Adapter<PostListAdapter.ViewHolder>{
private static final String TAG = "PostListAdapter";
private static final int NUM_GRID_COLUMNS = 3;
private ArrayList<Post> mPosts;
private Context mContext;
public class ViewHolder extends RecyclerView.ViewHolder{
SquareImageView mPostImage;
public ViewHolder(View itemView) {
super(itemView);
mPostImage = (SquareImageView) itemView.findViewById(R.id.post_image);
int gridWidth = mContext.getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
mPostImage.setMaxHeight(imageWidth);
mPostImage.setMaxWidth(imageWidth);
}
}
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(mContext);
public PostListAdapter(Context context, ArrayList<Post> posts) {
mPosts = posts;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.layout_view_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mContext));
UniversalImageLoader.setImage(mPosts.get(position).getImage(), holder.mPostImage);
//GlideApp.with(mContext).load(mPosts.get(position)).into(holder.mPostImage);
//imageLoader.displayImage(mPosts.get(position).getImage(), holder.mPostImage);
final int pos = position;
holder.mPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: selected a post");
//TODO
//view the post in more detail
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
}
My Fragment (where i initiliaze adapter and recyclerview):
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
mFilters = view.findViewById(R.id.ic_search);
mSearchText = view.findViewById(R.id.input_search);
mRecyclerView = view.findViewById(R.id.recyclerView);
mFrameLayout = view.findViewById(R.id.container);
getElasticSearchPassword();
init();
return view;
}
private void setupPostsList(){
RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
mRecyclerView.addItemDecoration(itemDecorator);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
mRecyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new PostListAdapter(getActivity(), mPosts);
mRecyclerView.setAdapter(mAdapter);
}
private void init(){
mFilters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to filters activity.");
Intent intent = new Intent(getActivity(), FiltersActivity.class);
startActivity(intent);
}
});
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
||actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
|| event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("", mElasticSearchPassword));
String searchString = "";
if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}
if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}
if(!mPrefCountry.equals("")){
searchString = searchString + " country:" + mPrefCountry;
}
Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try{
Log.d(TAG, "onResponse: server response: " + response.toString());
if(response.isSuccessful()){
hitsList = response.body().getHits();
}else{
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for(int i = 0; i < hitsList.getPostIndex().size(); i++){
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
}catch (NullPointerException e){
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage() );
}
catch (IndexOutOfBoundsException e){
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage() );
}
catch (IOException e){
Log.e(TAG, "onResponse: IOException: " + e.getMessage() );
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage() );
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
}
public void viewPost(String postId){
ViewPostFragment fragment = new ViewPostFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), postId);
fragment.setArguments(args);
transaction.replace(R.id.container, fragment, getString(R.string.fragment_view_post));
transaction.addToBackStack(getString(R.string.fragment_view_post));
transaction.commit();
mFrameLayout.setVisibility(View.VISIBLE);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
}
#Override
public void onResume() {
super.onResume();
getFilters();
}
private void getElasticSearchPassword(){
Log.d(TAG, "getElasticSearchPassword: retrieving elasticsearch password.");
Query query = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.node_elasticsearch))
.orderByValue();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
mElasticSearchPassword = singleSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getFilters(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mPrefCity = preferences.getString(getString(R.string.preferences_city), "");
mPrefStateProv = preferences.getString(getString(R.string.preferences_state_province), "");
mPrefCountry = preferences.getString(getString(R.string.preferences_country), "");
Log.d(TAG, "getFilters: got filters: \ncity: " + mPrefCity + "\nState/Prov: " + mPrefStateProv
+ "\nCountry: " + mPrefCountry);
}
}
It seems like you never call the method setupPostsList(). You should move your code in Fragment from onCreateView() to onViewCreated() - that's the mehod where all views in fragment are created and you can use findViewById(). First find all view by ids and then call method setupPostsList() to set up the recycle view.
I created a class for working with subscriptions in the store.
In the beginning I receive from the server the list of subscriptions with the prices
The code is working and on most devices there is no problem.
But some users do not recive prices. It's like there's no response from the server. I've studied examples of implementation in Google documentation, but I can not understand where I can have problems in the code.
Part of my code:
public class BillingActivity extends AppCompatActivity {
RelativeLayout imageLayout;
View payButton;
// WebView payWebView;
// TextView useCodeButton;
ProgressBar progress1;
ProgressBar progress2;
ProgressBar progress3;
IInAppBillingService inAppBillingService;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_billing_subscription);
price_1monthTextView = (TextView) findViewById(R.id.price_1monthTextView);
relative_1month = (RelativeLayout) findViewById(R.id.relative_1month);
relative_1month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (MainActivity.myAccount == null) return;
if (MainActivity.myAccount.getUniqid() == null) return;
if (subscription1m != null) {
try {
Log.d("my", "purchase..." + subscription1m.storeName);
purchaseProduct(subscription1m);
} catch (Exception e) {
e.printStackTrace();
Log.d("my", "purchase error = " + e.toString());
}
}
}
});
progress1 = (ProgressBar) findViewById(R.id.progress1);
startGoogleBilling();
}
private void startGoogleBilling() {
if (serviceConnection != null) {
unbindService(serviceConnection);
}
progress1.setVisibility(View.VISIBLE);
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
inAppBillingService = IInAppBillingService.Stub.asInterface(service);
getSubscribtionsList();
}
#Override
public void onServiceDisconnected(ComponentName name) {
inAppBillingService = null;
}
};
Intent serviceIntent =
new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private static final int PR_CNT = 3;
List<InAppProduct> subscriptions = null;
InAppProduct subscription1m = null;
InAppProduct subscription3m = null;
InAppProduct subscription1y = null;
String[] productIds = {"eq.subscription.1m", "eq.subscription.3m.2", "eq.subscription.1y"};
private void getSubscribtionsList() {
mSwipeRefreshLayout.setRefreshing(false);
progress1.setVisibility(View.GONE);
try {
subscriptions =
getInAppPurchases("subs", productIds[0], productIds[1], productIds[2]);
if (subscriptions.size() == PR_CNT) {
for (InAppProduct inAppProduct : subscriptions) {
String productId = inAppProduct.productId;
Log.d("my", "productId= " + productId);
if (productId.contains(productIds[0])) subscription1m = inAppProduct;
if (productId.contains(productIds[1])) subscription3m = inAppProduct;
if (productId.contains(productIds[2])) subscription1y = inAppProduct;
}
Log.d("my", "1m= " + subscription1m.storeName + " pr=" + subscription1m.price + "\\n\\r " +
"3m= " + subscription3m.storeName + " pr=" + subscription3m.price + "\\n\\r " +
"1y= " + subscription1y.storeName + " pr=" + subscription1y.price + "\\n\\r ");
///----------------------!!!!
// purchaseProduct(inAppProduct);
}
updatePrices();
} catch (Exception e) {
Log.d("my", "exc = " + e.toString());
if (e.toString().contains("Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getSkuDetails")) {
if (attempt < 4) {
//getSubscribtionsList();
// startGoogleBilling();
} else {
}
}
// Toast.makeText(this, "Google inApp connection error", Toast.LENGTH_SHORT).show();
// refreshButton.setVisibility(View.VISIBLE);
startGoogleBilling();
}
}
private int attempt = 0;
#Override
public void onDestroy() {
super.onDestroy();
if (serviceConnection != null) {
unbindService(serviceConnection);
}
}
class InAppProduct {
public String productId;
public String storeName;
public String storeDescription;
public String price;
public boolean isSubscription;
public int priceAmountMicros;
public String currencyIsoCode;
public String getSku() {
return productId;
}
String getType() {
return isSubscription ? "subs" : "inapp";
}
}
List<InAppProduct> getInAppPurchases(String type, String... productIds) throws Exception {
ArrayList<String> skuList = new ArrayList<>(Arrays.asList(productIds));
Bundle query = new Bundle();
query.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = inAppBillingService.getSkuDetails(
3, getPackageName(), type, query);
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
List<InAppProduct> result = new ArrayList<>();
for (String responseItem : responseList) {
JSONObject jsonObject = new JSONObject(responseItem);
InAppProduct product = new InAppProduct();
// "com.example.myapp_testing_inapp1"
product.productId = jsonObject.getString("productId");
// Покупка
product.storeName = jsonObject.getString("title");
// Детали покупки
product.storeDescription = jsonObject.getString("description");
// "0.99USD"
product.price = jsonObject.getString("price");
// "true/false"
product.isSubscription = jsonObject.getString("type").equals("subs");
// "990000" = цена x 1000000
product.priceAmountMicros =
Integer.parseInt(jsonObject.getString("price_amount_micros"));
// USD
product.currencyIsoCode = jsonObject.getString("price_currency_code");
result.add(product);
}
return result;
}
private void updatePrices() {
if (subscriptions.size() == PR_CNT) {
price_1monthTextView.setText(subscription1m.price);
price_3monthTextView.setText(subscription3m.price);
price_1yearTextView.setText(subscription1y.price);
}
}
}
my problem was the bit depth of the X variable priceAmountMicros
The price from playmarket is multiplied by a 1000000 , and Kazakh tenge has exchange rate = 1 USD= 331,3 KZT.
And if i have price 18 000 KTZ and * 1000 000.
For price variable I must use long type
I want to get message in my chat activity without press back button in Quickblox instance chat
userData = new QBUser();
userData.setEmail(uNameStr);
userData.setPassword(uPwdStr);
userData.setId(user.getId());
You have to set listeners after the privateChat.sendMessage(chatMessage); so when you get success in listeners call notifydatasetchange method of the adapter.
private void sendMessage() {
// privateChatManager = chatService.getPrivateChatManager();
Log.d("PRIVATE", ">>>>> " + privateChatManager);
Log.d("INST", ">>>>> " + QBChatService.getInstance());
Log.d("CHAT ", "" + chatService);
Log.d("PRI", ">>>>> " + QBChatService.getInstance().getPrivateChatManager());
//login to chat firstly
if (messageEdt.length() > 0) {
privateChatMessageListener = new QBMessageListener<QBPrivateChat>() {
#Override
public void processMessage(QBPrivateChat privateChat, final QBChatMessage chatMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("chatMessage", "" + chatMessage);
chatListAdapter.notifyDataSetChanged();
}
#Override
public void processError(QBPrivateChat privateChat, QBChatException error, QBChatMessage originMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("QBChatMessage", "" + originMessage);
Log.e("error", "" + error);
}
};
privateChatManagerListener = new QBPrivateChatManagerListener() {
#Override
public void chatCreated(final QBPrivateChat privateChat, final boolean createdLocally) {
if (!createdLocally) {
privateChat.addMessageListener(privateChatMessageListener);
}
}
};
ChattingFragment.chatService.getPrivateChatManager().addPrivateChatManagerListener(privateChatManagerListener);
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(messageEdt.getText().toString());
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
chatMessage.setProperty("notification_type", "1");
chatMessage.setSenderId(Integer.parseInt(Util.ReadSharePrefrence(getApplicationContext(), Constant.SHRED_PR.KEY_QB_USERID)));
chatMessage.setRecipientId(opponentId);
chatMessage.setMarkable(true);
privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBPrivateChat privateChat = privateChatManager.getChat(opponentId);
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentId, privateChatMessageListener);
}
// send message
privateChat.sendMessage(chatMessage);
privateChat.addMessageSentListener(privateChatMessageSentListener);
privateChat.addMessageListener(privateChatMessageListener);
} catch (SmackException.NotConnectedException e) {
Toast.makeText(PrivateChat.this, "Exception " + e, Toast.LENGTH_SHORT).show();
}
}
}
private QBMessageSentListener<QBPrivateChat> privateChatMessageSentListener = new QBMessageSentListener<QBPrivateChat>() {
#Override
public void processMessageSent(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "MSG " + qbChatMessage);
hashmap = new HashMap<String, String>();
hashmap.put("id", "" + qbChatMessage.getId());
if (qbChatMessage.getBody() != null) {
hashmap.put("msg", "" + qbChatMessage.getBody());
} else {
hashmap.put("msg", "");
}
hashmap.put("recipient_id", "" + opponentId);
hashmap.put("sender_id", "" + user_id);
Collection<QBAttachment> collection = qbChatMessage.getAttachments();
if (collection != null && collection.size() > 0) {
for (QBAttachment attachment : collection) {
String imageid = attachment.getId();
String RecivedUrl = attachment.getUrl();
hashmap.put("url", "" + RecivedUrl);
}
//Here is the AsyncTask where I am trying to download image
//
}
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
hashmap.put("updated_at", "" + currentDateTimeString);
chatArraylist.add(hashmap);
Toast.makeText(getApplicationContext(), "Message Sent Successfully", Toast.LENGTH_SHORT).show();
messageEdt.setText("");
chatListAdapter = new PrivateChatMsgListAdapter(getApplicationContext(), chatArraylist);
lvChatDetails.setAdapter(chatListAdapter);
lvChatDetails.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lvChatDetails.setStackFromBottom(true);
chatListAdapter.notifyDataSetChanged();
scrollMyListViewToBottom();
}
#Override
public void processMessageFailed(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "ERR " + qbChatMessage);
}
};