我想知道Java中使用的util类。我目前正在使用Android中的一个应用程序,我需要使用从一个文件到另一个不同文件的类。有人告诉我像import com.android.utli.(ClassName)
那样导入它,“com.android.util”是包名。
我可以简单地通过导入包和类名来在我的另一个文件中使用该类吗?
答案 0 :(得分:3)
是。导入java文件顶部的类后,如:
import android.util.Log;
然后您可以在代码中使用它。
Log.debug("MyActivity", "Thing I want to log");
答案 1 :(得分:2)
该包实际上是“完全限定类名”的一部分。实际上,您可以在使用类名的任何地方使用该完全限定名称,例如:
com.android.util.UtilClass myUtil = new com.android.util.UtilClass();
但这很不方便。因此,同一个包(以及包java.lang
)中的类可以在没有导入的情况下使用速记(即只有类名)。必须先导入其他包中的类,然后才能以这种方式使用它们。
这只是一种组织代码并防止不同程序员编写具有相同名称的类的问题的方法 - 只要它们位于不同的包中,就可以使用完全限定的类名来解决冲突。
答案 2 :(得分:0)
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();
}
}
答案 3 :(得分:0)
导入
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;
班在这里
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;
}
}
答案 4 :(得分:-1)
*********************************************
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();
}
});
}
答案 5 :(得分:-1)
**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();
}
});
}