我正在编写一个程序,希望从在线 url 下载图像并希望以交错的 GridView 格式显示,我从这里找到了交错的 GridView 代码
并使用此链接从在线链接以 JSON 格式下载图像
但问题是,我无法使用以下代码将图像下载到 SD 卡中.....
MainActivity.java:-
public class MainActivity extends Activity {
private String urls[];
String location = "http://snapoodle.com/APIS/android/feed.php";
static final String TAG_ITEMS = "print";
StaggeredGridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (StaggeredGridView) this.findViewById(R.id.staggeredGridView1);
getImages get= (getImages) new getImages();
get.execute(location);
// new getImages().execute();
}
class getImages extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject json = JSONfunctions
.getJSONfromURL(location);
try {
JSONArray jarray;
jarray = json.getJSONArray(TAG_ITEMS);
urls = new String[jarray.length()];
for (int i = 0; i < jarray.length(); i++) {
JSONObject gridImages = jarray.getJSONObject(i);
urls[i] = gridImages.getString("saved_location");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(Void args) {
StaggeredAdapter adapter = new StaggeredAdapter(MainActivity.this,
R.id.imageView1, urls);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
JSONfunctions.java:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}