Qr scanner scanned result in fragment - java

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

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 can I save user messages and history to room database

I am developing a chat app and I want to save user chat history and messages using room database. By this, when the users start the app they can see their previous history and messages.
Below my User.java model class where implemented user model properties.
#Entity
public class User implements IChatUser {
#PrimaryKey(autoGenerate = true)
private Integer id;
#ColumnInfo(name = "name")
String name;
#Ignore
Bitmap icon;
public User() {
}
public User(int id, String name, Bitmap icon) {
this.id = id;
this.name = name;
this.icon = icon;
}
#Override
public String getId() {
return this.id.toString();
}
#Override
public String getName() {
return this.name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
#Override
public Bitmap getIcon() {
return this.icon;
}
#Override
public void setIcon(Bitmap icon) {
this.icon = icon;
}
}
UserDao.java
#Dao
public interface UserDao {
#Query("SELECT * FROM user")
List<User> getUsers();
#Insert
void insert(User user);
#Delete
void delete(User user);
#Update
void update(User user);
}
UserRoomDatabase.java
#Database(entities = {User.class}, version = 1)
public abstract class UserRoomDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
MessengerActivity.java
public class MessengerActivity extends Activity{
#VisibleForTesting
protected static final int RIGHT_BUBBLE_COLOR = R.color.colorPrimaryDark;
#VisibleForTesting
protected static final int LEFT_BUBBLE_COLOR = R.color.gray300;
#VisibleForTesting
protected static final int BACKGROUND_COLOR = R.color.blueGray400;
#VisibleForTesting
protected static final int SEND_BUTTON_COLOR = R.color.blueGray500;
#VisibleForTesting
protected static final int SEND_ICON = R.drawable.ic_action_send;
#VisibleForTesting
protected static final int OPTION_BUTTON_COLOR = R.color.teal500;
#VisibleForTesting
protected static final int RIGHT_MESSAGE_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int LEFT_MESSAGE_TEXT_COLOR = Color.BLACK;
#VisibleForTesting
protected static final int USERNAME_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int SEND_TIME_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int DATA_SEPARATOR_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int MESSAGE_STATUS_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final String INPUT_TEXT_HINT = "New message..";
#VisibleForTesting
protected static final int MESSAGE_MARGIN = 5;
private ChatView mChatView;
private MessageList mMessageList;
private ArrayList<User> mUsers;
private int mReplyDelay = -1;
Realm realm;
private static final int READ_REQUEST_CODE = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messenger);
initUsers();
mChatView = findViewById(R.id.chat_view);
//Load saved messages
loadMessages(realm);
//Set UI parameters if you need
mChatView.setRightBubbleColor(ContextCompat.getColor(this,RIGHT_BUBBLE_COLOR));
mChatView.setLeftBubbleColor(ContextCompat.getColor(this, LEFT_BUBBLE_COLOR));
mChatView.setBackgroundColor(ContextCompat.getColor(this, BACKGROUND_COLOR));
mChatView.setSendButtonColor(ContextCompat.getColor(this, SEND_BUTTON_COLOR));
mChatView.setSendIcon(SEND_ICON);
mChatView.setOptionIcon(R.drawable.ic_account_circle);
mChatView.setOptionButtonColor(OPTION_BUTTON_COLOR);
mChatView.setRightMessageTextColor(RIGHT_MESSAGE_TEXT_COLOR);
mChatView.setLeftMessageTextColor(LEFT_MESSAGE_TEXT_COLOR);
mChatView.setUsernameTextColor(USERNAME_TEXT_COLOR);
mChatView.setSendTimeTextColor(SEND_TIME_TEXT_COLOR);
mChatView.setDateSeparatorColor(DATA_SEPARATOR_COLOR);
mChatView.setMessageStatusTextColor(MESSAGE_STATUS_TEXT_COLOR);
mChatView.setInputTextHint(INPUT_TEXT_HINT);
mChatView.setMessageMarginTop(MESSAGE_MARGIN);
mChatView.setMessageMarginBottom(MESSAGE_MARGIN);
mChatView.setMaxInputLine(5);
mChatView.setUsernameFontSize(getResources().getDimension(R.dimen.font_small));
mChatView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
mChatView.setInputTextColor(ContextCompat.getColor(this, R.color.red500));
mChatView.setInputTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
mChatView.setOnBubbleClickListener(new Message.OnBubbleClickListener() {
#Override
public void onClick(Message message) {
mChatView.updateMessageStatus(message, MyMessageStatusFormatter.STATUS_SEEN);
Toast.makeText(
MessengerActivity.this,
"click : " + message.getUser().getName() + " - " + message.getText(),
Toast.LENGTH_SHORT
).show();
}
});
mChatView.setOnIconClickListener(new Message.OnIconClickListener() {
#Override
public void onIconClick(Message message) {
Toast.makeText(
MessengerActivity.this,
"click : icon " + message.getUser().getName(),
Toast.LENGTH_SHORT
).show();
}
});
mChatView.setOnIconLongClickListener(new Message.OnIconLongClickListener() {
#Override
public void onIconLongClick(Message message) {
Toast.makeText(
MessengerActivity.this,
"Removed this message \n" + message.getText(),
Toast.LENGTH_SHORT
).show();
mChatView.getMessageView().remove(message);
}
});
//Click Send Button
mChatView.setOnClickSendButtonListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initUsers();
//new message
Message message = new Message.Builder()
.setUser(mUsers.get(0))
.setRight(true)
.setText(mChatView.getInputText())
.hideIcon(true)
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusTextFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
//Set to chat view
mChatView.send(message);
//Add message list
mMessageList.add(message);
//Reset edit text
mChatView.setInputText("");
receiveMessage(message.getText());
}
});
//Click option button
mChatView.setOnClickOptionButtonListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
}
private void openGallery() {
Intent intent;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
private void receiveMessage(String sendText) {
//Ignore hey
if (!sendText.contains("hey")) {
//Receive message
final Message receivedMessage = new Message.Builder()
.setUser(mUsers.get(1))
.setRight(false)
.setText(ChatBot.INSTANCE.talk(mUsers.get(0).getName(), sendText))
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusTextFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
if (sendText.equals( Message.Type.PICTURE.name())) {
receivedMessage.setText("Nice!");
}
// This is a demo bot
// Return within 3 seconds
if (mReplyDelay < 0) {
mReplyDelay = (new Random().nextInt(4) + 1) * 1000;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mChatView.receive(receivedMessage);
//Add message list
mMessageList.add(receivedMessage);
}
}, mReplyDelay);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != READ_REQUEST_CODE || resultCode != RESULT_OK || data == null) {
return;
}
Uri uri = data.getData();
try {
Bitmap picture = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Message message = new Message.Builder()
.setRight(true)
.setText(Message.Type.PICTURE.name())
.setUser(mUsers.get(0))
.hideIcon(true)
.setPicture(picture)
.setType(Message.Type.PICTURE)
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
mChatView.send(message);
//Add message list
mMessageList.add(message);
receiveMessage(Message.Type.PICTURE.name());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.error), Toast.LENGTH_SHORT).show();
}
}
private void initUsers() {
mUsers = new ArrayList<>();
//User id
int myId = 0;
//User icon
Bitmap myIcon = BitmapFactory.decodeResource(getResources(), R.drawable.face_2);
//User name
String myName = "Michael";
int yourId = 1;
Bitmap yourIcon = BitmapFactory.decodeResource(getResources(), R.drawable.face_1);
String yourName = "Emily";
final User me = new User(myId, myName, myIcon);
final User you = new User(yourId, yourName, yourIcon);
mUsers.add(me);
mUsers.add(you);
}
/**
* Load saved messages
* #param realm
*/
private void loadMessages(Realm realm) {
List<Message> messages = new ArrayList<>();
mMessageList = AppData.getMessageList(this);
if (mMessageList == null) {
mMessageList = new MessageList();
} else {
for (int i = 0; i < mMessageList.size(); i++) {
Message message = mMessageList.get(i);
//Set extra info because they were removed before save messages.
for (IChatUser user : mUsers) {
if (message.getUser().getId().equals(user.getId())) {
message.getUser().setIcon(user.getIcon());
}
}
if (!message.isDateCell() && message.isRight()) {
message.hideIcon(true);
}
message.setStatusStyle(Message.Companion.getSTATUS_ICON_RIGHT_ONLY());
message.setStatusIconFormatter(new MyMessageStatusFormatter(this));
message.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED);
messages.add(message);
}
}
MessageView messageView = mChatView.getMessageView();
messageView.init(messages);
messageView.setSelection(messageView.getCount() - 1);
}
#Override
public void onResume() {
super.onResume();
initUsers();
}
#Override
public void onPause() {
super.onPause();
//Save message
mMessageList = new MessageList();
mMessageList.setMessages(mChatView.getMessageView().getMessageList());
AppData.putMessageList(this, mMessageList);
}
#VisibleForTesting
public ArrayList<User> getUsers() {
return mUsers;
}
public void setReplyDelay(int replyDelay) {
mReplyDelay = replyDelay;
}
private void showDialog() {
final String[] items = {
getString(R.string.send_picture),
getString(R.string.clear_messages)
};
new AlertDialog.Builder(this)
.setTitle(getString(R.string.options))
.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position) {
switch (position) {
case 0 :
openGallery();
break;
case 1:
mChatView.getMessageView().removeAll();
break;
}
}
})
.show();
}
}
You should create a new room database to store your messages. It's table should look like this:
id
message
sendingUser
receivingUser
0
Hello how are you?
John
David
1
Thanks, im good.
David
John
2
good to hear that!
John
David
First create a new Message class. This class should look like this:
#Entity(tableName = "message_table")
data class Message(
#PrimaryKey(autoGenerate = true)
var id: Int,
#ColumnInfo(name= "message")
var message: String,
#ColumnInfo(name = "sendingUser")
var sendingUser: String,
#ColumnInfo(name = "receivingUser")
var receivingUser: String
)
Then create your MessageDatabase, like this:
#Database(entities = [Message::class], version = 1)
abstract class MessageDatabase: RoomDatabase() {
abstract fun messageDao(): MessageDao
}
Next create your MessageDao
#Dao
interface MessageDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(message: Message)
#Query("SELECT ALL * FROM message_table WHERE sendingUser= :sendingUser")
suspend fun getMessageListFromSender(sendingUser: String): MutableList<Message>
#Query("SELECT ALL * FROM message_table")
suspend fun getMessageList(): MutableList<Message>
#Delete
suspend fun delete(message: Message)
#Update
suspend fun update(message: Message)
}
At last you can initialize your room database like this:
private val roomDb = Room.databaseBuilder(
getApplication(),
MessageDatabase::class.java, "message_database"
).build()
private val messageDao = roomDb.messageDao()
Use messageDao, to make operations with the database, this example shows you how to get message list from a certain sender:
suspend fun getMessageListFromSender(sendingUser: String): MutableList<Message> {
var list : MutableList<Message>
with (messageDao) {
list = this.getMessageListFromSender(sendingUser)
}
return list
}
viewModelScope.launch {
getMessageListFromSender("John")
}

