array list adds the elements then remove them alone - java

I am using arrayList of object in my app. I made a methods to check if an element exists in the list or no. The element is coming from firebase database. After adding these methods I found that the elements appears in the recycler view then disappears again. I debugged my code and I found that the elements are added to the list then removed again, but I can't understand why this behavior happens.
These are the methods I made :
boolean existsInCompletedChallengesList(String currentChallengeId) {
for (Challenge c : completedChallengesList) {
Log.v("completedChallengesList", "id of challenge in completedChallengesList : " + c.getId() + " current challengeId " + currentChallengeId);
if (c.getId().equals(currentChallengeId)) {
return true;
}
}
return false;
}
boolean existsInUncompletedChallengesList(String currentChallengeId) {
no++;
Log.v("check", "number of times is : " + no);
for (Challenge c : uncompletedChallengesList) {
Log.v("uncompletedChallengesLi", "id of challenge in uncompletedChallengesList : " + c.getId() + " current challengeId " + currentChallengeId);
if (c.getId().equals(currentChallengeId)) {
Log.v("uncompletedChallengesLi", "id of challenge in uncompletedChallengesList : " + c.getId() + " returned true" + currentChallengeId);
return true;
}
}
Log.v("uncompletedChallengesLi", "returned false" );
return false;
}
and this is the code that brings the data from the firebase database :
public void startAsynkTask() {
//TODO : search for a solution to this error
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Boolean doInBackground(Object[] objects) {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) {
return false;
}
}
#Override
protected void onPostExecute(Object o) {
if ((boolean) o) {
clearLists();
ChildEventListener generalChallengesListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.v("onChildAdded", "child added");
getChallengeData(dataSnapshot, "onChildAdded");
view.onDataFound();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//TODO : note that the only changing handled is when challenge moves from uncompleted to completed state
if(!dataSnapshot.getKey().equals("questionsList")){
getChallengeData(dataSnapshot, "onChildChanged");
}
for (int i = 0; i < uncompletedChallengesList.size(); i++) {
if (uncompletedChallengesList.get(i).getId().equals(dataSnapshot.getKey())) {
uncompletedChallengesList.remove(i);
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
break;
}
}
checkListsSizeAndAdjustViews();
view.hideProgressBar();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
startAsynkTask();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Toast.makeText(getActivity(), "فشل تحميل البيانات من فضلك تأكد من الاتصال بالانترنت", Toast.LENGTH_SHORT).show();
view.hideProgressBar();
Log.v("Logging", "error loading data : " + databaseError);
}
};
//this code gives data where current user is player 1
player1Listener = challengesReference.orderByChild("player1Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);
//this code gives data where current user is player 2
player2Listener = challengesReference.orderByChild("player2Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);
challengesReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
onInitialDataLoaded();
Log.v("ChallengesFragPresenter", "completed list size :" + completedChallengesList + " , uncompleted list size : " + uncompletedChallengesList);
challengesReference.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
view.onNoInternetConnection();
}
}
};
asyncTask.execute();
}
public String getChallengeData(DataSnapshot dataSnapshot, String tag) {
Log.v("ChallengesFragPresenter", "get challenge data called");
Log.v("ChallengesFragPresenter", "completedChallengesList : " + completedChallengesList.size()
+ ", uncompletedChallengesList " + uncompletedChallengesList.size());
view.startCompletedChallengesAdapter(completedChallengesList);
view.startUnCompletedChallengesAdapter(uncompletedChallengesList);
GenericTypeIndicator<List<Question>> t = new GenericTypeIndicator<List<Question>>() {
};
challenge = new Challenge();
String challengeDate = dataSnapshot.child("date").getValue().toString();
String challengeSubject = dataSnapshot.child("subject").getValue().toString();
String challengeState = dataSnapshot.child("state").getValue().toString();
String challengeId = dataSnapshot.getKey();
ArrayList challengeQuestionsList = (ArrayList) dataSnapshot.child("questionsList").getValue(t);
long player1Score = (long) dataSnapshot.child("player1score").getValue();
long player2Score = (long) dataSnapshot.child("player2score").getValue();
String player1Name = dataSnapshot.child("player1Name").getValue().toString();
String player1Image = dataSnapshot.child("player1Image").getValue().toString();
String player1Uid = dataSnapshot.child("player1Uid").getValue().toString();
String player2Name = dataSnapshot.child("player2Name").getValue().toString();
String player2Image = dataSnapshot.child("player2Image").getValue().toString();
String player2Uid = dataSnapshot.child("player2Uid").getValue().toString();
String challengerName, challengerImage;
if (player1Uid.equals(currentUserUid)) {
currentPlayer = 1;
challengerName = player2Name;
challengerImage = player2Image;
challenge.setSecondChallengerUid(player2Uid);//second means that it is not the player who starts the challenge
if (tag.equals("onChildAdded")) {
player1childrenCount++;
}
} else {
currentPlayer = 2;
challengerName = player1Name;
challengerImage = player1Image;
challenge.setSecondChallengerUid(player1Uid);//second means that it is not the player who starts the challenge
if (tag.equals("onChildAdded")) {
player2childrenCount++;
}
}
challenge.setCurrentPlayer(currentPlayer);
challenge.setChallengerName(challengerName);
challenge.setDate(challengeDate);
challenge.setImage(challengerImage);
challenge.setSubject(challengeSubject);
challenge.setState(challengeState);
challenge.setId(challengeId);
challenge.setPlayer1Score(player1Score);
challenge.setPlayer2Score(player2Score);
challenge.setQuestionsList(challengeQuestionsList);
String score;
if (currentPlayer == 1) {
score = player1Score + " : " + player2Score;
} else {
score = player2Score + " : " + player1Score;
}
challenge.setScore(score);
if (challenge.getState().equals("اكتمل")) {
Log.v("loggingC1", "value is " + !existsInCompletedChallengesList(challengeId));
if (!existsInCompletedChallengesList(dataSnapshot.getKey())) {
view.showCompletedChallengesTv();
completedChallengesList.add(0, challenge);
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
}
}
else if (challenge.getState().equals(refusedChallengeText)) {
Log.v("loggingC2", "value is " + !existsInCompletedChallengesList(challengeId));
if (!existsInCompletedChallengesList(dataSnapshot.getKey())) {
view.showCompletedChallengesTv();
completedChallengesList.add(0, challenge);
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
}
}
else if (challenge.getState().equals(uncompletedChallengeText)) {
Log.v("loggingC3", "value is " + !existsInUncompletedChallengesList(dataSnapshot.getKey()));
if (!existsInUncompletedChallengesList(challengeId)) {
view.showUncompletedChallengesTv();
uncompletedChallengesList.add(0, challenge);
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
}
}
return player1Uid;
}
private void checkListsSizeAndAdjustViews() {
if (uncompletedChallengesList.size() == 0) {
view.hideUncompletedChallengesTv();
} else {
view.showUncompletedChallengesTv();
}
if (completedChallengesList.size() == 0) {
view.hideCompletedChallengesTv();
} else {
view.showCompletedChallengesTv();
}
if (completedChallengesList.size() == 0 && uncompletedChallengesList.size() == 0)
view.showNoChallengesTv();
else {
view.hideNoChallengesTv();
}
}
I am using asynk task at the begging to check if there is internet connection or no

