我在我的应用中使用了webservices。基本上我的应用程序显示了wordpress网站的帖子。用户还可以为帖子添加书签。我正在使用帖子网址保存sqlite中的所有书签帖子。现在的问题是我有很多不同的网址。我想在One ListView
中显示这些网址的内容。
所有这些网址的json结构也是一样的。
我已经查看了与此问题相关的其他问题,但这些问题并没有多大帮助。
让我告诉你到目前为止我已经尝试了多少。
这是代码
这是BookmarkActivity
ArrayList<HashMap<String,String>> allData;
String[] urlarray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
SqliteController controller= new SqliteController(this);
allData = controller.getAllData();
for (int i=0; i<allData.size(); i++){
String url=allData.get(i).get("link");
urlarray= new String[]{url};
}
for(int i=0; i <urlarray.length; i++){
MyAsyncTask task = new MyAsyncTask(i);
task.execute();
}
}
private class MyAsyncTask extends AsyncTask<Object,Void,String>{
int urlNumber;
HttpURLConnection connection=null;
BufferedReader reader=null;
public MyAsyncTask (int number){
this.urlNumber=number;
}
@Override
protected String doInBackground(Object... params) {
try {
URL url = new URL(urlarray[urlNumber]);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String json = buffer.toString();
return json;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Log.d("TAG",s);
}
}
这里是json。 (它不是完全相同的json,但我确信每个url都有相同的json结构)
{
"status": "ok",
"count": 1,
"count_total": 1,
"pages": 1,
"posts": [
{
"id": 1,
"type": "post",
"slug": "hello-world",
"url": "http:\/\/localhost\/wordpress\/?p=1",
"title": "Hello world!",
"title_plain": "Hello world!",
"content": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!<\/p>\n",
"excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!\n",
"date": "2009-11-11 12:50:19",
"modified": "2009-11-11 12:50:19",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "",
"url": "",
"description": ""
},
"comments": [
{
"id": 1,
"name": "Mr WordPress",
"url": "http:\/\/wordpress.org\/",
"date": "2009-11-11 12:50:19",
"content": "<p>Hi, this is a comment.<br \/>To delete a comment, just log in and view the post's comments. There you will have the option to edit or delete them.<\/p>\n",
"parent": 0
}
],
"comment_count": 1,
"comment_status": "open"
}
]
}
有人可以帮我这个吗?我应该如何处理这种情况?
答案 0 :(得分:3)
尝试这个......实际上在这段代码中我正在使用Volley Library进行网络操作。 首先在Application中创建Application类,以避免为网络操作创建Volley库的新实例。
public class ApplicationController extends Application {
public static final String TAG = ApplicationController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static ApplicationController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized ApplicationController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
//This function request the volley library to process with tag
//where <T> a generic method with an unbound type variable T.You can pass any datatype to functions.for more info About generic method.go through this link:http://docs.oracle.com/javase/tutorial/extra/generics/methods.html
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
//This function request the volley library to process with tag
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
//This function cancel the requested Url those are all in pending
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
在app build.gradle中,在依赖项下添加此行
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
在清单文件中添加此权限以访问网络
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Application标签中的提到了应用程序类名称
<application
android:name=".ApplicationController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
//your activity....
</application>
在活动onCreate中添加此行...
progressDialog=new ProgressDialog(MainClass.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
//place your code to form urlarray
urlarray = new String[5];
//where datas represents the arraylist to store received content from json response.if you want to show more datas add your custom object to arraylist
datas=new ArrayList<String>();
adapter= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1);
try {
for (int i = 0; i < urlarray.length; i++) {
final int j = i;
String url=urlarray[i];
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, (JSONObject) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("Response is for " + Integer.toString(j), response.toString());
//Here i assumed received json response is same as of sample json Provided by you.
try{
JSONArray jsonArray=response.getJSONArray("posts");
if(jsonArray.length()>0){
JSONObject obj=jsonArray.getJSONObject(0);
String content=obj.getString("content");
datas.add(content);
}
if(j==urlarray.length-1) {
progressDialog.dismiss();
adapter= new ArrayAdapter<String>(MainClass.this,
android.R.layout.simple_list_item_1, android.R.id.text1,datas);
listView.setAdapter(adapter);
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error",error.toString());
if(j==urlarray.length-1) {
progressDialog.dismiss();
}
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
objectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
ApplicationController.getInstance().addToRequestQueue(objectRequest, "JSON");
}
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:1)
在获得一次异步调用的结果后,您应该在onBackground方法中执行每次执行。这是因为异步任务在不同的线程上执行。
func uploadToCoreData() {
let dataController = DataController.sharedController
let moc = dataController.managedObjectContext
for goodies in datas{ //4 datas
let corePhoto = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: moc) as! Photo
let image = UIImageJPEGRepresentation(goodies.croppedPhoto!, 1)
corePhoto.photo = image
corePhoto.qty = goodies.value
let coreUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: moc) as! User
coreUser.userId = userId
let coreCart = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: moc) as! Cart
coreCart.cartId = cartId
coreCart.productName = productName
coreCart.price = price
coreCart.quantity = quantity
coreCart.cartToUser = coreUser
corePhoto.photoToCart = coreCart
print(corePhoto.qty)
}
dataController.saveContext()
let request = NSFetchRequest(entityName: "Photo")
let photoCount = moc.countForFetchRequest(request, error: NSErrorPointer.init())
print("total photo: \(photoCount)")
}