How do i get data from Rest API - api

Please, i am trying to access data from rest API,
From the Documentation ,to get the token, i have to make a post call ,then use the token received to access two other results:
for the token, they gave this from the documentation:
https://apps.qa.interswitchng.com/passport/oauth/token
with the following Query Params
grant_type string
Headers
Authorization string required
Set value to "Basic Base64(CLIENT_ID:SECRET_KEY)"
Content-Type application/x-www-form-urlencoded
string
My Codes
#SuppressLint("StaticFieldLeak")
class SendTokenReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("processing Token");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject2 = new JSONObject();
InputStream inputStream = null;
String result2 = "";
base64EncodedCredentials = "Basic" + Base64.encodeToString ((CLIENT_ID + ":" + SECRET) .getBytes (), Base64.NO_WRAP);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(" https://apps.qa.interswitchng.com/passport/oauth/token/");
//StringEntity stringEntity2 = new StringEntity(userPhoneNumber);
//httpPost.setEntity(stringEntity2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", base64EncodedCredentials);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse httpResponse1 = httpclient.execute(httpPost);
inputStream = httpResponse1.getEntity().getContent();
InputStreamReader inputStreamReader1 = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader1);
StringBuilder stringBuilder2 = new StringBuilder();
String bufferedStrChunk = null;
int data = inputStreamReader1.read();
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder2.append(bufferedStrChunk);
}
result2=stringBuilder2.toString();
return result2;
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String result2) {
super.onPostExecute(result2);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(true);
progressDialog.hide();
//String re=null;
/*try {
JSONObject jsonObject = new JSONObject(result2);
re = jsonObject.getString(result2);
} catch (JSONException e) {
e.printStackTrace();
}*/
txtInfo = findViewById(R.id.textViewMain);
txtInfo.setVisibility(View.VISIBLE);
txtInfo.setText(MessageFormat.format("Token is :{0}", result2));
}
}
with the below code in the oncreate
SendTokenReqAsyncTask myAsyncTasks = new SendTokenReqAsyncTask();
myAsyncTasks.execute();
i also used retrofit this way
#SuppressWarnings("deprecation")
public class MyRetrofitClient {
protected static MyRetrofitClient myRetrofitClient = null;
private static RetroApis myRetroApis;
private static TokenAPI tokenAPI;
private static Retrofit retrofit = null;
private String tokenFromServer;
String clientID,secret;
private byte[] data64;
String base64=null;
MyRetrofitClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
myRetroApis = retrofit.create(RetroApis.class);
}
public String encodeToBase64() {
clientID= CLIENT_ID1;
secret=SECRET1;
String text = clientID + ":" + secret;
data64 = new byte[0];
data64 = text.getBytes(StandardCharsets.UTF_8);
base64=android.util.Base64.encodeToString(data64, android.util.Base64.DEFAULT);
return base64;
}
static Retrofit getTokenClient() {
String type="application/x-www-form-urlencoded";
String base64String=MyRetrofitClient.myRetrofitClient.encodeToBase64();
RequestBody requestBody = RequestBody.create(MediaType.parse("Content-type"), type);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
logging.redactHeader("Authorization");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", MyRetrofitClient.getInstance().encodeToBase64()).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
return retrofit;
}
static Retrofit getTCreditReportClient(String tokenFromServer,String userPhoneNumber) {
String type="application/json";
RequestBody requestBody = RequestBody.create(MediaType.parse("Content-type"), type);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//logging.setLevel(HttpLoggingInterceptor.Level.BODY);
logging.redactHeader("Authorization");
logging.redactHeader("Content-type");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", tokenFromServer).build();
//Request request3 = chain.request().newBuilder().method("Content-type", requestBody).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
return retrofit;
}
static Retrofit getClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
//logging.setLevel(HttpLoggingInterceptor.Level.BODY);
logging.redactHeader("Authorization");
logging.redactHeader("Cookie");
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
public static synchronized MyRetrofitClient getInstance() {
if (myRetrofitClient == null) {
myRetrofitClient = new MyRetrofitClient();
}
return myRetrofitClient;
}
public RetroApis getMyApi() {
return myRetroApis;
}
public TokenAPI getMyTokenApi() {
return tokenAPI;
}
}
public interface TokenAPI {
String contentType= "application/json";
String authorization= "<>";
#FormUrlEncoded
#POST("client_credentials")
Call<OAuthToken> postCredentials(#Field("grant_type") String grantType);
//#FormUrlEncoded
#GET("creditScores")
Call<CreditScore> getCreditScore(#Query("client_credentials") String queryParam);
//#FormUrlEncoded
#GET("creditScores")
Call<List<CreditScoreHistory>> getCreditScoreHistory(#Query("client_credentials") String name);
#GET("/1.1/users/show.json")
Call<String> getUserDetails(#Query("screen_name") String name);
}
private void createInterSwitchTokenAPI33() {
editText = findViewById(R.id.editText);
base64EncodedCredentials = "Basic" + Base64.encodeToString ((CLIENT_ID + ":" + SECRET) .getBytes (), Base64.NO_WRAP);
//base64String=this.encodeToBase64();
String editTextInput = Objects.requireNonNull(editText.getText()).toString();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
logging.redactHeader("Authorization");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", base64EncodedCredentials).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
tokenAPI = retrofit.create(TokenAPI.class);
tokenAPI.getCreditScore(editTextInput).enqueue(creditScoreCallback);
}
public void onClick(View view) {
if (view.getId() == R.id.post) {
editText = findViewById(R.id.editText);
String editTextInput = editText.getText().toString();
if (!editTextInput.isEmpty())
createCreditScoreAPI(token);
createHistoryAPI(token);
tokenAPI.getCreditScore(editTextInput).enqueue(creditScoreCallback);
tokenAPI.getCreditScoreHistory(editTextInput).enqueue(creditScoreHistoryCallback);
} else {
Toast.makeText(this, "Please provide your BVN Phone Number", Toast.LENGTH_LONG).show();
}
}
private void createCreditScoreAPI(OAuthToken token) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Chain chain) throws IOException {
//Request originalRequest = chain.request();
Request request = chain.request().newBuilder().addHeader("Authorization", token.getAccessToken()).build();
return chain.proceed(request);
}
}).addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SCORE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
tokenAPI = retrofit.create(TokenAPI.class);
}
Callback<CreditScore> creditScoreCallback = new Callback<CreditScore>() {
#Override
public void onResponse(Call<CreditScore> call, Response<CreditScore> response) {
if (response.isSuccessful()) {
CreditScore creditScore = response.body();
if (creditScore != null) {
id = creditScore.getId();
msisdn = creditScore.getMsisdn();
score = creditScore.getScore();
dateCreated = creditScore.getDateCreated();
}
displayResponse += id + " Phone\n" + msisdn + " Score\n" + score + " dateCreated\n"+dateCreated;
txtCreditScore = findViewById(R.id.textCreditScore);
if (displayResponse == null) txtCreditScore.setText("no value");
else txtCreditScore.setText(displayResponse);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting Credit Score", Toast.LENGTH_LONG).show();
txtCreditScore.setText(MessageFormat.format("Error!{0}", response.message()));
Log.d("Credit Score Details", "Code: " + response.code() + "Message: " + response.message());
}
}
#Override
public void onFailure(Call<CreditScore> call, Throwable t) {
t.printStackTrace();
}
};
private void createHistoryAPI(OAuthToken token) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request = chain.request().newBuilder().addHeader("Authorization", token.getAccessToken()).build();
return chain.proceed(request);
}
}).addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HISTORY_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
tokenAPI = retrofit.create(TokenAPI.class);
}
Callback<List<CreditScoreHistory>> creditScoreHistoryCallback = new Callback<List<CreditScoreHistory>>() {
#Override
public void onResponse(Call<List<CreditScoreHistory>> call, Response<List<CreditScoreHistory>> response) {
if (response.isSuccessful()) {
recyclerView = findViewById(R.id.recyclerViewHistory);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting user details", Toast.LENGTH_LONG).show();
Log.d("History Callback", "Code: " + response.code() + "Message: " + response.message());
}
if (response.isSuccessful()) {
CreditScoreHistory creditScoreHistory = new CreditScoreHistory();
creditScoreList = response.body();
if (creditScoreList != null) {
for (int i = 0; i < creditScoreList.size(); i++) {
creditScoreList.add(creditScoreHistory);
count=creditScoreList.size();
}
if(creditScoreHistory !=null){
msisdn = creditScoreHistory.getMsisdn1();
score = creditScoreHistory.getScore1();
dateCreated = creditScoreHistory.getDateCreated1();
creditScoreList = creditScoreHistory.data;
}
}
displayResponse += count+" Phone\n" + msisdn + " Score\n" + score + " dateCreated\n"+dateCreated;
txtCreditHistory = findViewById(R.id.textCreditHistory);
creditHistoryAdapter = new CreditHistoryAdapter(MainActivity.this, creditScoreList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(creditHistoryAdapter);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setNestedScrollingEnabled(false);
if (displayResponse == null) txtCreditScore.setText("no value");
else txtCreditHistory.setText(displayResponse);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting Credit Score", Toast.LENGTH_LONG).show();
txtCreditHistory.setText(MessageFormat.format("Error!{0}", response.message()));
Log.d("Credit Score History", "Code: " + response.code() + "Message: " + response.message());
}
}
#Override
public void onFailure(Call<List<CreditScoreHistory>> call, Throwable t) {
t.printStackTrace();
}
};
buy could not get any result, please help

Use VSCode and ThunderClient extension https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client

Related

onMessageReceived method is not called, when app is not open

I have implemented FCM in my app, and I need to pass some data from Firebase service to Activity. I have implemented the following code, which works fine, when the app is in foreground(open). When the app is killed or in background, onMessageReceived method is not called, and the launcher activity is loaded while click on the push notification. Also, when the app is open, push message is blank. Kindly advise what I have done wrong. FYI, from backend, they are sending data payload, not notification.
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public FirebaseMessagingService() {
}
private static final String TAG = com.google.firebase.messaging.FirebaseMessagingService.class.getSimpleName();
public static String CHAT_PUSH_NOTIFICATION_INTENT = "chatPushNotificationIntent";
private PreferencesManager preferencesManager;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("push token >>", s);
String reliableIdentifier = FirebaseInstanceId.getInstance().getId();
FCMPreferencesManager pref = FCMPreferencesManager.getInstance(this);
if (pref != null) {
pref.setStringValue(FCMPreferencesManager.FCM_KEY_VALUE, s);
pref.setStringValue(FCMPreferencesManager.DEVICE_ID, reliableIdentifier);
}
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
preferencesManager = PreferencesManager.getInstance(this);
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
Log.e("onMessage received >>", "inside service");
Log.e("userId >>", userId + "");
if (userId > 0) {
Log.e("remote message >>", remoteMessage.getNotification().getBody() + "");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void classApprovedNotification(int jobId, String stage) {
if (!Utils.isAppIsInBackground(getApplicationContext())) {
Intent pushNotification = new Intent(Constants.PUSH_NOTIFICATION_INTENT);
pushNotification.putExtra("jobId", jobId);
pushNotification.putExtra("stage", stage);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
private void handleDataMessage(JSONObject json) {
try {
Log.e("total json >> ", json.toString());
JSONObject data = json.optJSONObject("data");
Log.e("data >> ", data.toString());
String title = data.optString("title");
String message = data.optString("message");
Log.e("title >>", title);
Log.e("message >>", message);
localNotification(data, title, message, false);
} catch (Exception e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
}
}
private void localNotification(JSONObject data, String title, String message, boolean isSendBird) {
int type = 0, groupId = 0, classId = 0, jobId = 0;
String stage = "";
int notificationId = (int) System.currentTimeMillis();
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
String className = "", fileName = "";
if (data != null) {
jobId = data.optInt("job_id");
stage = data.optString("stage", "");
}
Log.e("jobId in service >>", jobId + "");
Log.e("stage in service >>", stage);
Intent intent = new Intent(FirebaseMessagingService.this, VendorHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("jobId", jobId);
intent.putExtra("stage","stage");
int requestID = (int) System.currentTimeMillis();
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
requestID,
intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
String channelId = "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.fyxt_logo)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);*/
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
try {
PowerManager.WakeLock screenLock = null;
if ((getSystemService(POWER_SERVICE)) != null) {
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "OOTUSER:WAKE");
screenLock.acquire(10 * 60 * 1000L /*10 minutes*/);
screenLock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
classApprovedNotification(jobId, stage);
}
}
In my Activity, I have the following code.
private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
jobIdFromNotification = intent.getIntExtra("jobId", 0);
stageFromNotification = intent.getStringExtra("stage");
Log.e("jobIdFromNotification >>", jobIdFromNotification + "");
Log.e("stageFromNotification >>", stageFromNotification);
prefManager.setIntValue(PreferencesManager.JOB_ID_IN_PREF, jobIdFromNotification);
prefManager.setStringValue(PreferencesManager.JOB_STAGE_IN_PREF, stageFromNotification);
classApprovedViewUpdate();
}
};
private void classApprovedViewUpdate() {
if (jobIdFromNotification > 0) {
fragmentInteractionCallback = (BaseFragment.FragmentInteractionCallback) this;
Log.e("inside push receiver update ", "sfs");
if (stageFromNotification.trim().equalsIgnoreCase(Constants.STAGE_TICKET_APPROVAL)) {
sendActionToActivity(ACTION_CREATE_MAINTENANCE_REQUEST, currentTab, true, fragmentInteractionCallback);
}
}
}
Edit:
data payload:
{
"data": {
"type": 0,
"job_id": 123,
"stage": "STAGE_TICKET_APPROVAL",
}

Null pointer Exception when using volley

i am using volley to fetch data from database.I always get null pointer error. I don't know whats the error. it always executes onErrorResponse() (error.null) and shows this in my logcat
BasicNetwork.performRequest: Unexpected response code 301
here is my java method to fetch data from php file .
private void fetchChatThread() {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages=new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
Toast.makeText(Chat_Rooms.this, messages.getSender_id(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queue
addToRequestQueue(strReq);
}
here is my private that loads data from php to objects
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("id");
String commentText = commentObj.getString("message");
String createddate = commentObj.getString("date");
String commentuser_id = commentObj.getString("user_id_fk");
URL url;
Bitmap image, image1;
try {
url = new URL(Base_URL.BASE_URL_IMAGES + "user_profile_pictures" + commentuser_id + ".jpg");
image1 = BitmapFactory.decodeStream(url.openStream());
image = getResizedBitmap(image1, 50);
} catch (Exception e) {
image = null;
e.printStackTrace();
}
Users user;
user = new Users(commentuser_id, String_username.user_name, image);
Messages message = new Messages();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createddate);
message.setSender_id(commentuser_id);
message.setUser(user);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
#Override
protected void onPostExecute(ArrayList<Messages> messageArrayList) {
Collections.reverse(messageArrayList);
chatroom_adapter.notifyDataSetChanged();
if (chatroom_adapter.getItemCount() > 1) {
rec_chatBubble.getLayoutManager().smoothScrollToPosition(rec_chatBubble, null, chatroom_adapter.getItemCount() - 1);
}
}
}
TRY THIS
private void fetchChatThread(final String count) {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d("response error", response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages = new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
}
}) {
#Override
protected HashMap<String, String> getParams() {
HashMap<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
myparams.put("count", count);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queueok
addToRequestQueue(strReq);
}
AND THIS
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
messageArrayList.clear();
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String Id = commentObj.getString("id");
String Text = commentObj.getString("message");
String date = commentObj.getString("date");
String yuser_id = commentObj.getString("user_id");
Messages message = new Messages();
message.setId(Id);
message.setMessage(Text);
message.setCreatedAt(date);
message.setSender_id(yuser_id);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}

bad request:Volley 400

i want to connect to server by REST but i have Volley 400 error;
i tried almost everything i could find but nothing;
i'll be grateful if help me!
here is my codes:
private void volleyCall(String phone, String token) {
RequestQueue queue = Volley.newRequestQueue(this);
String URL = "http://1*4.***.**.1*1/login/register-phone";
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("phone", phone);
jsonParams.put("admin_token", token);
Log.i("log1", "Json:" + new JSONObject(jsonParams));
JsonObjectRequest postRequest = new
JsonObjectRequest(Request.Method.POST, URL,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("log2", "Json" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
Log.i("log3", "Error: " + error
+ "\nStatus Code " +
error.networkResponse.statusCode
+ "\nResponse Data " +
error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
Log.i("log4",headers.toString());
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(postRequest);
}
someone told me should remove this form header : (and i tried too, But same error!)
headers.put("Content-Type", "application/json; charset=utf-8");

How to implement a endless Recylerview?

How to implement a endless Recylerview?
This is Activity code:
public class ShopList extends AppCompatActivity {
RecyclerView rview;
RatingBar ratingbar;
private String `urlParameters`;
Recyclerviewshopl adapter;
String category;
JSONArray arr = null;
private Boolean Isinternetpresent = false;
ConnectionDetector cd;
String cat;
ProgressDialog dialog;
String lat,lon;
TextView nodata;
ImageView oops;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ratingbar = (RatingBar) findViewById(R.id.ratingbar);
List<Itemshopl> rowListItem = getAllItemList();
rview=(RecyclerView)findViewById(R.id.recycleshop);
nodata=(TextView)findViewById(R.id.nodata);
oops=(ImageView)findViewById(R.id.oops);
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
// LayerDrawable stars = (LayerDrawable) ratingbar.getProgressDrawable();
//stars.getDrawable(5).setColorFilter(Color.parseColor("#26ce61"),
// PorterDuff.Mode.SRC_ATOP);
// stars.getDrawable(1).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
/* RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, //width
ViewGroup.LayoutParams.WRAP_CONTENT);//height
rview.setLayoutParams(lp);*/
Bundle extras = getIntent().getExtras();
cat = extras.getString("category");
lat=extras.getString("lat");
lon=extras.getString("lon");
System.out.println("gr++"+cat);
cd = new ConnectionDetector(getApplicationContext());
Isinternetpresent = cd.isConnectingToInternet();
// onBackPressed();
if(Isinternetpresent)
{
shoplist tasku=new shoplist();
tasku.execute(new String[]{"http://abc**.com/****/getshoplist"});
}else{
// Toast.makeText(UserProfileActivity.this,"No Internet connection",Toast.LENGTH_SHORT).show();
showAlertDialog(ShopList.this, "No Internet Connection", "You don't have internet connection.", false);
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
// alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();
}
private List<Itemshopl> getAllItemList() {
List<Itemshopl> allItems = new ArrayList<Itemshopl>();
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
return allItems;
}
private class shoplist extends AsyncTask<String, String, List<Itemshopl>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(ShopList.this, "Loading", "Please Wait...", true);
dialog.show();
}
#Override
protected List<Itemshopl> doInBackground(String... urls) {
URL url;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
urlParameters = "&cat=" + URLEncoder.encode(cat, "UTF-8")+
"&lat="+ URLEncoder.encode(lat, "UTF-8")+
"&lon="+ URLEncoder.encode(lon, "UTF-8");
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
String finalJson = buffer.toString();
List<Itemshopl> itemshoplist = new ArrayList<>();
arr = new JSONArray(finalJson);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
/// String state = obj.getString("status");
Itemshopl model = new Itemshopl();
model.setName(obj.getString("shopname"));
model.setcat1(obj.getString("subcat1"));
model.setcat2(","+obj.getString("subcat2"));
model.setcat3(","+obj.getString("subcat3"));
model.setcat4(","+obj.getString("subcat4"));
model.setThumbnailUrl(obj.getString("logo"));
model.setid(obj.getString("id"));
model.setrating(obj.getString("rating"));
model.setreview(obj.getString("reviews")+"Reviews");
model.setcat(obj.getString("category"));
itemshoplist.add(model);
}
// cacheThis.writeObject(ShopList.this, "name", "hai");
return itemshoplist;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Itemshopl> detailsModels) {
super.onPostExecute(detailsModels);
dialog.dismiss();
if (detailsModels != null && detailsModels.size() > 0) {
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
rview=(RecyclerView)findViewById(R.id.recycleshop);
rview.setHasFixedSize(true);
adapter = new Recyclerviewshopl(getApplicationContext(), detailsModels);
rview.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rview.setAdapter(adapter);
}else
{
nodata.setVisibility(View.VISIBLE);
oops.setVisibility(View.VISIBLE);
}
}
}}
Adapter:
public class Recyclerviewshopl extends RecyclerView.Adapter<Recyclerviewshopl.ViewHolder> {
private List<Itemshopl> itemList;
private Context context;
public Recyclerviewshopl(Context context, List<Itemshopl> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(itemList.get(position).getName());
holder.icons.setImageResource(itemList.get(position).getPhoto());
holder.cat1.setText(itemList.get(position).getcat1());
holder.cat2.setText(itemList.get(position).getcat2());
holder.cat3.setText(itemList.get(position).getcat3());
holder.cat4.setText(itemList.get(position).getcat4());
holder.id.setText(itemList.get(position).getid());
// holder.review.setText(itemList.get(position).getreview());
holder.image.setText(itemList.get(position).getimg());
Glide.with(context).load(itemList.get(position).getThumbnailUrl()).into(holder.icons );
holder.phone.setText(itemList.get(position).getPhone());
holder.cat.setText(itemList.get(position).getcat());
if(itemList.get(position).getrating().equals(""))
{
itemList.get(position).getrating().equals("0");
} else {
//int value= Integer.parseInt(holder.rate.toString());
holder.rate.setRating(Float.parseFloat(itemList.get(position).getrating()));
}
holder.review.setText(itemList.get(position).getreview());
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int i)
{
View layoutview = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardshoplist, null);
ViewHolder sg = new ViewHolder(layoutview);
return sg;
}
#Override
public int getItemCount() {
return this.itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, cat1,cat2,cat3,cat4,review,image,id,phone,cat;
ImageView photo;
ImageView icons;
RatingBar rate;
public ViewHolder(final View itemView) {
super(itemView);
icons = (ImageView) itemView.findViewById(R.id.img1);
name = (TextView) itemView.findViewById(R.id.shopname);
cat=(TextView)itemView.findViewById(R.id.cat);
cat1=(TextView)itemView.findViewById(R.id.cat1);
cat2=(TextView)itemView.findViewById(R.id.cat2);
cat3=(TextView)itemView.findViewById(R.id.cat3);
cat4=(TextView)itemView.findViewById(R.id.cat4);
review=(TextView)itemView.findViewById(R.id.review);
image=(TextView)itemView.findViewById(R.id.img);
id=(TextView)itemView.findViewById(R.id.idvalue);
phone=(TextView)itemView.findViewById(R.id.phone);
rate=(RatingBar)itemView.findViewById(R.id.ratingbar);
itemView.setOnClickListener(new View.OnClickListener() {
int pos = getAdapterPosition();
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Intent in = new Intent(v.getContext(),ShopeProfile.class);
in.putExtra("id",id.getText().toString());
in.putExtra("shopname",name.getText().toString());
in.putExtra("phone",phone.getText().toString());
in.putExtra("rate",rate.getRating());
in.putExtra("cat",cat.getText().toString());
v.getContext().startActivity(in);
}
});
}
}
}

Worklight Security WorkLightAuthLoginModule

I'm using the WorkLightAuthenticator to validate User login.
But I need to return some parameters like userName, organozationID, among others. What would be the correct way to return this data?
I believe that would be the method createIdentity as exemple down. And to retrieve the data on the client?
/*Worklight Adapter*/
public class LoginModule implements WorkLightAuthLoginModule {
private String USERNAME;
private String PASSWORD;
public void init(Map<String, String> options) throws MissingConfigurationOptionException {
}
#SuppressWarnings("unchecked")
public boolean login(Map<String, Object> authenticationData) {
USERNAME = (String) authenticationData.get("username");
PASSWORD = (String) authenticationData.get("password");
InvocationResult invocationResult = callLoginAdapter(USERNAME, PASSWORD);
JSONObject jsonObject = invocationResult.toJSON();
HashMap<String, String> result = (HashMap<String, String>) jsonObject.get("result");
if(result != null){
return true;
} else {
HashMap<String, String> fault = (HashMap<String, String>) jsonObject.get("Fault");
String detail = fault.get("Detail");
throw new RuntimeException(detail);
}
}
public UserIdentity createIdentity(String loginModule) {
HashMap<String, Object> customAttributes = new HashMap<String, Object>();
customAttributes.put("AuthenticationDate", new Date());
customAttributes.put("userName", userExample);
customAttributes.put("organizationID", 1);
UserIdentity identity = new UserIdentity(loginModule, USERNAME, null, null, customAttributes, PASSWORD);
return identity;
}
public void logout() {
USERNAME = null;
PASSWORD = null;
}
public void abort() {
USERNAME = null;
PASSWORD = null;
}
#Override
public LoginModule clone() throws CloneNotSupportedException {
return (LoginModule) super.clone();
}
public InvocationResult callLoginAdapter(String user, String password){
DataAccessService service = WorklightBundles.getInstance().getDataAccessService();
String parameters = "['"+user+"','"+password+"']";
ProcedureQName procedureQName = new ProcedureQName("LoginAdapter", "getUserByLogin");
return service.invokeProcedure(procedureQName, parameters);
}
}
And AuthenticatorRealmChallengeHandler in client-side
/*AuthenticatorRealmChallengeHandler.js*/
var customAuthenticatorRealmChallengeHandler = WL.Client.createChallengeHandler("AuthenticatorRealm");
customAuthenticatorRealmChallengeHandler.isCustomResponse = function(response) {
console.log("**********************");
console.log(response.responseJSON);
if (!response || !response.responseJSON) {
return false;
}
if (response.responseJSON.authStatus)
return true;
else
return false;
};
customAuthenticatorRealmChallengeHandler.handleChallenge = function(response){
var authStatus = response.responseJSON.authStatus;
if (authStatus == "required"){
if (response.responseJSON.errorMessage){
currentPage.loginFail(response.responseJSON.errorMessage);
}
} else if (authStatus == "complete"){
currentPage.loadMaster();
customAuthenticatorRealmChallengeHandler.submitSuccess();
}
};
customAuthenticatorRealmChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = customAuthenticatorRealmChallengeHandler.isCustomResponse(response);
if (isLoginFormResponse){
customAuthenticatorRealmChallengeHandler.handleChallenge(response);
}
};
$('#loginButton').bind('click', function () {
var reqURL = '/auth_request_url';
var options = {};
options.parameters = {
username : $('#userTextField').val(),
password : $('#passwordTextField').val()
};
options.headers = {};
customAuthenticatorRealmChallengeHandler.submitLoginForm(reqURL, options, customAuthenticatorRealmChallengeHandler.submitLoginFormCallback);
});
var attributes = WL.Client.getUserInfo("AuthenticatorRealm", "attributes");