Related

Paytm All in one SDK not working in release more or after publishing to Play store

I have integrated PAYTM ALL IN ONE SDK to my android app. It is working fine in debug mode but in release mode it is throwing exception. There is small thing that i am missing because its working absolutely fine in debug mode but changing it to release it is throwing exception.
Deposit Activity
public class DepositActivity extends AppCompatActivity {
private TextView mmbalance, mgateway, mtext_imp3;
private DatabaseReference mmRef, mmtRef, mmbRef, mmcRef, mmcrRef, mmiRef, mmdRef, mmopRef, mmdbRef, yesRefty3, mmRefuc;
DatabaseReference databaseReference, tdatabaseReference, yesRef, mmRefu, mmRefr;
private ImageView mdep_back;
public EditText mtodepo;
private ConstraintLayout mcons_imp3;
private String TAG ="DepositActivity";
private ProgressBar progressBar;
private String midString="MY MERCHANT ID I HAVE HIDED", txnAmountString="", orderIdString="", txnTokenString="";
private Integer ActivityRequestCode = 2;
public CardView depobtn, depobtn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deposit);
mtodepo=(EditText)findViewById(R.id.amountdepo);
depobtn=(CardView) findViewById(R.id.depositbtn);
depobtn2=(CardView) findViewById(R.id.depositbtn2);
String mydep = mtodepo.getText().toString();
mmbalance = (TextView) findViewById(R.id.dbalance);
mgateway = (TextView) findViewById(R.id.gateway);
mcons_imp3 = findViewById(R.id.cons_imp3);
mtext_imp3 = findViewById(R.id.text_imp3);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
String date = df.format(c.getTime());
Random rand = new Random();
int min =1000, max= 9999;
// nextInt as provided by Random is exclusive of the top value so you need to add 1
int randomNum = rand.nextInt((max - min) + 1) + min;
orderIdString = date+String.valueOf(randomNum);
depobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txnAmountString = mtodepo.getText().toString();
String errors = "";
if(orderIdString.equalsIgnoreCase("")){
errors ="Enter valid Order ID here\n";
Toast.makeText(DepositActivity.this, errors, Toast.LENGTH_SHORT).show();
}else
if(txnAmountString.equalsIgnoreCase("")){
errors ="Enter valid Amount here\n";
Toast.makeText(DepositActivity.this, errors, Toast.LENGTH_SHORT).show();
}else{
int amountff = Math.round(Float.parseFloat(txnAmountString));
if (amountff <= 50000) {
if (amountff > 99) {
getToken();
} else {
Toast.makeText(DepositActivity.this, "Minimum amount > 100", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(DepositActivity.this, "Amount must be smaller than 50000", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void getToken(){
Log.e(TAG, " get token start");
progressBar.setVisibility(View.VISIBLE);
ServiceWrapper serviceWrapper = new ServiceWrapper(null);
Call<Token_Res> call = serviceWrapper.getTokenCall("12345", midString, orderIdString, txnAmountString);
call.enqueue(new Callback<Token_Res>() {
#Override
public void onResponse(Call<Token_Res> call, Response<Token_Res> response) {
Log.e(TAG, " respo "+ response.isSuccessful() );
progressBar.setVisibility(View.GONE);
try {
if (response.isSuccessful() && response.body()!=null){
if (response.body().getBody().getTxnToken()!="") {
Log.e(TAG, " transaction token : "+response.body().getBody().getTxnToken());
startPaytmPayment(response.body().getBody().getTxnToken());
}else {
Log.e(TAG, " Token status false");
}
}
}catch (Exception e){
Log.e(TAG, " error in Token Res "+e.toString());
}
}
#Override
public void onFailure(Call<Token_Res> call, Throwable t) {
progressBar.setVisibility(View.GONE);
Log.e(TAG, " response error "+t.toString());
}
});
}
public void startPaytmPayment (String token){
txnTokenString = token;
// for test mode use it
// String host = "https://securegw-stage.paytm.in/";
// for production mode use it
String host = "https://securegw.paytm.in/";
String orderDetails = "MID: " + midString + ", OrderId: " + orderIdString + ", TxnToken: " + txnTokenString
+ ", Amount: " + txnAmountString;
//Log.e(TAG, "order details "+ orderDetails);
String callBackUrl = host + "theia/paytmCallback?ORDER_ID="+orderIdString;
Log.e(TAG, " callback URL "+callBackUrl);
PaytmOrder paytmOrder = new PaytmOrder(orderIdString, midString, txnTokenString, txnAmountString, callBackUrl);
TransactionManager transactionManager = new TransactionManager(paytmOrder, new PaytmPaymentTransactionCallback(){
#Override
public void onTransactionResponse(Bundle bundle) {
}
#Override
public void networkNotAvailable() {
Log.e(TAG, "network not available ");
}
#Override
public void onErrorProceed(String s) {
Log.e(TAG, " onErrorProcess "+s.toString());
}
#Override
public void clientAuthenticationFailed(String s) {
Log.e(TAG, "Clientauth "+s);
}
#Override
public void someUIErrorOccurred(String s) {
Log.e(TAG, " UI error "+s);
}
#Override
public void onErrorLoadingWebPage(int i, String s, String s1) {
Log.e(TAG, " error loading web "+s+"--"+s1);
}
#Override
public void onBackPressedCancelTransaction() {
Log.e(TAG, "backPress ");
}
#Override
public void onTransactionCancel(String s, Bundle bundle) {
Log.e(TAG, " transaction cancel "+s);
}
});
transactionManager.setShowPaymentUrl(host + "theia/api/v1/showPaymentPage");
transactionManager.startTransaction(this, ActivityRequestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e(TAG ," result code "+resultCode);
// -1 means successful // 0 means failed
// one error is - nativeSdkForMerchantMessage : networkError
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ActivityRequestCode && data != null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Log.e(TAG, key + " : " + (bundle.get(key) != null ? bundle.get(key) : "NULL"));
}
}
/*Log.e(TAG, " data "+ data.getStringExtra("nativeSdkForMerchantMessage"));
Log.e(TAG, " data response - "+data.getStringExtra("response"));*/
Toast.makeText(DepositActivity.this, "Payment Cancelled", Toast.LENGTH_LONG).show();
/*
data response - {"BANKNAME":"WALLET","BANKTXNID":"1395841115",
"CHECKSUMHASH":"7jRCFIk6eRmrep+IhnmQrlrL43KSCSXrmMP5pH0hekXaaxjt3MEgd1N9mLtWyu4VwpWexHOILCTAhybOo5EVDmAEV33rg2VAS/p0PXdk\u003d",
"CURRENCY":"INR","GATEWAYNAME":"WALLET","MID":"EAcR4116","ORDERID":"100620202152",
"PAYMENTMODE":"PPI","RESPCODE":"01","RESPMSG":"Txn Success","STATUS":"TXN_SUCCESS",
"TXNAMOUNT":"2.00","TXNDATE":"2020-06-10 16:57:45.0","TXNID":"202006101112128001101683631290118"}
*/
/*Toast.makeText(this, data.getStringExtra("nativeSdkForMerchantMessage")
+ data.getStringExtra("response"), Toast.LENGTH_SHORT).show();*/
}else{
/*Log.e(TAG, " payment failed");*/
Toast.makeText(DepositActivity.this, "Payment Failed", Toast.LENGTH_LONG).show();
}
}
public static boolean isConnectionAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()
&& netInfo.isConnectedOrConnecting()
&& netInfo.isAvailable()) {
return true;
}
}
return false;
}
}
ServiceWrapper
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceWrapper {
private ServiceInterface mServiceInterface;
public ServiceWrapper(Interceptor mInterceptorheader) {
mServiceInterface = getRetrofit(mInterceptorheader).create(ServiceInterface.class);
}
public Retrofit getRetrofit(Interceptor mInterceptorheader) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient mOkHttpClient = null;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(1201, TimeUnit.SECONDS);
builder.readTimeout(901, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
mOkHttpClient = builder.build();
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://mywebsitei_i_have_hided.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(mOkHttpClient)
.build();
return retrofit;
}
public Call<Token_Res> getTokenCall(String code, String mid, String order_id, String amount) {
return mServiceInterface.generateTokenCall(
convertPlainString(code), convertPlainString(mid), convertPlainString(order_id)
, convertPlainString(amount));
}
// convert aa param into plain text
public RequestBody convertPlainString(String data){
RequestBody plainString = RequestBody.create(MediaType.parse("text/plain"), data);
return plainString;
}
}
This is because of the new R8 code obfuscation. You need to disable it from your project by adding below line to the gradle.properties file -
android.enableR8=false
Also you need to add below lines to your proguard rules file -
# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
#com.google.gson.annotations.SerializedName <fields>;
}

