【问题标题】:How can I call what I have in Static Method from MainActivity in Android如何从 Android 的 MainActivity 调用静态方法中的内容
【发布时间】:2013-08-25 11:40:29
【问题描述】:

我有这个类和简单的静态 {} 方法的问题:

 package com.example.tabletapp1.dummy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.StrictMode;
import android.util.Log;

public class DummyContent {

    public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();
    public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
    public static ArrayList<HashMap<String, String>> stireList = new ArrayList<HashMap<String, String>>();

    static {   /////// THIS FUNCTION
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();

        StrictMode.setThreadPolicy(policy);

        String url = "http://kosalis.beclenar.ro/stiri.txt";

        // JSON Node names
        String TAG_STIRE = "stire";
        String TAG_ID = "ID";
        String TAG_NUME = "Nume";
        String TAG_DESCRIERE = "Descriere";
        String TAG_POZA = "Poza";
        String TAG_CORP_STIRE_HTML = "Corp_stire_html";

        // contacts JSONArray
        JSONArray news = null;

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            news = json.getJSONArray(TAG_STIRE);

            // looping through All Contacts
            for (int i = 0; i < news.length(); i++) {
                JSONObject c = news.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NUME);
                String description = c.getString(TAG_DESCRIERE);
                String poza = c.getString(TAG_POZA);
                String body_html = c.getString(TAG_CORP_STIRE_HTML);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_NUME, name);
                map.put(TAG_DESCRIERE, description);
                map.put(TAG_POZA, poza);

                // adding HashList to ArrayList
                stireList.add(map);
                addItem(new DummyItem(id, name, description, poza, body_html));

            }
        } catch (JSONException e) {
            Log.e("Error2", TAG_CORP_STIRE_HTML);
            e.printStackTrace();
        }
    }

    private static void addItem(DummyItem item) {
        ITEMS.add(item);
        ITEM_MAP.put(item.id, item);
    }

    public static class DummyItem {
        public String id;
        public String title;
        public String description;
        public String content;
        public String photo;

        public DummyItem(String id, String title, String description,
                String photo, String content) {
            this.id = id;
            this.title = title;
            this.description = description;
            this.photo = photo;
            this.content = content;
        }

        @Override
        public String toString() {
            return title;
        }
    }
}

但我不知道如何执行 MainActivity 的静态 { } 函数中的内容。 我想从我的 mainactivity 中调用一个 asynctask,因为每次我的应用程序启动时,UI 都会冻结,我确信这是因为创建 JSONPArser 类的静态函数:

    package com.example.tabletapp1.dummy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "ISO-8859-2"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

我还有一个问题: 假设我有一个 AsyncTask,并且在 doInBackground() 中调用 JSONParser 类,这是否会冻结 UI?

【问题讨论】:

    标签: java android json static android-asynctask


    【解决方案1】:

    你没有定义一个静态方法,你定义了一个静态初始化器;当对象被实例化时它会自动运行。让它成为一个实际的方法(使用 static 关键字),你就可以调用它了。

    关于你的另一个问题:它与第一个无关;为它创建一个单独的问题。

    【讨论】:

    • 这意味着如果我在 MainActivity 和 doInBackfround() 中创建一个异步任务,我调用 MyStaticFunction() ,它会在不冻结 UI 的情况下工作吗?感谢您的建议!
    • 不,这对冻结 UI 没有任何意义。您问了两个不相关的问题,但您必须为第二个问题创建第二个帖子。我回答了您首先列出的问题/占据了您的大部分帖子。为您的新问题创建一个新问题帖子,而不是对此问题发表评论......但只要代码不在 UI 线程中运行,它通常不应该冻结/阻止 UI。
    【解决方案2】:

    您需要将static { 替换为static void staticMethod() {。然后你可以用DummyContent.staticMethod()调用它。

    edit:@Mah 对多个问题提出了很好的观点。如果你创建一个新的,请告诉我,我可以为你移动我的部分答案。

    对于 Asynctask,它确实非常适合此类工作,因为在 doInBackground() 中所做的任何事情都不会阻塞 UI 线程。对我来说,它有一些学习曲线,但我发现它是一门非常有用的课程。要使用下面的示例,您可以调用 new myAsyncTask().execute(url)

    class myAsyncTask extends AsyncTask<String, Integer, Boolean> {
    
        @Override
        protected Boolean doInBackground(String... url) {
            // This will receive the String you passed into it and return a boolean to onPostExecute()
            // Put all your CPU intensive stuff here
    
            // publishProgress can be used update the UI thread
            Integer progress = 1;
            publishProgress(progress);
    
            return true;
        }
    
        @Override
        protected void onProgressUpdate(Integer... doInBackgroundResult) {
            super.onProgressUpdate(doInBackgroundResult);
            // Anything done here can update the UI but will block
        }
    
        @Override
        protected void onPostExecute(Boolean doInBackgroundResult) {
            super.onPostExecute(doInBackgroundResult);
            // Runs after doInBackground finishes
            // Anything done here will block the UI
        }
    }
    

    【讨论】:

    • 是的,谢谢,它工作正常。还有一件事:该方法必须是公开的,以便我可以从 MainActivity() 访问它(以帮助他人)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多