두 개 이상의 서로 다른 URL과 하나의 목록 보기만
저는 제 앱에서 웹 서비스를 사용하고 있습니다.기본적으로 제 앱은 워드프레스 사이트의 게시물을 보여줍니다.사용자는 게시물을 북마크할 수도 있습니다.저는 모든 북마크 게시물을 포스트 URL과 함께 sqlite에 저장하고 있습니다.이제 문제는 제가 다양한 URL을 가지고 있다는 것입니다.그리고 이 url들의 내용을 One으로 보여주고 싶습니다.ListView
.
또한 이 모든 URL의 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"
}
]
}
누가 좀 도와주세요.그런 상황에서 어떻게 대처해야 할까요?
이거 한번...실제로 이 코드에서는 네트워크 운영을 위해 Voli Library를 사용하고 있습니다.먼저 네트워크 작업을 위해 Voli 라이브러리의 새 인스턴스를 만들지 않도록 응용 프로그램 클래스를 만듭니다.
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
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>
작성 시 작업에서 이 줄 추가...
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();
}
한 번의 비동기 호출 결과를 얻은 후 온백그라운드 방법으로 모든 실행을 수행해야 합니다.비동기 작업이 다른 스레드에서 실행되기 때문입니다.
ArrayList<HashMap<String,String>> allData;
Iterator iterator;
ArrayList<String> urlarray = new ArrayList<>();
@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.add(url);
}
iterator = urlarray.iterator();
MyAsyncTask task = new MyAsyncTask();
task.execute();
}
private class MyAsyncTask extends AsyncTask<Object,Void,ArrayList<String>>{
int urlNumber;
ArrayList<String> resultList = new ArrayList<>();
HttpURLConnection connection=null;
BufferedReader reader=null;
public MyAsyncTask (){
}
@Override
protected String doInBackground(Object... params) {
if(iterator.hasNext()) {
try {
URL url = new URL(iterator.next());
connection= (HttpURLConnection) url.openConnection();
connection.connect();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String json = buffer.toString();
resultList.add(json);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultList;
}
@Override
protected void onPostExecute(ArrayList<String> s) {
super.onPostExecute(s);
//Log.d("TAG",s);
if(s.size > 0){
//Your listview processing here.
}
}
}
언급URL : https://stackoverflow.com/questions/34813614/more-than-1-different-urls-and-only-one-listview
'sourcetip' 카테고리의 다른 글
py.test의 각 테스트 전후에 코드를 실행하시겠습니까? (0) | 2023.06.12 |
---|---|
C/C++와 같은 typedef (0) | 2023.06.12 |
환경 이름(IHosting Environment) 설정 방법.환경 이름)? (0) | 2023.06.12 |
Microsoft T-SQL에서 Oracle SQL로 변환 (0) | 2023.06.12 |
Python ValueError: 값이 너무 많아 압축을 풀 수 없습니다. (0) | 2023.06.07 |