CustomAlertDialog doesn't finish its process after deleting a record of databse

I am using my CustomAlertDialog in order to delete a record from database, when I delete one successfully and I attempt to insert a new row into database, the AlertDialog appears again notwithstanding I didn't even call it and when I click the delete button it deletes one record until all the records are deleted and app crashes.
I call it on my AdapterClass =>
#Override
public void onClick(View view) {
E04Object obj = object.get(getAdapterPosition()) ;
id = obj.getId() ;
if (view == deleteBtn) {
int position = id ;
if (position != RecyclerView.NO_POSITION) {
activityReference.ShowDialog(position);
}
clicked = false ;
} }
and I initialize it in my FragmentClass =>
#Override
public void ShowDialog(int position) {
DialogObject dialogObject = new DialogObject() ;
CustomDialogView customDialogView = new CustomDialogView(getActivity() , dialogObject) ;
dialogObject.setListener(new DialogListener() {
#Override
public void onPositive() {
dbConnector.get().execSQL(
" DELETE FROM " + db.Tables.MYDB + " WHERE " + db.MYDB.ID + " = " + position );
customDialogView.hide();
list.remove(MyAdapter.cardId) ;
adapter.notifyDataSetChanged();
}
#Override
public void onNegative() {
customDialogView.hide();
}
});
customDialogView.setCancelable(true);
customDialogView.show();
}
#Override
public void ShowDialog(int position) {
DialogObject dialogObject = new DialogObject() ;
CustomDialogView customDialogView = new CustomDialogView(getActivity() , dialogObject) ;
dialogObject.setListener(new DialogListener() {
#Override
public void onPositive() {
dbConnector.get().execSQL(
" DELETE FROM " + db.Tables.MYDB + " WHERE " + db.MYDB.ID + " = " + position );
customDialogView.dismiss();
list.remove(MyAdapter.cardId) ;
adapter.notifyDataSetChanged();
}
#Override
public void onNegative() {
customDialogView.dismiss();
}
});
customDialogView.setCancelable(true);
customDialogView.show();
}
customDialogView.hide();
replace code with this
customDialogView.dismiss();

