任何人都可以告诉我如何在android中使用retrofit从JOSN格式的url中获取数据。 我在gradle文件中添加了依赖项,并在manifest文件中添加了权限。 感谢您的帮助。我只是一个初学者,所以请帮助我。 感谢
答案 0 :(得分:0)
阅读本教程:
Android Retrofit Library Example
Retrofit tutorial android studio 1.9
Retrofit 2.0 tutorial with sample application
Retrofit Android Tutorial : Example of Retrofit 2.0 capturing JSON Array and JSON Object from URL
答案 1 :(得分:0)
**Api calling Using Retrofit In Recyclerview**
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'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
**ApiClient**
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient
{
public static final String BASE_URL = "http://tttyuuuh/";
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;
}
}
**ApiInterface**
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface ApiInterface
{
@FormUrlEncoded
@POST("api/login_for_all.php")
Call<LoginMainStatus> getLoginDetails(@FieldMap HashMap<String, String> params);
}
**Mainactivity**
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public RecyclerView recyclerView;
private List<LeaveDatum> leaveInfoList;
private LinearLayoutManager layoutManager;
private LeaveApplicationAdapter leaveAdapter;
public ProgressDialog pd;
private Utils utils;
utils=new Utils(getActivity());
if (utils.isConnectingToInternet(getActivity()))
{
getLeaveApplicationList();
}
else
{
Toast.makeText(getActivity(), R.string.error_nointernet, Toast.LENGTH_SHORT).show();
}
private void getLeaveApplicationList()
{
pd=new ProgressDialog(getActivity());
pd.setMessage("Loading...");
pd.setCancelable(false);
pd.show();
ApiInterface apiINterface = ApiClient.getClient().create(ApiInterface.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("emp_id", ReadSharePrefrence(getActivity(), USERID));
Call<LeaveMainDetails> call = apiINterface.getLeaveApplicationList(hashMap);
call.enqueue(new Callback<LeaveMainDetails>()
{
@Override
public void onResponse(Call<LeaveMainDetails> call, Response<LeaveMainDetails> response)
{
if (response.body().getStatus().equalsIgnoreCase("true"))
{
pd.dismiss();
if (response.body().getLeaveData() != null)
{
leaveInfoList = response.body().getLeaveData();
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
leaveAdapter = new LeaveApplicationAdapter(getActivity(), leaveInfoList);
recyclerView.setAdapter(leaveAdapter);
}
else
{
Toast.makeText(getActivity(), getActivity().getString(R.string.datanotfound), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LeaveMainDetails> call, Throwable t)
{
pd.dismiss();
Toast.makeText(getActivity(), getString(R.string.datanotfound), Toast.LENGTH_SHORT).show();
}
});
}
public static String getCurrentDate() {
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
return df.format(c.getTime());
}
public static String locatToUTC(String dtStart) {
String newDate = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date localTime = format.parse(dtStart);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
newDate = format.format(gmtTime);
return newDate;
} catch (Exception e) {
e.printStackTrace();
}
return newDate;
}
public static String changeDOBFormate(String time) {
String inputPattern = "yyyy-MM-dd";
String outputPattern = " d" + " MMM" + "," + " yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
public static String locatToUTCForLocalMsg(String dtStart) {
String newDate = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date localTime = format.parse(dtStart);
sdf2.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf2.format(localTime));
newDate = format.format(gmtTime);
return newDate;
} catch (Exception e) {
e.printStackTrace();
}
return newDate;
}
public static void makeAlertSingleButtons(final AppCompatActivity appCompatActivity, String title) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity);
alertDialogBuilder.setMessage(title);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public static void makeAlertTwoButtons(final AppCompatActivity appCompatActivity, String yesButton, String noButton) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity);
alertDialogBuilder.setMessage("Kindly grant all permission, we respect your privacy and data!");
alertDialogBuilder.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
appCompatActivity.startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", appCompatActivity.getPackageName(), null)));
}
}
});
alertDialogBuilder.setNegativeButton(noButton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private static String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
public static void toolBarSetup(final AppCompatActivity activity, String title) {
Toolbar toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitleTextColor(activity.getResources().getColor(android.R.color.white));
activity.setSupportActionBar(toolbar);
toolbar.setTitle(title);
final Drawable upArrow = activity.getResources().getDrawable(R.drawable.ic_right_arrow);
upArrow.setColorFilter(activity.getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
activity.getSupportActionBar().setHomeAsUpIndicator(upArrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
activity.finish();
activity.overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
}
public static String capitalFirstLatter(String text) {
return text.substring(0, 1).toUpperCase() + text.substring(1);
}
public static Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
public static String diffBetweenTwoDates(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : " + endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
String returnDate;
if (elapsedDays == 0) {
SimpleDateFormat spf = new SimpleDateFormat("hh:mm aaa");
String retunString = spf.format(startDate);
returnDate = retunString;
} else {
SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yy");
String retunString = spf.format(startDate);
returnDate = retunString;
}
System.out.printf("%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
return returnDate;
}
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
public static boolean isOnline(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static boolean checkFileSize(String filePath) {
TypedFile file = new TypedFile("image/*", new File(filePath));
long fileSizeInBytes = file.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
Log.e("fileSizeInMB", "::" + fileSizeInMB);
if (fileSizeInMB >= 1) {
return false;
}
return true;
}
public static String utcToLocalTime1(String dtStart) {
if (dtStart != null && dtStart.length() > 5) {
String newDate = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localTime = format.parse(dtStart);
newDate = sdf.format(localTime);
return newDate;
} catch (Exception e) {
e.printStackTrace();
}
return newDate;
}
return "";
}
public static String utcToLocalTime2(String dtStart) {
if (dtStart != null && dtStart.length() > 5) {
String newDate = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localTime = format.parse(dtStart);
newDate = sdf.format(localTime);
return newDate;
} catch (Exception e) {
e.printStackTrace();
}
return newDate;
}
return "";
}
public static String utcToLocalNewTime(String dtStart) {
if (dtStart != null && dtStart.length() > 5) {
String newDate = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localTime = format.parse(dtStart);
newDate = sdf.format(localTime);
return newDate;
} catch (Exception e) {
e.printStackTrace();
}
return newDate;
}
return "";
}
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
答案 2 :(得分:0)
**Calling API Using Retorfit**
**Library**
// Network API
implementation 'com.commonsware.cwac:provider:0.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
**[1] Create Interface**
public interface ApiInterface
{
// LOGIN
@FormUrlEncoded
@POST("apiname")
Call<RegisterResponse> login(
@FieldMap Map<String,String> map);
}
[2]make API Client
public class ApiClient {
public static ApiInterface apiInterface;
public static ApiInterface getApiInterface() {
if (apiInterface == null)
{
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
apiInterface = retrofit.create(ApiInterface.class);
return apiInterface;
} else {
return apiInterface;
}
}
}
**[3]Activity**
Map<String, String> map = new HashMap<>();
map.put("password", password);
Call<RegisterResponse> registerResponseCall = ApiClient.getApiInterface().login(map);
registerResponseCall.enqueue(new Callback<RegisterResponse>()
{
@Override
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response)
{
if (response.code() == 200)
{
if (response.body().getStatus().equals("success"))
{
} else
}
}
@Override
public void onFailure(Call<RegisterResponse> call, Throwable t)
{
}
});
} else {
}