In App Purchases - How to handle the second click? - java

i just want to implement in-app-purchasement into my app. It is a card game with different rulesets. So now want to implement 2 new rulesets which should work as my products and with in-app-purchasement.
I have this:
`go = (Button)findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList skuList = new ArrayList();
skuList.add(inappid);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mservice.getSkuDetails(3, getPackageName(),
"inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList =
skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals(inappid)) {
System.out.println("price " + price);
Bundle buyIntentBundle =
mservice.getBuyIntent(3, getPackageName(), sku,
"inapp",
"blablabla");
PendingIntent pendingIntent =
buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(
pendingIntent.getIntentSender(), 1001,
new Intent(), Integer.valueOf(0),
Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IntentSender.SendIntentException e ) {
e.printStackTrace();
}
}
});`
First click on my ruleset works fine. The second click triggers the app to break down with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.IntentSender android.app.PendingIntent.getIntentSender()' on a null object reference
Do you have some good in-app tutorials or a tipp for me?
Thanks in advance
JD

Here is my BaseClass that i use everywhere i need. Just extend your activity by this BaseInAppPurchaseActivity
Bonus in this class.
You can get what items are available for purchase so user can not get future exception if item is not available like
checkAvailablePurchases(skuList, new OnResultInApp() {
#Override
public void onResult(ArrayList<AvailablePurchase> availablePurchaseArrayList) {
.. logic for showing view with available purchaseItem
}
});
For purchasing an item
purchaseItem(googleInAppId, new OnResultPurchase() {
#Override
public void onSuccess(PurchaseResponseBean purchaseResponseBean, String inAppPurchaseData) {
// your stuff
}
#Override
public void onError() {
showToast(R.string.something_went_wrong);
}
});
Isn't this look pretty clean and nice.
BaseInAppPurchaseActivity.class
package in.kpis.nearyou.base;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import com.android.vending.billing.IInAppBillingService;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import in.kpis.nearyou.entity.AvailablePurchase;
import in.kpis.nearyou.entity.Helper;
import in.kpis.nearyou.entity.PurchaseResponseBean;
import in.kpis.nearyou.entity.UserPurchaseItemsBean;
import in.kpis.nearyou.utilities.AppPreference;
import static in.kpis.nearyou.base.BaseInAppPurchaseActivity.ConsuptionResponseType.SUCCESS;
import static in.kpis.nearyou.base.BaseInAppPurchaseActivity.PurchaseStateTypes.PURCHASED;
public class BaseInAppPurchaseActivity extends BaseAppCompatActivity {
private static final String TAG = BaseInAppPurchaseActivity.class.getSimpleName();
private IInAppBillingService mService;
private static final char[] symbols = new char[36];
static {
for (int idx = 0; idx < 10; ++idx)
symbols[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
symbols[idx] = (char) ('a' + idx - 10);
}
public void startInAppPurchaseServices() {
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
private String appPackageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appPackageName = this.getPackageName();
startInAppPurchaseServices();
}
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
startAsyncForCheckingAvailablePurchase();
}
};
private void startAsyncForCheckingAvailablePurchase() {
if (skuListByNearyouServer != null && skuListByNearyouServer.size() > 0 & onResultInApp != null) {
AvailablePurchaseAsyncTask mAsyncTask = new AvailablePurchaseAsyncTask(appPackageName, skuListByNearyouServer, onResultInApp);
mAsyncTask.execute();
}
}
private ArrayList<String> skuListByNearyouServer = new ArrayList<>();
OnResultInApp onResultInApp;
public void checkAvailablePurchases(ArrayList<String> skuList, OnResultInApp onResultInApp) {
skuListByNearyouServer = skuList;
this.onResultInApp = onResultInApp;
if (mService == null) startInAppPurchaseServices();
else startAsyncForCheckingAvailablePurchase();
}
public interface OnResultPurchase {
void onSuccess(PurchaseResponseBean purchaseResponseBean, String inAppPurchaseData);
void onError();
}
private OnResultPurchase onResultPurchase;
private String itemToPurchaseSku;
public void purchaseItem(String sku, OnResultPurchase onResultPurchase) {
this.onResultPurchase = onResultPurchase;
itemToPurchaseSku = sku;
if (isBillingSupported()) {
String generatedPayload = getPayLoad();
AppPreference.getInstance(BaseInAppPurchaseActivity.this).setDeveloperPayload(generatedPayload);
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", generatedPayload);
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
try {
startIntentSenderForResult(pendingIntent.getIntentSender(), Helper.RESPONSE_CODE, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Helper.RESPONSE_CODE) {
if (data != null && data.getExtras() != null && data.getStringExtra("INAPP_DATA_SIGNATURE") != null & data.getStringExtra("INAPP_PURCHASE_DATA") != null) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK && responseCode == 0) {
try {
PurchaseResponseBean purchaseResponseBean = new Gson().fromJson(purchaseData, PurchaseResponseBean.class);
String sku = purchaseResponseBean.getProductId();
String developerPayload = purchaseResponseBean.getDeveloperPayload();
int responseCodeConsuption = consumePurchaseItem(purchaseResponseBean.getPurchaseToken());
if (responseCodeConsuption == SUCCESS) {
if (purchaseResponseBean.getPurchaseState() == PURCHASED && itemToPurchaseSku.equals(sku) && developerPayload.equals(AppPreference.getInstance(BaseInAppPurchaseActivity.this).getDeveloperPayload())) {
if (onResultPurchase != null)
onResultPurchase.onSuccess(purchaseResponseBean, purchaseData);
} else onErrorOfPurchase();
} else onResultPurchase.onSuccess(purchaseResponseBean, purchaseData);
} catch (Exception e) {
e.printStackTrace();
onErrorOfPurchase();
}
} else onErrorOfPurchase();
}
} else onErrorOfPurchase();
}
private void onErrorOfPurchase() {
if (onResultPurchase != null) onResultPurchase.onError();
}
interface PurchaseStateTypes {
int PURCHASED = 0;
int CANCELED = 1;
int REFUNDED = 2;
}
interface ConsuptionResponseType {
int SUCCESS = 0;
}
private String getPayLoad() {
RandomString randomString = new RandomString(36);
String payload = randomString.nextString();
return payload;
}
private class RandomString {
private final Random random = new Random();
private final char[] buf;
RandomString(int length) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
public final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
public interface OnResultInApp {
void onResult(ArrayList<AvailablePurchase> canPurchaseList);
}
private class AvailablePurchaseAsyncTask extends AsyncTask<Void, Void, Bundle> {
String packageName;
ArrayList<String> skuList;
OnResultInApp OnResultInApp;
AvailablePurchaseAsyncTask(String packageName, ArrayList<String> skuList, OnResultInApp OnResultInApp) {
this.packageName = packageName;
this.skuList = skuList;
this.OnResultInApp = OnResultInApp;
}
#Override
protected Bundle doInBackground(Void... voids) {
Bundle query = new Bundle();
query.putStringArrayList(Helper.ITEM_ID_LIST, skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, packageName, "inapp", query);
} catch (RemoteException e) {
e.printStackTrace();
}
return skuDetails;
}
#Override
protected void onPostExecute(Bundle skuDetails) {
ArrayList<AvailablePurchase> availablePurchaseArrayList = new ArrayList<>();
if (skuDetails != null) {
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
if (responseList != null) {
for (String thisResponse : responseList) {
JSONObject object = null;
try {
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
availablePurchaseArrayList.add(new AvailablePurchase(sku, price, false));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
for (AvailablePurchase availablePurchase : availablePurchaseArrayList) {
for (String sku : skuList) {
if (sku.equals(availablePurchase.getSku())) {
availablePurchase.setActive(true);
}
}
}
if (OnResultInApp != null) {
OnResultInApp.onResult(availablePurchaseArrayList);
}
}
}
public boolean isBillingSupported() {
int response = 1;
try {
response = mService.isBillingSupported(3, getPackageName(), "inapp");
} catch (RemoteException e) {
e.printStackTrace();
}
if (response > 0) {
return false;
}
return true;
}
public int consumePurchaseItem(String purchaseToken) {
if (isBillingSupported()) {
try {
int response = mService.consumePurchase(3, getPackageName(), purchaseToken);
return response;
} catch (RemoteException e) {
e.printStackTrace();
return -1;
}
} else return -1;
}
public Bundle getAllUserPurchase() {
Bundle ownedItems = null;
try {
ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
} catch (RemoteException e) {
e.printStackTrace();
}
return ownedItems;
}
public List<UserPurchaseItemsBean> extractAllUserPurchase(Bundle ownedItems) {
List<UserPurchaseItemsBean> mUserItems = new ArrayList<UserPurchaseItemsBean>();
int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
if (purchaseDataList != null) {
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
assert signatureList != null;
String signature = signatureList.get(i);
assert ownedSkus != null;
String sku = ownedSkus.get(i);
UserPurchaseItemsBean allItems = new UserPurchaseItemsBean(sku, purchaseData, signature);
mUserItems.add(allItems);
}
}
}
return mUserItems;
}
#Override
public void onDestroy() {
super.onDestroy();
stopInAppPurchaseService();
}
private void stopInAppPurchaseService() {
if (mService != null) {
unbindService(mServiceConn);
}
}
}
AvailablePurchase.class
/**
* Created by KHEMRAJ on 7/13/2017.
*/
public class AvailablePurchase {
private String sku;
private String price;
private boolean isActive;
public AvailablePurchase(String sku, String price, boolean isActive) {
this.sku = sku;
this.price = price;
this.isActive = isActive;
}
public String getSku() {
return sku;
}
public String getPrice() {
return price;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
}
Helper.class
/**
* Created by KHEMRAJ on 7/13/2017.
*/
import android.content.Context;
import android.widget.Toast;
public class Helper {
public static final String ITEM_ID_LIST = "ITEM_ID_LIST";
public static final String ITEM_ONE_ID = "android.test.purchased";
public static final String ITEM_TWO_ID = "2";
public static final String ITEM_THREE_ID = "3";
public static final String ITEM_FIVE_ID= "4";
public static final String ITEM_SIX_ID = "5";
public static final int RESPONSE_CODE = 1001;
public static void displayMessage(Context context, String message){
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
PurchaseResponseBean.class
/**
* Created by KHEMRAJ on 7/15/2017.
*/
public class PurchaseResponseBean {
private String productId;
private String developerPayload;
private String purchaseToken;
private String orderId;
private String purchaseTime;
private int purchaseState;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getDeveloperPayload() {
return developerPayload;
}
public void setDeveloperPayload(String developerPayload) {
this.developerPayload = developerPayload;
}
public String getPurchaseToken() {
return purchaseToken;
}
public void setPurchaseToken(String purchaseToken) {
this.purchaseToken = purchaseToken;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getPurchaseTime() {
return purchaseTime;
}
public void setPurchaseTime(String purchaseTime) {
this.purchaseTime = purchaseTime;
}
public int getPurchaseState() {
return purchaseState;
}
public void setPurchaseState(int purchaseState) {
this.purchaseState = purchaseState;
}
}
UserPurchaseItemsBean.class
public class UserPurchaseItemsBean {
private String sku;
private String purchasedata;
private String signature;
public UserPurchaseItemsBean(String sku, String purchasedata, String signature) {
this.sku = sku;
this.purchasedata = purchasedata;
this.signature = signature;
}
public String getSku() {
return sku;
}
public String getPurchasedata() {
return purchasedata;
}
public String getSignature() {
return signature;
}
}
AppPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class AppPreference {
String DEVELOPERPAYLOAD = "DEVELOPERPAYLOAD";
String PURCHASETOKEN = "PURCHASETOKEN";
//Configuration Variable
private static AppPreference singletonPreference = null;
private SharedPreferences sp;
private Context context;
private AppPreference(Context context) {
if (context == null)
return;
this.context = context;
sp = context.getSharedPreferences(Constants.sharedPreference.PREFERENCE, 0);
}
public static AppPreference getInstance(Context context) {
if (singletonPreference == null)
singletonPreference = new AppPreference(context);
return singletonPreference;
}
public void clearOnlogout() {
Editor prefsEditor = sp.edit();
prefsEditor.clear();
prefsEditor.apply();
}
void removeData(String key) {
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
editor.apply();
}
public void setStringData(String pKey, String pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(pKey, pData);
editor.apply();
}
public void setBooleanData(String pKey, boolean pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(pKey, pData);
editor.apply();
}
void setIntegerData(String pKey, int pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putInt(pKey, pData);
editor.apply();
}
public String getStringData(String pKey) {
return sp.getString(pKey, "");
}
public boolean getBooleanData(String pKey) {
return sp.getBoolean(pKey, false);
}
public int getIntegerData(String pKey) {
return sp.getInt(pKey, 0);
}
public String getDeveloperPayload() {
return sp.getString(DEVELOPERPAYLOAD, "");
}
public void setDeveloperPayload(String developerPayload) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(DEVELOPERPAYLOAD, developerPayload);
editor.apply();
}
}
Happy coding :)

Related

How to send image as auto reply to Whatsapp in background?

I developed an android app for auto replying to Whatsapp. My app is perfect working for replying with text. But I am unable to send images in auto reply in background.
This activity is for managing notifications.
NotificationService.java
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.SpannableString;
import android.util.Log;
import android.widget.TextView;
import androidx.core.app.NotificationCompat;
import com.templatemela.whatsbot.model.Action;
import com.templatemela.whatsbot.model.AutoReply;
import com.templatemela.whatsbot.model.StatisticsReplyMsgListModel;
import com.templatemela.whatsbot.utilities.Const;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class NotificationService extends NotificationListenerService {
public static final String TAG = "Auto Reply";
private String autoReplyText;
private List<String> cntList;
private String contactType;
private long count = 0;
private List<String> getUserList;
private String headerText;
private String noMatch = "";
private SharedPreference preference;
private int replyTime;
private String sendMessage;
private TextView text;
private Uri string;
private Bitmap bitmap;
#Override
public void onListenerConnected() {
super.onListenerConnected();
Log.e(TAG, "Notification Listener Connected");
}
#Override
public void onCreate() {
super.onCreate();
preference = new SharedPreference(this);
count = preference.getFromPref_Long("Counter");
getUserList = new ArrayList();
cntList = new ArrayList();
Const.staticsReplyList = new ArrayList();
Const.contactList = new ArrayList();
}
#Override
public int onStartCommand(Intent intent, int i, int i2) {
Log.e("Service Class", "Service is started-----");
return Service.START_STICKY;
}
#Override
public void onNotificationRemoved(StatusBarNotification statusBarNotification) {
super.onNotificationRemoved(statusBarNotification);
Log.e("AUTO REPLY", "Notificationremoved");
}
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
if (preference.getFromPref_Boolean("CheckedState")) {
boolean fromPref_Boolean = preference.getFromPref_Boolean("ScheduleTime");
Log.e("scheduleTime", fromPref_Boolean + ":::");
contactType = preference.getFromPref_String("ContactType");
Const.contactList = preference.getContactList("ContactList");
try {
if (Const.contactList.isEmpty()) {
Const.contactList = new ArrayList();
}
} catch (Exception unused) {
Const.contactList = new ArrayList();
}
Const.replyList = preference.getList("MessageList");
try {
if (Const.replyList.isEmpty()) {
Const.replyList = new ArrayList();
}
} catch (Exception unused2) {
Const.replyList = new ArrayList();
}
Const.staticsReplyList = preference.getReplyList("StaticsReplyList");
try {
if (Const.staticsReplyList.isEmpty()) {
Const.staticsReplyList = new ArrayList();
}
} catch (Exception e) {
Const.staticsReplyList = new ArrayList();
Log.e("StaticsList", e.getMessage());
}
String fromPref_String = preference.getFromPref_String("BoldHeaderText");
if (fromPref_String.isEmpty()) {
headerText = "*Auto Reply*\n\n";
} else if (fromPref_String.equals(" ")) {
headerText = fromPref_String;
} else {
headerText = "*" + fromPref_String + "*\n\n";
}
autoReplyText = headerText + preference.getFromPref_String("autoReplyText");
if (isScheduleTime(fromPref_Boolean)) {
Log.e("IS SCHEDULE TIME", isScheduleTime(fromPref_Boolean) + "::::");
cancelNotification(statusBarNotification.getKey());
final Action quickReplyAction = NotificationUtils.getQuickReplyAction(statusBarNotification.getNotification(), getPackageName());
Log.e("Action", quickReplyAction + "::Action:");
if (quickReplyAction == null) {
return;
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")||statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b"))
{
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")&&preference.getFromPref_Boolean("WAState") ){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b")&&preference.getFromPref_Boolean("WBState")){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
}
else {
Log.e(TAG, "not success");
}
}
}
}
#Override
public void onTaskRemoved(Intent intent) {
super.onTaskRemoved(intent);
Intent intent2 = new Intent(getApplicationContext(), getClass());
intent2.setPackage(getPackageName());
startService(intent2);
}
public void sendMsg(Action action, String str, String str2, String tetStr, Bitmap image4) {
String str3;
String str4;
Intent phonebookIntent = new Intent();
image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
boolean z;
try {
Log.e("RECEIVE MSG", str);
Const.replyList.isEmpty();
boolean z2 = false;
boolean isContain=preference.getFromPref_Boolean("contain");
boolean isExtra=preference.getFromPref_Boolean("exact");
Log.e("rules","contain=="+String.valueOf(isContain)+" "+"exact==="+String.valueOf(isExtra));
boolean fromPref_Boolean = preference.getFromPref_Boolean("customAutoReplySwitch");
Log.e("CustomReply", fromPref_Boolean + ":::");
Iterator<AutoReply> it = Const.replyList.iterator();
while (true) {
if (!it.hasNext()) {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
break;
}
AutoReply next = it.next();
if (isContain?next.getReceiveMsg().equalsIgnoreCase(str)||str.contains(next.getReceiveMsg()):next.getReceiveMsg().equalsIgnoreCase(str)) {
if (fromPref_Boolean) {
long currentTimeMillis = System.currentTimeMillis();
Context applicationContext = getApplicationContext();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
action.sendReply(applicationContext, headerText + next.getSendMsg(), "okay kar", bitmap);
stopService(new Intent(getApplicationContext(), getClass()));
long j = count + 1;
count = j;
preference .addToPref_Long("Counter", j);
sendMessage = next.getSendMsg();
List<StatisticsReplyMsgListModel> list = Const.staticsReplyList;
str3 = "autoReplyText";
str4 = "Counter";
z = true;
StatisticsReplyMsgListModel statisticsReplyMsgListModel = new StatisticsReplyMsgListModel((int) count, next.getSendMsg(), str2, currentTimeMillis);
list.add(statisticsReplyMsgListModel);
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
} else {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
stopService(new Intent(getApplicationContext(), getClass()));
}
z2 = true;
}
}
if (!z2 && preference.getFromPref_Boolean("autoReplyTextSwitch") == z) {
Log.e(TAG, "Else");
if (autoReplyText.equals(str)) {
Log.e("Equal", "Message");
stopService(new Intent(getApplicationContext(), getClass()));
}
long currentTimeMillis2 = System.currentTimeMillis();
action.sendReply(getApplicationContext(), autoReplyText, "okay kar bhai", bitmap );
stopService(new Intent(getApplicationContext(), getClass()));
String str7 = str3;
sendMessage = preference.getFromPref_String(str7);
long j2 = count + 1;
count = j2;
preference.addToPref_Long(str4, j2);
Const.staticsReplyList.add(new StatisticsReplyMsgListModel((int) count, preference.getFromPref_String(str7), str2, currentTimeMillis2));
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") == z && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
}
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("Replied Message Error", e.getMessage());
}
}
private Intent getIntent() {
return null;
}
private boolean selfName(StatusBarNotification statusBarNotification) {
String title = NotificationUtils.getTitle(statusBarNotification);
return title == null || !title.equalsIgnoreCase(statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_SELF_DISPLAY_NAME));
}
private boolean isGroupMessageAndReplyAllowed(StatusBarNotification statusBarNotification) {
String titleRaw = NotificationUtils.getTitleRaw(statusBarNotification);
SpannableString valueOf = SpannableString.valueOf("" + statusBarNotification.getNotification().extras.get(NotificationCompat.EXTRA_TEXT));
boolean z = titleRaw != null && (": ".contains(titleRaw) || "# ".contains(titleRaw)) && valueOf != null && valueOf.toString().contains("📷");
if (!statusBarNotification.getNotification().extras.getBoolean(NotificationCompat.EXTRA_IS_GROUP_CONVERSATION)) {
return !z;
}
boolean fromPref_Boolean = preference.getFromPref_Boolean("GroupEnable");
Log.e("Group Message", "Return" + fromPref_Boolean);
return fromPref_Boolean;
}
private boolean EveryOne(String str) {
return str.equals("Everyone") || str.equals("");
}
private boolean ContactList(String str, String str2) {
return str.equals("ContactList") && Const.contactList.contains(str2);
}
private boolean ExceptContactList(String str, String str2) {
return str.equals("ExceptContList") && !Const.contactList.contains(str2);
}
#SuppressLint("Range")
private boolean ExceptPhoneList(String str, String str2) {
if (!str.equals("ExceptPhoneList")) {
return false;
}
Cursor query = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, (String[]) null, (String) null, (String[]) null, "display_name ASC");
while (query.moveToNext()) {
cntList.add(query.getString(query.getColumnIndex("display_name")));
}
query.close();
return !cntList.contains(str2);
}
private boolean isScheduleTime(boolean z) {
if (z) {
try {
Calendar instance = Calendar.getInstance();
String fromPref_String = preference.getFromPref_String("StartTime");
String fromPref_String2 = preference.getFromPref_String("EndTime");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
Date parse = simpleDateFormat.parse(simpleDateFormat.format(instance.getTime()));
Date parse2 = simpleDateFormat.parse(fromPref_String);
Date parse3 = simpleDateFormat.parse(fromPref_String2);
if (!parse.after(parse2) || !parse.before(parse3)) {
return false;
}
return true;
} catch (ParseException e) {
e.printStackTrace();
Log.e("CURRENTTIME", e.getMessage());
}
}
return true;
}
}
This is action activity that is sending reply in background.
Action.java
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import com.templatemela.whatsbot.NotificationService;
import com.templatemela.whatsbot.R;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Iterator;
public class Action implements Parcelable {
public static final Creator CREATOR = new Creator() {
public Action createFromParcel(Parcel parcel) {
return new Action(parcel);
}
public Action[] newArray(int i) {
return new Action[i];
}
};
private final boolean isQuickReply;
private final PendingIntent p;
private final String packageName;
private final ArrayList<RemoteInputParcel> remoteInputs;
private final String text;
private final Uri imageUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/AwakiFolder/" + "aifile" + ".jpeg");
public int describeContents() {
return 0;
}
public Action(Parcel parcel) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = parcel.readString();
packageName = parcel.readString();
p = (PendingIntent) parcel.readParcelable(PendingIntent.class.getClassLoader());
isQuickReply = parcel.readByte() != 0;
parcel.readTypedList(arrayList, RemoteInputParcel.CREATOR);
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(text);
parcel.writeString(packageName);
parcel.writeParcelable(p, i);
parcel.writeByte(isQuickReply ? (byte) 1 : 0);
parcel.writeTypedList(remoteInputs);
}
public Action(String str, String str2, PendingIntent pendingIntent, RemoteInput remoteInput, boolean z) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = str;
packageName = str2;
p = pendingIntent;
isQuickReply = z;
arrayList.add(new RemoteInputParcel(remoteInput));
}
public Action(NotificationCompat.Action action, String str, boolean z) {
remoteInputs = new ArrayList<>();
text = action.title.toString();
packageName = str;
p = action.actionIntent;
if (action.getRemoteInputs() != null) {
for (RemoteInput remoteInputParcel : action.getRemoteInputs()) {
remoteInputs.add(new RemoteInputParcel(remoteInputParcel));
}
}
isQuickReply = z;
}
public void sendReply(Context context, String str, String tetStr, Bitmap bitmap) throws PendingIntent.CanceledException {
Log.e("AutoReply", "inside sendReply");
Intent intent = new Intent();
Bundle bundle = new Bundle();
Bitmap image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
bundle.putParcelable( "image/png", image4);
String both = imageUri+ str + tetStr;
ArrayList arrayList = new ArrayList();
Iterator<RemoteInputParcel> it = remoteInputs.iterator();
while (it.hasNext()) {
RemoteInputParcel next = it.next();
Log.e("", "RemoteInput: " + next.getLabel());
intent.setAction(Intent.ACTION_SEND);
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
bundle.putCharSequence(next.getResultKey(), both);
RemoteInput.Builder builder = new RemoteInput.Builder(next.getResultKey());
builder.setLabel(next.getLabel());
builder.setChoices(next.getChoices());
builder.setAllowFreeFormInput(next.isAllowFreeFormInput());
builder.addExtras(next.getExtras());
arrayList.add(builder.build());
}
RemoteInput.addResultsToIntent((RemoteInput[]) arrayList.toArray(new RemoteInput[arrayList.size()]), intent, bundle);
p.send(context, 0, intent);
context.stopService(new Intent(context, NotificationService.class));
}
private Resources getResources() {
return null;
}
public ArrayList<RemoteInputParcel> getRemoteInputs() {
return remoteInputs;
}
public boolean isQuickReply() {
return isQuickReply;
}
public String getText() {
return text;
}
public PendingIntent getQuickReplyIntent() {
if (isQuickReply) {
return p;
}
return null;
}
public String getPackageName() {
return packageName;
}
}