on child added method work multiple times

I am making a challenge between two users in my app using firebase database. in the challenge I store player1Uid and player2Uid(player1 is the player who started the challenge and player two is the player who will accept or refuse the challenge). I want to make a history of challenges so If the challenge is completed I store it in a list called"completedChallengesList" and if the challenge isn't completed yet I store it in a list called uncompleted challenge list.the code some times work fine but in other times it bring the data more than one time to the list.
this is my code that brings data :
public void startAsynkTask() {
//TODO : search for a solution to this error
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Boolean doInBackground(Object[] objects) {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) {
return false;
}
}
#Override
protected void onPostExecute(Object o) {
if ((boolean) o) {
clearLists();
ChildEventListener generalChallengesListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String challengeState = dataSnapshot.child("state").getValue().toString();
Log.v("Logging2", "onChildAdded");
if (challengeState.equals(uncompletedChallengeText)) {
getChallengeData(dataSnapshot, "onChildAdded");
view.onDataFound();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//TODO : note that the only changing handled is when challenge moves from uncompleted to completed state
getChallengeData(dataSnapshot, "onChildChanged");
for (int i = 0; i < uncompletedChallengesList.size(); i++) {
if (uncompletedChallengesList.get(i).getId().equals(dataSnapshot.getKey())) {
uncompletedChallengesList.remove(i);
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
break;
}
}
checkListsSizeAndAdjustViews();
view.hideProgressBar();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
startAsynkTask();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Toast.makeText(getActivity(), "فشل تحميل البيانات من فضلك تأكد من الاتصال بالانترنت", Toast.LENGTH_SHORT).show();
view.hideProgressBar();
Log.v("Logging", "error loading data : " + databaseError);
}
};
//this code gives data where current user is player 1
player1Listener = challengesReference.orderByChild("player1Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);
//this code gives data where current user is player 2
player2Listener = challengesReference.orderByChild("player2Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);
challengesReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
onInitialDataLoaded();
Log.v("ChallengesFragPresenter", "completed list size :" + completedChallengesList + " , uncompleted list size : " + uncompletedChallengesList);
challengesReference.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
view.onNoInternetConnection();
}
}
};
asyncTask.execute();
}
public String getChallengeData(DataSnapshot dataSnapshot, String tag) {
Log.v("ChallengesFragPresenter", "get challenge data called");
Log.v("ChallengesFragPresenter", "completedChallengesList : " + completedChallengesList.size()
+ ", uncompletedChallengesList " + uncompletedChallengesList.size());
view.startCompletedChallengesAdapter(completedChallengesList);
view.startUnCompletedChallengesAdapter(uncompletedChallengesList);
GenericTypeIndicator<List<Question>> t = new GenericTypeIndicator<List<Question>>() {
};
challenge = new Challenge();
String challengeDate = dataSnapshot.child("date").getValue().toString();
String challengeSubject = dataSnapshot.child("subject").getValue().toString();
String challengeState = dataSnapshot.child("state").getValue().toString();
String challengeId = dataSnapshot.getKey();
ArrayList challengeQuestionsList = (ArrayList) dataSnapshot.child("questionsList").getValue(t);
long player1Score = (long) dataSnapshot.child("player1score").getValue();
long player2Score = (long) dataSnapshot.child("player2score").getValue();
String player1Name = dataSnapshot.child("player1Name").getValue().toString();
String player1Image = dataSnapshot.child("player1Image").getValue().toString();
String player1Uid = dataSnapshot.child("player1Uid").getValue().toString();
String player2Name = dataSnapshot.child("player2Name").getValue().toString();
String player2Image = dataSnapshot.child("player2Image").getValue().toString();
String player2Uid = dataSnapshot.child("player2Uid").getValue().toString();
String challengerName, challengerImage;
if (player1Uid.equals(currentUserUid)) {
currentPlayer = 1;
challengerName = player2Name;
challengerImage = player2Image;
challenge.setSecondChallengerUid(player2Uid);//second means that it is not the player who starts the challenge
if (tag.equals("onChildAdded")) {
player1childrenCount++;
}
} else {
currentPlayer = 2;
challengerName = player1Name;
challengerImage = player1Image;
challenge.setSecondChallengerUid(player1Uid);//second means that it is not the player who starts the challenge
if (tag.equals("onChildAdded")) {
player2childrenCount++;
}
}
challenge.setCurrentPlayer(currentPlayer);
challenge.setChallengerName(challengerName);
challenge.setDate(challengeDate);
challenge.setImage(challengerImage);
challenge.setSubject(challengeSubject);
challenge.setState(challengeState);
challenge.setId(challengeId);
challenge.setQuestionsList(challengeQuestionsList);
String score;
if (currentPlayer == 1) {
score = player2Score + " : " + player1Score;
} else {
score = player1Score + " : " + player2Score;
}
challenge.setScore(score);
if (challenge.getState().equals("اكتمل")) {
view.showCompletedChallengesTv();
if(!completedChallengesList.contains(challenge)) {
completedChallengesList.add(0, challenge);
}
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
} else if (challenge.getState().equals(refusedChallengeText)) {
view.showCompletedChallengesTv();
if(!completedChallengesList.contains(challenge)) {
completedChallengesList.add(0, challenge);
}
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
} else if (challenge.getState().equals(uncompletedChallengeText)) {
view.showUncompletedChallengesTv();
if(!uncompletedChallengesList.contains(challenge)) {
uncompletedChallengesList.add(0, challenge);
}
view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
}
return player1Uid;
}
after long time of debugging I found that the method getChallengeData() is called more than one time when a new child added . I tried a lot to know why but I couldn't.
NOTE : I am using asynk task to check if there is internet connection or no before start loading data.
I think that your problem is, you are not removing your listner "generalChallengesListener", so multiple refereces will be created, so the onChildAdded will be excuted multiple times as the number of listners you created. So add a reference to your lister and know when you should remove it.
Hope it will helps you =)