In App Purchases - How to handle the second click?

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 :)

Variable is not reflecting the assigned value while working with retrofit library: Android

I am trying to get the photo of the day from bing using this url
http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US
I am having trouble saving the value of the url which i am getting through retrofit library.
This is my code:
MainActivity.class
package com.gadgetsaint.downloadmanagerexample;
import android.Manifest;
import android.app.DownloadManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
private DownloadManager downloadManager;
private long refid;
private Uri Download_Uri;
String url,name;
ArrayList<Long> list = new ArrayList<>();
ApiInterface apiService;
TextView btnSingle ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiService=ApiClient.getClient().create(ApiInterface.class);
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
getImageUrl();
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//url is showing null value even after assigning the data obtained through json .
Download_Uri = Uri.parse(url);
btnSingle = (TextView) findViewById(R.id.single);
btnSingle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Abhishek Adhikari's file Downloading " + name + ".png");
request.setDescription("Downloading " + name + ".jpg");
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.getExternalStorageState(), "/adhikariabhishek/" + "/" + name + ".jpg");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
list.add(refid);
}
});
// TextView btnMultiple = (TextView) findViewById(R.id.multiple);
if(!isStoragePermissionGranted())
{
}
/* btnMultiple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
for(int i = 0; i < 2; i++)
{
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("GadgetSaint Downloading " + "Sample_" + i + ".png");
request.setDescription("Downloading " + "Sample_" + i + ".png");
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/GadgetSaint/" + "/" + "Sample_" + i + ".png");
refid = downloadManager.enqueue(request);
Log.e("OUTNM", "" + refid);
list.add(refid);
}
}
});
*/
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Log.e("IN", "" + referenceId);
list.remove(referenceId);
if (list.isEmpty())
{
Log.e("INSIDE", "" + referenceId);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FileDownloader")
.setContentText("All Download completed");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(455, mBuilder.build());
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
// permission granted
}
}
private void getImageUrl() {
Call<ImageModel> call = apiService.getImageDetails("js","0","1","en-US");
call.enqueue(new Callback<ImageModel>() {
#Override
public void onResponse(Response<ImageModel> response, Retrofit retrofit) {
try {
Toast.makeText(MainActivity.this, "inside onresponse()", Toast.LENGTH_SHORT).show();
url=response.body().getImages().get(0).getUrl().toString();
//Here variable "url" is showing the data obtained through json
// but not reflecting changes back in "oncreate" method when used with variable "Download_uri"
Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Cannot download the image", Toast.LENGTH_SHORT).show();
}
});
}
#Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
public void onMessage(String url){
Toast.makeText(MainActivity.this, "inside Eventbus : "+url+" ", Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
ApiInterface.class
package com.gadgetsaint.downloadmanagerexample;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface ApiInterface {
#GET("HPImageArchive.aspx")
Call<ImageModel> getImageDetails(#Query("format") String format,
#Query("idx") String idx, #Query("n") String n, #Query("mkt") String
mkt);
}
ApiClient.class
package com.gadgetsaint.downloadmanagerexample;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class ApiClient {
public static final String BASE_URL = "http://www.bing.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ImageModel.class
package com.gadgetsaint.downloadmanagerexample;
import java.util.List;
public class ImageModel {
/**
* images : [{"startdate":"20170920","fullstartdate":"201709200700","enddate":"20170921","url":"/az/hprichbg/rb/RotenbergVineyards_EN-US11270850012_1920x1080.jpg","urlbase":"/az/hprichbg/rb/RotenbergVineyards_EN-US11270850012","copyright":"Vineyards at Rotenberg in Baden-Württemberg, Germany (© Werner Dieterich/plainpicture)","copyrightlink":"http://www.bing.com/search?q=rotenberg+stuttgart&form=hpcapt&filters=HpDate:%2220170920_0700%22","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20170920_RotenbergVineyards%22&FORM=HPQUIZ","wp":true,"hsh":"0b5b6af9429a1f1e53c494ee482c73bc","drk":1,"top":1,"bot":1,"hs":[]}]
* tooltips : {"loading":"Loading...","previous":"Previous image","next":"Next image","walle":"This image is not available to download as wallpaper.","walls":"Download this image. Use of this image is restricted to wallpaper only."}
*/
private TooltipsBean tooltips;
private List<ImagesBean> images;
public TooltipsBean getTooltips() {
return tooltips;
}
public void setTooltips(TooltipsBean tooltips) {
this.tooltips = tooltips;
}
public List<ImagesBean> getImages() {
return images;
}
public void setImages(List<ImagesBean> images) {
this.images = images;
}
public static class TooltipsBean {
/**
* loading : Loading...
* previous : Previous image
* next : Next image
* walle : This image is not available to download as wallpaper.
* walls : Download this image. Use of this image is restricted to wallpaper only.
*/
private String loading;
private String previous;
private String next;
private String walle;
private String walls;
public String getLoading() {
return loading;
}
public void setLoading(String loading) {
this.loading = loading;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public String getWalle() {
return walle;
}
public void setWalle(String walle) {
this.walle = walle;
}
public String getWalls() {
return walls;
}
public void setWalls(String walls) {
this.walls = walls;
}
}
public static class ImagesBean {
/**
* startdate : 20170920
* fullstartdate : 201709200700
* enddate : 20170921
* url : /az/hprichbg/rb/RotenbergVineyards_EN-US11270850012_1920x1080.jpg
* urlbase : /az/hprichbg/rb/RotenbergVineyards_EN-US11270850012
* copyright : Vineyards at Rotenberg in Baden-Württemberg, Germany (© Werner Dieterich/plainpicture)
* copyrightlink : http://www.bing.com/search?q=rotenberg+stuttgart&form=hpcapt&filters=HpDate:%2220170920_0700%22
* quiz : /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20170920_RotenbergVineyards%22&FORM=HPQUIZ
* wp : true
* hsh : 0b5b6af9429a1f1e53c494ee482c73bc
* drk : 1
* top : 1
* bot : 1
* hs : []
*/
private String startdate;
private String fullstartdate;
private String enddate;
private String url;
private String urlbase;
private String copyright;
private String copyrightlink;
private String quiz;
private boolean wp;
private String hsh;
private int drk;
private int top;
private int bot;
private List<?> hs;
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getFullstartdate() {
return fullstartdate;
}
public void setFullstartdate(String fullstartdate) {
this.fullstartdate = fullstartdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlbase() {
return urlbase;
}
public void setUrlbase(String urlbase) {
this.urlbase = urlbase;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCopyrightlink() {
return copyrightlink;
}
public void setCopyrightlink(String copyrightlink) {
this.copyrightlink = copyrightlink;
}
public String getQuiz() {
return quiz;
}
public void setQuiz(String quiz) {
this.quiz = quiz;
}
public boolean isWp() {
return wp;
}
public void setWp(boolean wp) {
this.wp = wp;
}
public String getHsh() {
return hsh;
}
public void setHsh(String hsh) {
this.hsh = hsh;
}
public int getDrk() {
return drk;
}
public void setDrk(int drk) {
this.drk = drk;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getBot() {
return bot;
}
public void setBot(int bot) {
this.bot = bot;
}
public List<?> getHs() {
return hs;
}
public void setHs(List<?> hs) {
this.hs = hs;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.gadgetsaint.downloadmanagerexample.MainActivity">
<TextView
android:id="#+id/single"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#fff"
android:padding="20dp"
android:background="#ce3910"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download single file" />
</RelativeLayout>
There is some trouble with the getImageUrl() method in MainActivity.class.
Help me out guys!!
Replace your getImageUrl() like this
private String getImageUrl() {
String imurl;
Call<ImageModel> call = apiService.getImageDetails("js","0","1","en-US");
call.enqueue(new Callback<ImageModel>() {
#Override
public void onResponse(Response<ImageModel> response, Retrofit retrofit) {
try {
Toast.makeText(MainActivity.this, "inside onresponse()", Toast.LENGTH_SHORT).show();
imurl=response.body().getImages().get(0).getUrl().toString();
//Here variable "url" is showing the data obtained through json
// but not reflecting changes back in "oncreate" method when used with variable "Download_uri"
Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Cannot download the image", Toast.LENGTH_SHORT).show();
}
});
return imurl;
}
and in oncreate change,
Download_Uri = Uri.parse(url);
by this
Download_Uri = Uri.parse(getImageUrl());

Util Class in Java

I want to know about the util Class used in Java. I am currently working on one Application in Android where I need to used a class from one file to another different file. I was told to import it like import com.android.utli.(ClassName) here the "com.android.util" is a package name.
Can I use that class in my another file simply by importing the package along with the class name?
Yes. After you import the class at the top of your java file like:
import android.util.Log;
You can then use it in your code.
Log.debug("MyActivity", "Thing I want to log");
The package is really a part of the "fully qualified class name". You can actually use that fully qualified name everywhere you use the class name, e.g.
com.android.util.UtilClass myUtil = new com.android.util.UtilClass();
But that's rather inconvenient. Therefore, classes in the same package (and in the package java.lang) can be used shorthand (i.e. only the class name) without imports. Classes from other packages have to be imported before they can be used that way.
It's just a way to organize the code and prevent problems when different programmers write classes with the same name - as long as they are in different packages, the collision can always be resolved by using the fully qualified class name.
public class SelectionListAdapter extends BaseAdapter {
private static final String TAG = SelectionListAdapter.class.getSimpleName();
private static LayoutInflater inflater = null;
// ArrayList<Selection> selections;
ArrayList<MultiSelection> multiselections;
ArrayList<MultiSelection> multiselectionsTemp;
Context mContext;
ArrayList<String> arrSelectedIDs;
ArrayList<String> arrSelectedNames;
String type;
public SelectionListAdapter(Activity ctx, ArrayList<MultiSelection> multiselections, String type) {
mContext = ctx;
inflater = (LayoutInflater) mContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.selections = selections;
this.multiselections = multiselections;
this.multiselectionsTemp = new ArrayList<>();
multiselectionsTemp.addAll(multiselections);
arrSelectedIDs = new ArrayList<>();
arrSelectedNames = new ArrayList<>();
this.type = type;
}
public int getCount() {
return multiselections.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.selection_list_row, null);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_item.setText(multiselections.get(i).name);
final MultiSelection multiSelection = multiselections.get(i);
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.chacked);
if (!arrSelectedIDs.contains(multiSelection.id.trim()))
arrSelectedIDs.add(multiSelection.id.trim());
if (!arrSelectedNames.contains(multiSelection.name.trim()))
arrSelectedNames.add(multiSelection.name);
} else {
holder.check.setBackgroundResource(R.drawable.unchacked);
}
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.unchacked);
arrSelectedIDs.remove(multiSelection.id.trim());
arrSelectedNames.remove(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = false;
} else {
holder.check.setBackgroundResource(R.drawable.chacked);
arrSelectedIDs.add(multiSelection.id.trim());
arrSelectedNames.add(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = true;
}
}
});
return view;
}
public class ViewHolder {
#InjectView(R.id.txt_item)
TextView txt_item;
#InjectView(R.id.check)
ImageView check;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
multiselections.clear();
if (charText.length() == 0) {
multiselections.addAll(multiselectionsTemp);
} else {
for (MultiSelection wp : multiselectionsTemp) {
if (wp.name.toLowerCase(Locale.getDefault())
.contains(charText)) {
multiselections.add(wp);
}
}
}
notifyDataSetChanged();
}
}
public boolean isChecked;
private SwipeRefreshLayout swipeRefreshLayout;
implements SwipeRefreshLayout.OnRefreshListener
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setProgressBackgroundColor(R.color.colorPrimary);
swipeRefreshLayout.setColorSchemeColors(getActivity().getResources().getColor(R.color.color_white));
// swipeRefreshLayout.post(new Runnable()
// {
// #Override
// public void run()
// {
// swipeRefreshLayout.setRefreshing(true);
// }
// });
swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setRefreshing(false); // not call
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
if (Utils.isInternetConnected(getActivity())) {
getNearbyUserList();
} else {
MDToast mdToast = MDToast.makeText(getActivity(), "Please check the internet connection.",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
**Connection Detector Class**
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
}
return false;
}
public boolean connectionDetected()
{
if (isConnectingToInternet(context)) {
return true;
} else {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.connection_checker);
dialog.setCancelable(false);
dialog.show();
Button ok = (Button) dialog.findViewById(R.id.dialog_ok);
Button cancel = (Button) dialog.findViewById(R.id.dialog_cancel);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
connectionDetected();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
return false;
}
}
}
**Datetime**
//Click
fromDatePickerDialog.show();
// Defin Oncreat()
private SimpleDateFormat dateFormatter;
dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
setDateTimeField();
private void setDateTimeField()
{
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
startDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
endDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
GLIDE_WITH BLUER
Glide.with(mContext)
.load(user.card_image.toString())
.bitmapTransform(new BlurTransformation(mContext))
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(((ItemTypeViewHolder) viewHolder).iv_card_pic);
if (!user.profile_image.toString().equals(""))
Glide.with(mContext)
.load(user.profile_image.toString()) // Uri of the picture
.into(holder.img_pp);
else
Glide.with(mContext)
.load(R.drawable.ico_profile_default) // Uri of the picture
.into(holder.img_pp);
Push Notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static int count = 0;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
//This method is only generating push notification
private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
PendingIntent contentIntent = null;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap))
.setSmallIcon(R.mipmap.)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
}
}
Snackbar
<string name="no_internet">It seems like there is problem with your internet connection</string>
Main View
android:id="#+id/ll_main"
llMain = findViewById(R.id.ll_main);
Snackbar snackbar = Snackbar.make(llMain, R.string.no_internet, Snackbar.LENGTH_LONG);
snackbar.show();
Custom Spinner
public void CustomSpinner() {
pd = new ProgressDialog(Over75Lakh.this);
pd.setIndeterminate(false);
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
ApiInterface apiServiceData =
ApiClient.getClient().create(ApiInterface.class);
Call<GetServicesMainResponse> callServices = apiServiceData.getServices();
callServices.enqueue(new Callback<GetServicesMainResponse>() {
#Override
public void onResponse(Call<GetServicesMainResponse> call, Response<GetServicesMainResponse> response) {
if ((pd != null) && pd.isShowing()) {
pd.dismiss();
}
getServices = new ArrayList<String>();
getServicesDataResponses = response.body().getData();
for (GetServicesDataResponse getServicesDataResponse : getServicesDataResponses) {
getServices.add(getServicesDataResponse.getServices());
}
ArrayAdapter<String> adapterServices = new ArrayAdapter<String>(Activit.this, android.R.layout.simple_spinner_item, getServices);
adapterServices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMainService.setAdapter(adapterServices);
}
#Override
public void onFailure(Call<GetServicesMainResponse> call, Throwable t) {
pd.dismiss();
}
});
}
Get CallLogs.
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.CallLog;
public class CallLogHelper {
public static Cursor getAllCallLogs(ContentResolver cr) {
String strOrder = CallLog.Calls.DATE + " DESC"; // ASC --> then latest calls will get the latest txn no
Cursor curCallLogs = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, strOrder);
return curCallLogs;
}
}
public class timer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
= new ArrayList<>();
}
#SuppressLint("DefaultLocale")
#Override
protected String doInBackground(String... params) {
if (ActivityCompat.checkSelfPermission(CallHistoryRevenueActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return null;
}
Cursor managedCursor = CallLogHelper.getAllCallLogs(getContentResolver());
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
int callType11 = managedCursor.getColumnIndex(android.provider.CallLog.Calls.TYPE);
if (managedCursor.moveToFirst()) {
do {
String contactNumber = managedCursor.getString(number);
String callType = managedCursor.getString(callType11);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = CallType.OUTGOING_CALL_END;
break;
case CallLog.Calls.INCOMING_TYPE:
dir = CallType.INCOMING_CALL_END;
break;
case CallLog.Calls.MISSED_TYPE:
dir = CallType.MISS_CALL;
break;
case CallLog.Calls.VOICEMAIL_TYPE:
dir = CallType.VoiceMail;
break;
case 5:
dir = CallType.Rejected;
break;
case 6:
dir = CallType.Refused;
break;
}
if (str_unit.equals("sec")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = ((str_def_Rate / str_per) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("min")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 60) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("hr")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 3600) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
}
}
#Override
public void onFailure() {
}
});
}
while (managedCursor.moveToNext());
}
managedCursor.close();
// If the AsyncTask cancelled
if (isCancelled()) {
}
return "run";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setText(str_currency + " " + values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
finish();
}
}
JAVA utitlity / Helper Class is here
imports
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class is here
public class Utils {
/**
* Convertim to time format
*
* #param unix is time with long value
* #return string time
*/
public static String convertUnix2Date(long unix) {
if (unix == 0) return "";
String result;
Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
#SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
f.setTimeZone(TimeZone.getDefault());
result = f.format(date);
return result;
}
/**
* Handling the keyboard on device
*
* #param activity
*/
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Handling the listener to dismiss the keyboard on device
*
* #param context <br>
* #param view is parent view <br>
*/
public static void setupDismissKeyboardListener(Context context, View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard((Activity) context);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupDismissKeyboardListener(context, innerView);
}
}
}
/**
* Converting the DP value to PX to display on device
*
* #param context <br>
* #param value is DP value
* #return PX value
*/
public static int parseFromDPtoPX(Context context, float value) {
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
resources.getDisplayMetrics()
);
}
public static void setupUI(View view, final Activity activity) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard(activity);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
/**
*
*/
protected Utils() {
}
public static final String TAG = "Utils";
public static final int DEFAULT_BUFFER_SIZE = 8192;
private static String sFormatEmail = "^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$";
/**
* #return true if JellyBean or higher
*/
public static boolean isJellyBeanOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
/**
* #return true if Ice Cream or higher
*/
public static boolean isICSOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/**
* #return true if HoneyComb or higher
*/
public static boolean isHoneycombOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
/**
* #return true if GingerBreak or higher
*/
public static boolean isGingerbreadOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
/**
* #return true if Froyo or higher
*/
public static boolean isFroyoOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
/**
* Check SdCard
*
* #return true if External Strorage available
*/
public static boolean isExtStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
/**
* Check internet
*
* #param context
* #return true if Network connected
*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
return activeNetworkInfo.isConnected();
}
return false;
}
/**
* Check wifi
*
* #param context
* #return true if Wifi connected
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetworkInfo != null) {
return wifiNetworkInfo.isConnected();
}
return false;
}
/**
* Check on/off gps
*
* #return true if GPS available
*/
public static boolean checkAvailableGps(Context context) {
LocationManager manager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* Download data url
*
* #param urlString
* #return InputStream
* #throws IOException IOException
*/
/**
* #return an {#link HttpURLConnection} using sensible default settings for
* mobile and taking care of buggy behavior prior to Froyo.
* #throws IOException exception
*/
public static HttpURLConnection buildHttpUrlConnection(String urlString)
throws IOException {
Utils.disableConnectionReuseIfNecessary();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
conn.setRequestMethod("GET");
return conn;
}
/**
* Prior to Android 2.2 (Froyo), {#link HttpURLConnection} had some
* frustrating bugs. In particular, calling close() on a readable
* InputStream could poison the connection pool. Work around this by
* disabling connection pooling.
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!isFroyoOrHigher()) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Check an email is valid or not
*
* #param email the email need to check
* #return {#code true} if valid, {#code false} if invalid
*/
public static boolean isValidEmail(Context context, String email) {
boolean result = false;
Pattern pt = Pattern.compile(sFormatEmail);
Matcher mt = pt.matcher(email);
if (mt.matches()) {
result = true;
}
return result;
}
/**
* A method to download json data from url
*/
#SuppressWarnings("ThrowFromFinallyBlock")
public static String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
assert iStream != null;
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
ShowProgress();
}
#Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
**Q :- How to Calling a Api Using Retrofit in Android**
Library :-
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
**[1] Insert & Show Record :-**
*[i]ApiClient :-*
public class ApiClient
{
public static final String BASE_URL ="";
private static Retrofit retrofit = null;
public static Retrofit getClient()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
*[ii]ApiInterface :-*
public interface ApiInterface
{
#FormUrlEncoded
#POST("api/name")
Call<MainStatus> getDetails(#FieldMap HashMap<String, String> params);
}
*[iii]MainStatus :-*
public class MainStatus
{
#SerializedName("status")
#Expose
private String status;
#SerializedName("msg")
#Expose
private String msg;
}
*[iv]MainActivity.java :-*
public class Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new getData();
}
public void getData()
{
ApiInterface apiObj = ApiClient.getClient().create(ApiInterface.class);
//Optional
//HashMap<String, String> hashMap = new HashMap<>();
//hashMap.put("emp_id", read(USERID));
Call<MainStatus> call = apiObj.getDetails(hashMap);
call.enqueue(new Callback<MainStatus>()
{
#Override
public void onResponse(Call<MainStatus> call, Response<MainStatus> response)
{
Log.d("RESPONS#",""+response);
if (response.body().getStatus().equalsIgnoreCase("true"))
{
mainstatus= response.body().getDetails();
}
}
#Override
public void onFailure(Call<EmployeeLeaveMainDetails> call, Throwable t)
{
Toast.makeText(LeaveApplicationDetails.this, getString("Error"), Toast.LENGTH_SHORT).show();
}
});
}

Categories

Resources