How to get device location?

I am using openweathermap to parse weather information, it works fine without the city, but when I try to fetch city, it force closes. How do I fix this? been searching for hours but no luck.
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr
.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
public class Location implements Serializable {
private float longitude;
private float latitude;
private long sunset;
private long sunrise;
private String country;
private String city;
...
public String getCountry() {
return country;
}
public String getCity() {
return city;
}
here is my log-
FATAL EXCEPTION: main
Process: com.survivingwithandroid.weatherapp, PID: 2057
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.myweather.weatherapp.model.Location.getCity()' on a null object reference
at com.survivingwithandroid.weatherapp.MainActivity$JSONWeatherTask.onPostExecute(MainActivity.java:114)
UPDATE
JSONWeatherParser.java
package com.survivingwithandroid.weatherapp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.survivingwithandroid.weatherapp.model.Location;
import com.survivingwithandroid.weatherapp.model.Weather;
public class JSONWeatherParser {
public static Weather getWeather(String data) throws JSONException {
Weather weather = new Weather();
// We create out JSONObject from the data
JSONObject jObj = new JSONObject(data);
// We start extracting the info
Location loc = new Location();
JSONObject coordObj = getObject("coord", jObj);
loc.setLatitude(getFloat("lat", coordObj));
loc.setLongitude(getFloat("lon", coordObj));
JSONObject sysObj = getObject("sys", jObj);
loc.setCountry(getString("country", sysObj));
loc.setSunrise(getInt("sunrise", sysObj));
loc.setSunset(getInt("sunset", sysObj));
loc.setCity(getString("name", jObj));
weather.location = loc;
// We get weather info (This is an array)
JSONArray jArr = jObj.getJSONArray("weather");
// We use only the first value
JSONObject JSONWeather = jArr.getJSONObject(0);
weather.currentCondition.setWeatherId(getInt("id", JSONWeather));
weather.currentCondition.setDescr(getString("description", JSONWeather));
weather.currentCondition.setCondition(getString("main", JSONWeather));
weather.currentCondition.setIcon(getString("icon", JSONWeather));
JSONObject mainObj = getObject("main", jObj);
weather.currentCondition.setHumidity(getInt("humidity", mainObj));
weather.currentCondition.setPressure(getInt("pressure", mainObj));
weather.temperature.setMaxTemp(getFloat("temp_max", mainObj));
weather.temperature.setMinTemp(getFloat("temp_min", mainObj));
weather.temperature.setTemp(getFloat("temp", mainObj));
// Wind
JSONObject wObj = getObject("wind", jObj);
weather.wind.setSpeed(getFloat("speed", wObj));
weather.wind.setDeg(getFloat("deg", wObj));
// Clouds
JSONObject cObj = getObject("clouds", jObj);
weather.clouds.setPerc(getInt("all", cObj));
// We download the icon to show
return weather;
}
private static JSONObject getObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName);
return subObj;
}
private static String getString(String tagName, JSONObject jObj) throws JSONException {
return jObj.getString(tagName);
}
private static float getFloat(String tagName, JSONObject jObj) throws JSONException {
return (float) jObj.getDouble(tagName);
}
private static int getInt(String tagName, JSONObject jObj) throws JSONException {
return jObj.getInt(tagName);
}
}
MainActivity.java
package com.survivingwithandroid.weatherapp;
import org.json.JSONException;
import com.survivingwithandroid.weatherapp.model.Weather;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView hum;
private ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String city = "London,UK";
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[] { city });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr
.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
}
WeatherHttpClient.java
package com.survivingwithandroid.weatherapp;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherHttpClient {
private static String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q=";
private static String IMG_URL = "http://openweathermap.org/img/w/";
public String getWeatherData(String location) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(BASE_URL + location)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
// Let's read the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
is.close();
} catch (Throwable t) {
}
try {
con.disconnect();
} catch (Throwable t) {
}
}
return null;
}
public byte[] getImage(String code) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(IMG_URL + code)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
// Let's read the response
is = con.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (is.read(buffer) != -1)
baos.write(buffer);
return baos.toByteArray();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
is.close();
} catch (Throwable t) {
}
try {
con.disconnect();
} catch (Throwable t) {
}
}
return null;
}
}
Location.java
package com.survivingwithandroid.weatherapp.model;
import java.io.Serializable;
public class Location implements Serializable {
private float longitude;
private float latitude;
private long sunset;
private long sunrise;
private String country;
private String city;
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public long getSunset() {
return sunset;
}
public void setSunset(long sunset) {
this.sunset = sunset;
}
public long getSunrise() {
return sunrise;
}
public void setSunrise(long sunrise) {
this.sunrise = sunrise;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Weather.java
package com.survivingwithandroid.weatherapp.model;
public class Weather {
public Location location;
public CurrentCondition currentCondition = new CurrentCondition();
public Temperature temperature = new Temperature();
public Wind wind = new Wind();
public Rain rain = new Rain();
public Snow snow = new Snow();
public Clouds clouds = new Clouds();
public byte[] iconData;
public class CurrentCondition {
private int weatherId;
private String condition;
private String descr;
private String icon;
private float pressure;
private float humidity;
public int getWeatherId() {
return weatherId;
}
public void setWeatherId(int weatherId) {
this.weatherId = weatherId;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public float getHumidity() {
return humidity;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
}
public class Temperature {
private float temp;
private float minTemp;
private float maxTemp;
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getMinTemp() {
return minTemp;
}
public void setMinTemp(float minTemp) {
this.minTemp = minTemp;
}
public float getMaxTemp() {
return maxTemp;
}
public void setMaxTemp(float maxTemp) {
this.maxTemp = maxTemp;
}
}
public class Wind {
private float speed;
private float deg;
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public float getDeg() {
return deg;
}
public void setDeg(float deg) {
this.deg = deg;
}
}
public class Rain {
private String time;
private float ammount;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public float getAmmount() {
return ammount;
}
public void setAmmount(float ammount) {
this.ammount = ammount;
}
}
public class Snow {
private String time;
private float ammount;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public float getAmmount() {
return ammount;
}
public void setAmmount(float ammount) {
this.ammount = ammount;
}
}
public class Clouds {
private int perc;
public int getPerc() {
return perc;
}
public void setPerc(int perc) {
this.perc = perc;
}
}
}
Please find attached code for fetching location using LocationManager.
private GoogleApiClient mGoogleApiClient;
private Context mContext;
#SuppressWarnings({"MissingPermission"})
public void getLocation(Context context) {
mContext = context;
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
//Show message alert for gps enable
} else {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
}
After that, you will get callback on onConnected method and you get location from there
#Override
public void onConnected(#Nullable Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (location != null) {
double lat= location.getLatitude();
double lang= location.getLongitude());
} else {
//No location found message
}
mGoogleApiClient.disconnect();
}

how can i compare a json with < or >

I have a problem I want to compare my json but isn't work I don't understand why.
i try to use the fonction compareTo() but isn't work too. I want that
if (Myjson<5 or Myjson>5)
{ ( do something ) }
I show my code
Acceuil.java
public class Accueil extends AppCompatActivity {
String json_string;
JSONObject jObj = null;
private TextView Mpx,Al,Ar,Rds,Pilots,Frequence,Rf;
private String value= String.valueOf(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
json_string = getIntent().getExtras().getString("json_data");
Mpx = (TextView) findViewById(R.id.mpx);
Ar=(TextView)findViewById(R.id.ar);
Al=(TextView)findViewById(R.id.al);
Rds=(TextView)findViewById(R.id.rds);
Pilots=(TextView)findViewById(R.id.pilots);
Frequence=(TextView)findViewById(R.id.fréquence);
Rf=(TextView)findViewById(R.id.rf);
try {
// Json Object {}
/******************************************************************************/
String mpx, rds, al, ar, frequence, pilots, id, id_SIGFOX, timestamps, rf;
jObj = new JSONObject(json_string);
mpx = jObj.getString("MPX");
rds = jObj.getString("RDS");
rf = jObj.getString("RF");
frequence = jObj.getString("Frequence");
timestamps = jObj.getString("timestamp");
id = jObj.getString("id");
id_SIGFOX = jObj.getString("id_SIGFOX");
pilots = jObj.getString("PILOT");
al = jObj.getString("a_l");
ar = jObj.getString("a_r");
Valeur valeurs = new Valeur(mpx, rds, al, ar, frequence, pilots, id, timestamps, id_SIGFOX, rf);
/******************************************************************************/
if(mpx.compareTo(String.valueOf(5))) {
Mpx.setText(valeurs.getMpx())
Mpx.setText(valeurs.getMpx());
Mpx.setTextColor(Color.parseColor("#00000"))
}else{
Mpx.setText(valeurs.getMpx())
Mpx.setTextColor(Color.parseColor("#DF0101"))};//red
} catch (JSONException e) {
e.printStackTrace();
}
}
public void popUp(View view){
Intent intent=new Intent(this,popUp.class);
startActivity(intent);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.warning:
Intent intent = new Intent(this, popUp.class);
startActivity(intent);
return true;
case R.id.localiser:
return true;
case R.id.station:
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//ajoute les entrées de menu_test à l'ActionBar
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
Valeur.java
public class Valeur {
private String mpx,rds,al,ar,pilots,frequence,id,timestamps,id_SIGFOX,rf;
public Valeur(String mpx, String rds, String al, String ar, String pilots, String frequence, String id, String timestamps, String id_SIGFOX, String rf)
{
this.setMpx(mpx);
this.setRds(rds);
this.setAl(al);
this.setAr(ar);
this.setPilots(pilots);
this.setFrequence(frequence);
this.setId(id);
this.setTimestamps(timestamps);
this.setId_SIGFOX(id_SIGFOX);
this.setRf(rf);
}
public String getMpx() {
return mpx;
}
public void setMpx(String mpx) {
this.mpx = mpx;
}
public String getRds() {
return rds;
}
public void setRds(String rds) {
this.rds = rds;
}
public String getAl() {
return al;
}
public void setAl(String al) {
this.al = al;
}
public String getAr() {
return ar;
}
public void setAr(String ar) {
this.ar = ar;
}
public String getPilots() {
return pilots;
}
public void setPilots(String pilots) {
this.pilots = pilots;
}
public String getFrequence() {
return frequence;
}
public void setFrequence(String frequence) {
this.frequence = frequence;
}
public String getTimestamps() {
return timestamps;
}
public void setTimestamps(String timestamps) {
this.timestamps = timestamps;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getId_SIGFOX() {
return id_SIGFOX;
}
public void setId_SIGFOX(String id_SIGFOX) {
this.id_SIGFOX = id_SIGFOX;
}
public String getRf() {
return rf;
}
public void setRf(String rf) {
this.rf = rf;
}
}
my flux json
{"id":"1","timestamp":"2017-01-31 10:59:11","id_SIGFOX":"ABER","MPX":"1","RDS":"2","RF":"79","PILOT":"8","a_l":"-5","a_r":"-39","Frequence":"1034"}
Do as follow:
int mpxInt = Integer.parseInt(mpx);
if(mpxInt > 5) {
// mpx is > 5
} else {
// mpx is < 5
}
This should works fine
I think the problem is you try to compare the String in mpx with the integer 5.
mpx = jObj.getString("MPX");
...
if(mpx.compareTo(String.valueOf(5))) {
To do this correctly, you need to convert mpx to int. Either use something else than jObj.getString, or use Integer.parseInt to convert the string to an int.

Qr scanner scanned result in fragment

I am beginner to android..I integrated qr scanner ZXING library in my app..in fragment layout..this library working..On click button..qr scanner is opening..but scanned result is not displaying inside edit text in fragment layout..how to display result in fragment?
below is my On click button code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = null;
view = inflater.inflate(R.layout.configure_switch,container,false);
button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.initiateScan();
}
});
it's simple. after getting scanned result, you need to put the following code.
YourEditTextName.setText(ResultText);
look as my related answer here,
[ https://stackoverflow.com/a/36788367/3981656 ]
here is the full code,
MainActivity.java
package futurevision.jsk.barcodesanner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.scan_button){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
IntentIntegrator.java
package com.google.zxing.integration.android;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(
BS_PACKAGE, // Barcode Scanner
BSPLUS_PACKAGE, // Barcode Scanner+
BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String,Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String,Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String,?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApplications.contains(packageName)) {
return packageName;
}
}
}
return null;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String,Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
IntentResult.java
package com.google.zxing.integration.android;
public final class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
public String getContents() {
return contents;
}
public String getFormatName() {
return formatName;
}
public byte[] getRawBytes() {
return rawBytes;
}
public Integer getOrientation() {
return orientation;
}
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
#Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
Happy coding.!!!
when you receive the result to a activity get the current fragment and call that method like below
CustomFragmentClass will be your fragment.
Fragment fragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof CustomFragmentClass){
fragment.onActivityResult(int requestCode, int resultCode, Intent data);
}
or you can also refer this onActivityResult is not being called in Fragment

Android, Best way to populate Endless List View's data with Retrofit?

I've success to populate data into listview, but my way seems very bad because when i scroll the list view, the retrofit always get All the Repository. So, what is the best way to populate Endless List view's data with retrofit ? Thanks ...
MainActivity.java
public class MainActivity extends Activity {
public static final String ENDPOINT = "http://rfhan.com";
private List<Tempat> tempatList;
private TempatAdapter tadapter;
private EndlessListView lv;
private int start=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempatList = new ArrayList<Tempat>();
tadapter = new TempatAdapter(this, R.layout.item_tempat, tempatList);
lv = (EndlessListView) findViewById(R.id.el);
lv.setLoadingView(R.layout.loading_layout);
lv.setAdapter(tadapter);
//init data to my list
requestData();
//scroll listener
lv.setListener(new EndlessListener() {
#Override
public void loadData() {
requestData();
}
});
}
private void requestData(){
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.build();
TempatAPI api = adapter.create(TempatAPI.class);
api.getAllData(new Callback<List<Tempat>>() {
//here the problem
#Override
public void success(List<Tempat> data, Response arg1) {
updateData(data);
}
#Override
public void failure(RetrofitError arg0) {
Toast.makeText(MainActivity.this, "Retrofit Error!", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, arg0+"", Toast.LENGTH_LONG).show();
}
});
}
//the tmpt list is contain all Tempat's data
//code below is to get some tmpt's data into new Arraylist
//and update the adapter's data
//it's work but seems bad way
private void updateData(List<Tempat> tmpt){
tempatList = new ArrayList<Tempat>();
start+=10;
for(int i=start-10;(i<start&&start<tmpt.size());i++)
tempatList.add(tmpt.get(i));
lv.addNewData(tempatList);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Model Tempat.java
import java.math.BigInteger;
import android.graphics.Bitmap;
public class Tempat {
BigInteger idkoleksi;
String nama;
String kategori;
String alamat;
String notelp;
String jambuka;
String jamtutup;
String harga;
String imageHeaderURL;
double latitude;
double longitude;
int jumlahview;
int jumlatrate;
double rating;
String tanggal;
Bitmap bitmap;
public BigInteger getIdkoleksi() {
return idkoleksi;
}
public String getNama() {
return nama;
}
public String getKategori() {
return kategori;
}
public String getAlamat() {
return alamat;
}
public String getNotelp() {
return notelp;
}
public String getJambuka() {
return jambuka;
}
public String getJamtutup() {
return jamtutup;
}
public String getHarga() {
return harga;
}
public String getImageHeaderURL() {
return imageHeaderURL;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public int getJumlahview() {
return jumlahview;
}
public int getJumlatrate() {
return jumlatrate;
}
public double getRating() {
return rating;
}
public String getTanggal() {
return tanggal;
}
public void setIdkoleksi(BigInteger idkoleksi) {
this.idkoleksi = idkoleksi;
}
public void setNama(String nama) {
this.nama = nama;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public void setNotelp(String notelp) {
this.notelp = notelp;
}
public void setJambuka(String jambuka) {
this.jambuka = jambuka;
}
public void setJamtutup(String jamtutup) {
this.jamtutup = jamtutup;
}
public void setHarga(String harga) {
this.harga = harga;
}
public void setImageHeaderURL(String imageHeaderURL) {
this.imageHeaderURL = imageHeaderURL;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public void setJumlahview(int jumlahview) {
this.jumlahview = jumlahview;
}
public void setJumlatrate(int jumlatrate) {
this.jumlatrate = jumlatrate;
}
public void setRating(double rating) {
this.rating = rating;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
Repository TempatAPI.java
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
public interface TempatAPI {
#GET("api/tempat/get_all_data.php")
public void getAllData(Callback<List<Tempat>> response);
}
Webservice API get_all_data.php
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$nama=$_GET["nama"];
$query = "SELECT DataKoleksi.* , DataStatistikKoleksi.* FROM DataKoleksi, DataStatistikKoleksi WHERE DataKoleksi.idkoleksi = DataStatistikKoleksi.idkoleksi";
$result = mysql_query($query) or die(mysql_error());
$response = array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$koleksi = array();
$koleksi["idkoleksi"] = $row["idkoleksi"];
$koleksi["nama"] = $row["nama"];
$koleksi["kategori"] = $row["kategori"];
$koleksi["alamat"] = $row["alamat"];
$koleksi["notelp"] = $row["notelp"];
$koleksi["jambuka"] = $row["jambuka"];
$koleksi["jamtutup"] = $row["jamtutup"];
$koleksi["harga"] = $row["harga"];
$koleksi["imageHeaderURL"] = $row["imageHeaderURL"];
$koleksi["latitude"] = $row["latitude"];
$koleksi["longitude"] = $row["longitude"];
$koleksi["jumlahview"] = $row["jumlahview"];
$koleksi["jumlahrate"] = $row["jumlahrate"];
$koleksi["rating"] = $row["rating"];
$koleksi["tanggal"] = $row["tanggal"];
array_push($response, $koleksi);
}
echo json_encode($response);
} else {
// no found
echo json_encode($response);
}
?>
You need to add a listener to your listview to see if you have scrolled to the end of the list. In my example below, we check if we have reached the end of the list and if we have, we try to load 10 more items. The listview is then updated.
lvEvents.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {}
#Override
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = firstVisible + visibleCount >= totalCount;
if (loadMore && !isLoadingEvents && futureEvents.size() >= 10 && !noMoreEvents) {
Log.d(TAG, "LOADING MORE EVENTS");
isLoadingEvents = true;
networkManager.getTenMoreEvents(getActivity(), new NetworkManager.Request() {
#Override
public void finished() {
updateEventsFeed();
isLoadingEvents = false;
}
});
}
}
});

Categories

Resources