Trouble getting getItem on an object in a RecyclerAdapter

I'm currently having some trouble getItem in the RecyclerAdapter on my Photo class. I tried adding
public int getItem(int pos){
return getItem(pos);
}
but that did not seem to work it. How can i getItem(position) without it having errors? (If i have not elaborated enough please say.)
Here is my code so you can tell me what i am doing wrong.
ViewProfilePostsAdapter.java
public class ViewProfilePostsAdapter extends RecyclerView.Adapter<ViewProfilePostsAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private String[] mDataSet;
private int[] getItemIn;
private LayoutInflater mInflater;
private int mLayoutResource;
private Context mContext;
private DatabaseReference mReference;
private String currentUsername;
private Photo mPic;
public static class ViewHolder extends RecyclerView.ViewHolder {
//private final TextView textView;
ImageView mProfileImage;
String likesString;
TextView username, timeDelta, caption, likes, liked;
ImageView postImage;
ImageView heartRed, heartWhite;
UserAccountSettings settings = new UserAccountSettings();
User user = new User();
StringBuilder users;
String mLikesString;
boolean likeByCurrentUser;
Heart heart;
GestureDetector detector;
Photo photo;
public ViewHolder(View convertView) {
super(convertView);
if(convertView == null) {
username = (TextView) convertView.findViewById(R.id.display_name);
postImage = (ImageView) convertView.findViewById(R.id.post_image);
caption = (TextView) convertView.findViewById(R.id.image_caption);
timeDelta = (TextView) convertView.findViewById(R.id.image_time_posted);
likes = (TextView) convertView.findViewById(R.id.tvLikesString);
mProfileImage = (ImageView) convertView.findViewById(R.id.f_profile_image);
heartRed = (ImageView) convertView.findViewById(R.id.image_heart_red);
heartWhite = (ImageView) convertView.findViewById(R.id.image_heart_white);
heart = new Heart(heartWhite, heartRed);
liked = (TextView) convertView.findViewById(R.id.likeText);
}
}
}
public ViewProfilePostsAdapter(String[] dataSet, int[] intSet) {
mDataSet = dataSet;
getItemIn = intSet;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_post_listitem, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position)
{
Log.d(TAG, "Element " + position + " set.");
viewHolder.photo = getItem(position);
viewHolder.detector = new GestureDetector(mContext, new GestureListener(viewHolder));
getCurrentUsername();
getLikesString(viewHolder);
viewHolder.caption.setText(getItem(position).getCaption());
String timestampDifference = getTimestampDifference(getItem(position));
if(!timestampDifference.equals("0")){
viewHolder.timeDelta.setText(timestampDifference + " DAYS AGO");
}else{
viewHolder.timeDelta.setText("TODAY");
}
final ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(getItem(position).getImage_path(), viewHolder.postImage);
//get the profile image and username
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "onDataChange: OnDataChange ******************************************************************************");
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.e(TAG, "onDataChange: found user: "
+ singleSnapshot.getValue(UserAccountSettings.class).getUsername() + "****************************");
holder.username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.mProfileImage);
holder.settings = singleSnapshot.getValue(UserAccountSettings.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query userQuery = mReference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
viewHolder.user = singleSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mDataSet.length;
}
public int getItem(int pos){
return getItem(pos);
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener{
ViewHolder mHolder;
public GestureListener(ViewHolder holder) {
mHolder = holder;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG, "onDoubleTap: double tap detected.");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_photos))
.child(mHolder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren())
{
String keyID = singleSnapshot.getKey();
//case1: Then user already liked the photo
if(mHolder.likeByCurrentUser &&
singleSnapshot.getValue(Like.class).getUser_id()
.equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){
mReference.child(mContext.getString(R.string.dbname_photos))
.child(mHolder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(keyID)
.removeValue();
mReference.child(mContext.getString(R.string.dbname_user_photos))
.child(mHolder.photo.getUser_id())
.child(mHolder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(keyID)
.removeValue();
mHolder.heart.toggleLike();
getLikesString(mHolder);
}
//case2: The user has not liked the photo
else if(!mHolder.likeByCurrentUser){
//add new like
addNewLike(mHolder);
break;
}
}
if(!dataSnapshot.exists()){
//add new like
addNewLike(mHolder);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
}
private void addNewLike(final ViewHolder holder){
Log.d(TAG, "addNewLike: adding new like");
String newLikeID = mReference.push().getKey();
Like like = new Like();
like.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
mReference.child(mContext.getString(R.string.dbname_photos))
.child(holder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(newLikeID)
.setValue(like);
mReference.child(mContext.getString(R.string.dbname_user_photos))
.child(holder.photo.getUser_id())
.child(holder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(newLikeID)
.setValue(like);
holder.heart.toggleLike();
getLikesString(holder);
}
private void getCurrentUsername(){
Log.d(TAG, "getCurrentUsername: retrieving user account settings");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getLikesString(final ViewHolder holder){
Log.d(TAG, "getLikesString: getting likes string");
try{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_photos))
.child(holder.photo.getPhoto_id())
.child(mContext.getString(R.string.field_likes));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
holder.users = new StringBuilder();
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren())
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(singleSnapshot.getValue(Like.class).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found like: " +
singleSnapshot.getValue(User.class).getUsername());
holder.users.append(singleSnapshot.getValue(User.class).getUsername());
holder.users.append(",");
}
String[] splitUsers = holder.users.toString().split(",");
if(holder.users.toString().contains(currentUsername + ",")){
holder.likeByCurrentUser = true;
}else{
holder.likeByCurrentUser = false;
}
int length = splitUsers.length;
if(length == 1){
holder.likesString = "Liked by " + splitUsers[0];
}
else if(length == 2){
holder.likesString = "Liked by " + splitUsers[0]
+ " and " + splitUsers[1];
}
else if(length == 3){
holder.likesString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ " and " + splitUsers[2];
}
else if(length == 4){
holder.likesString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ ", " + splitUsers[2]
+ " and " + splitUsers[3];
}
else if(length > 4){
holder.likesString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ ", " + splitUsers[2]
+ " and " + (splitUsers.length - 3) + " others";
}
Log.d(TAG, "onDataChange: likes string: " + holder.likesString);
//setup likes string
setupLikesString(holder, holder.likesString);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
if(!dataSnapshot.exists()){
holder.likesString = "";
holder.likeByCurrentUser = false;
//setup likes string
setupLikesString(holder, holder.likesString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}catch (NullPointerException e){
Log.e(TAG, "getLikesString: NullPointerException: " + e.getMessage()
);
holder.likesString = "";
holder.likeByCurrentUser = false;
//setup likes string
setupLikesString(holder, holder.likesString);
}
}
private void setupLikesString(final ViewHolder holder, String likesString) {
Log.d(TAG, "setupLikesString: likes string:" + holder.likesString);
if (holder.likeByCurrentUser) {
Log.d(TAG, "setupLikesString: photo is liked by current user");
holder.liked.setText("UnLike");
holder.heartWhite.setVisibility(View.GONE);
holder.heartRed.setVisibility(View.VISIBLE);
holder.heartRed.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return holder.detector.onTouchEvent(event);
}
});
} else {
Log.d(TAG, "setupLikesString: photo is not liked by current user");
holder.liked.setText("Like");
holder.heartWhite.setVisibility(View.VISIBLE);
holder.heartRed.setVisibility(View.GONE);
holder.heartWhite.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return holder.detector.onTouchEvent(event);
}
});
}
holder.likes.setText(likesString);
}
//---------------------------------------------end of likes----------------------------
private String getTimestampDifference(Photo photo){
Log.d(TAG, "getTimestampDifference: getting timestamp difference.");
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.CANADA);
sdf.setTimeZone(TimeZone.getTimeZone("Canada/Pacific"));//google 'android list of timezones'
Date today = c.getTime();
sdf.format(today);
Date timestamp;
final String photoTimestamp = photo.getDate_created();
try{
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24 )));
}catch (ParseException e){
Log.e(TAG, "getTimestampDifference: ParseException: " + e.getMessage() );
difference = "0";
}
return difference;
}
}
Photo.java
public class Photo implements Parcelable {
private String caption;
private String date_created;
private String photo_id;
private String user_id;
private String tags;
private String image_path;
private List<Like> likes;
public Photo(){
}
public Photo(String caption, String date_created, String photo_id, String user_id, String tags, String image_path, List<Like> likes) {
this.caption = caption;
this.date_created = date_created;
this.photo_id = photo_id;
this.user_id = user_id;
this.tags = tags;
this.image_path = image_path;
this.likes = likes;
}
protected Photo(Parcel in) {
caption = in.readString();
date_created = in.readString();
photo_id = in.readString();
user_id = in.readString();
tags = in.readString();
image_path = in.readString();
}
public static final Creator<Photo> CREATOR = new Creator<Photo>() {
#Override
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
#Override
public Photo[] newArray(int size) {
return new Photo[size];
}
};
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getDate_created() {
return date_created;
}
public void setDate_created(String date_created) {
this.date_created = date_created;
}
public String getPhoto_id() {
return photo_id;
}
public void setPhoto_id(String photo_id) {
this.photo_id = photo_id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getImage_path() {
return image_path;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
public List<Like> getLikes() {
return likes;
}
public void setLikes(List<Like> likes) {
this.likes = likes;
}
#Override
public String toString() {
return "Photo{" +
"caption='" + caption + '\'' +
", date_created='" + date_created + '\'' +
", photo_id='" + photo_id + '\'' +
", user_id='" + user_id + '\'' +
", tags='" + tags + '\'' +
", image_path='" + image_path + '\'' +
", likes=" + likes +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(caption);
parcel.writeString(date_created);
parcel.writeString(photo_id);
parcel.writeString(user_id);
parcel.writeString(tags);
parcel.writeString(image_path);
}
}
You function calls itself:
public int getItem(int pos){
return getItem(pos);
}
To fix the problem you should do several things:
1) You adapter should have collection of Photo objects. E.g. ArrayList list;
It should be filled from maybe Countructor. So, your adapter should have constructor containing this list.
2) Change getItem method to this :
public Photo getItem(int pos){
return list.get(pos);
}
First of all, your getItem function should return an object (i guess).
Also Honestly I am little confused what u r trying to accomplish and I thought You wanted to get an item in a specific position in your recycler view right?
In your Viewholder class just add below code
int position = 0;
In your OnBindViewHolder Function in the RecyclerViewAdapter, there is a position of each item in your recyclerview
public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) {
Model yourModel= modelList.get(position);
holder.position = position;
}
Besides if you are trying to get OnClickListener in your recyclerview. The Following way may be useful. Create Interface
public interface RecyclerViewOnItemClickListener {
void OnItemClickListener(View view, int position);
void OnItemLongClickListener(View view, int position);
}
This code goes into RecyclerAdapter Class
public void setOnItemClickListener(RecyclerViewOnItemClickListener OnItemClickListener){
this.recyclerViewOnItemClickListener = OnItemClickListener;
}
Final Step in your Main activity or your fragment that you wanna show the recyclerview
recyclerViewAdapter.setOnItemClickListener(new RecyclerViewOnItemClickListener() {
#Override
public void OnItemClickListener(View view, int position) {
Model yourModel= modelList.get(position);
}
#Override
public void OnItemLongClickListener(View view, int position) {
}
});
Here is how you can get the item in a specific position.
Hope this helps ;)

