我正试图通过使用此网址获取当天的照片
http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US
我无法保存通过改造库获取的网址的值。 这是我的代码:
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>
MainActivity.class中的 getImageUrl()方法存在一些问题。 帮帮我们!!
答案 0 :(得分:0)
像这样替换你的getImageUrl()
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;
}
并在oncreate change,
Download_Uri = Uri.parse(url);
由此
Download_Uri = Uri.parse(getImageUrl());