Getting Error java.lang.IllegalArgumentException: unexpected url

Hi i am trying to send some data to server by using json parsing but activity is getting crashed and it leads to
java.lang.IllegalArgumentException: unexpected url
This is My Activity Code and i am commenting the lines where i am getting the Errors.
public class LoginActivity extends AppCompatActivity { **// Showing Error at this LIne**
public Location location;
private Button btnLogin;
private boolean doubleBackToExitPressedOnce = false;
private EditText phoneNo, password;
private CheckBox cbShow, cbRemember;
private NetworkUtil networkUtil;
private SharePrefUtil sharePref;
private LocationInfo locationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
networkUtil = new NetworkUtil(getApplicationContext());
sharePref = new SharePrefUtil(getApplicationContext());
initScreen();
if (sharePref.getValueFromSharePref("remeberFlag").equalsIgnoreCase("true")) {
phoneNo.setText(sharePref.getValueFromSharePref("mobileno"));
password.setText(sharePref.getValueFromSharePref("password"));
cbRemember.setChecked(true);
}
}
private void initScreen() {
LocationLibrary.showDebugOutput(true);
try {
LocationLibrary.initialiseLibrary(LoginActivity.this, 60 * 1000, 60 * 1000 * 2, "com.aspeage.jagteraho");
} catch (UnsupportedOperationException e) {
Toast.makeText(this, "Device doesn't have any location providers", Toast.LENGTH_LONG).show();
}
phoneNo = (EditText) findViewById(R.id.ed_phoneno);
password = (EditText) findViewById(R.id.ed_password);
cbRemember = (CheckBox) findViewById(R.id.cbox_rememberme);
cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) sharePref.setValueInSharePref("remeberFlag", "true");
else sharePref.setValueInSharePref("remeberFlag", "false");
}
});
cbShow = (CheckBox) findViewById(R.id.cbox_showpass);
cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
password.setInputType(129);
}
}
});
btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new ButtonClick());
}
private class ButtonClick implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
btnLoginClicked();
break;
default:
break;
}
}
}
private void btnLoginClicked() {
if(phoneNo.getText().toString().trim().equals("admin") && password.getText().toString().trim().equals("admin")) {
loginService();
}
if (validation()) {
if (cbRemember.isChecked())
rememberMe(password.getText().toString().trim());
if (networkUtil.isConnected()) {
loginService();
} else {
new SweetAlertDialog(LoginActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No Network Connection")
.show();
}
}
}
/**
* save username and password in SharedPreferences.
*
* #param //password is key value for storing in SharedPreferences.
*/
public void rememberMe(String password) {
SharePrefUtil sharePref = new SharePrefUtil(getApplicationContext());
sharePref.setValueInSharePref("password", password);
}
private boolean validation() {
int errorCount = 0;
if (phoneNo.getText().toString().trim().equals("")
|| phoneNo.getText().length() != 10) {
phoneNo.setError("Enter valid phone number");
errorCount = errorCount + 1;
if (errorCount == 1) {
phoneNo.requestFocus();
}
} else {
phoneNo.setError(null);
}
if (password.getText().toString().trim().equals("")
|| password.getText().length() != 12) {
password.setError("Enter valid password");
errorCount = errorCount + 1;
if (errorCount == 1) {
password.requestFocus();
}
} else {
password.setError(null);
}
if (errorCount == 0) {
return true;
} else {
return false;
}
}
private void batteryTimer(){
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run() {
if (networkUtil.isConnected()) {
batteryLevelCheckService(); // **Getting Error at this Line**
}
else {
offlineBatteryStatus();
}
}
};
timer.scheduleAtFixedRate(hourlyTask, 01, 60000);
}
private void batteryLevelCheckService() {
OkHttpClient client = new OkHttpClient();
String requestURL = String.format(getResources().getString(R.string.service_batteryLevelCheckService));
JSONArray jsonArrayRequest = new JSONArray();
JSONObject jsonRequest;
try {
List<BatteryStatusModel> batStatusOffline = new Select().from(BatteryStatusModel.class).execute();
if (batStatusOffline.size() > 0) {
for (BatteryStatusModel batStatusObject : batStatusOffline) {
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", batStatusObject.batStatTime);
jsonRequest.accumulate("batteryStatusLat", "" + batStatusObject.battery_lat);
jsonRequest.accumulate("batteryStatusLog", "" + batStatusObject.battery_lon);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobno", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + batStatusObject.batteryStatus);
jsonArrayRequest.put(jsonRequest);
}
}
Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String time = simpleDateFormat.format(today);
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", time);
jsonRequest.accumulate("batteryStatusLat", "" + locationInfo.lastLat);
jsonRequest.accumulate("batteryStatusLon", "" + locationInfo.lastLong);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobNo", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + percent);
jsonArrayRequest.put(jsonRequest);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonArrayRequest.toString());
Request request = new Request.Builder()
.url(requestURL) // Getting Error at this Line
.post(body).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseString = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(responseString);
String status = jsonResponse.getString("status");
String message = jsonResponse.getString("message");
Log.d("jagteraho", "response :: status: " + status.toString() + " message: " + message);
if (status.equals("success")) {
new Delete().from(BatteryStatusModel.class).execute();
} else if (status.equals("failure")) {
} else if (status.equals("error")) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
This is my Logcat
java.lang.IllegalArgumentException: unexpected url: >http://192.168.2.20:8080/jagteraho/batteryStatus/save
at okhttp3.Request$Builder.url(Request.java:143)
at com.aspeage.jagteraho.LoginActivity.batteryLevelCheckService(LoginActivity.java:270)
at com.aspeage.jagteraho.LoginActivity.access$600(LoginActivity.java:59)
at com.aspeage.jagteraho.LoginActivity$4.run(LoginActivity.java:216)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Please help me with the possible solutions i am quite new in Android Development
Your error is coming from OkHttp.
If you search for the error message, you can see where OkHttp is generating it:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Request.java#L142
HttpUrl parsed = HttpUrl.parse(url);
if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
It means that your URL is invalid. As the comment to your question points out: >http://192.168.2.20:8080/jagteraho/batteryStatus/save is not a valid URL.
You need to remove the >.

Categories

Resources