无法在android中加载本地json数据

时间:2015-07-13 17:04:36

标签: java android json android-asynctask

我正在尝试将json数据加载到我的Android设备中,但是有一个条件。

1.)如果有互联网,则通过特定网址从互联网下载数据。

2.)如果没有互联网,则使用名称为tch.txt的资产文件夹中的本地数据。

我这是检查互联网并执行所需的课程。

我的代码在有互联网的情况下可以正常获取数据,但它会让我出现以下错误

M <- cbind(c(t(A)), c(t(B)))
fnc <- function(){
  n <- nrow(A)
  ind <- sample(n) + (1:n-1)*n
  M[ind, ]
}
set.seed(0)
do.call(cbind, lapply(1:5, function(i)fnc()))
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    4    9    1    1    4    9    1    4     2
# [2,]    7    4    3    3    4    5    7    4    4     5
# [3,]    2    7    1    3    1    3    9    2    9     2

我在想我的listviewadapter类也存在一些问题,但无法弄明白。我附加了我的JsonLoader类和ListviewAdapterClass。

JsonLoadSubFirstFirst.java

   07-13 16:24:03.800  14691-14691/scientist.jobless.foodmana I/dalvikvm-heap﹕ Grow heap (frag case) to 11.560MB for 692236-byte allocation
07-13 16:24:03.828  14691-14691/scientist.jobless.foodmana I/dalvikvm-heap﹕ Grow heap (frag case) to 12.259MB for 692236-byte allocation
07-13 16:24:03.904  14691-14691/scientist.jobless.foodmana W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-13 16:24:03.988  14691-14697/scientist.jobless.foodmana I/jdwp﹕ Ignoring second debugger -- accepting and dropping
07-13 16:24:06.792  14691-14691/scientist.jobless.foodmana W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-13 16:24:06.840  14691-14691/scientist.jobless.foodmana W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-13 16:24:07.764  14691-14691/scientist.jobless.foodmana I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
07-13 16:24:07.764  14691-14691/scientist.jobless.foodmana W/dalvikvm﹕ VFY: unable to resolve virtual method 491: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-13 16:24:07.764  14691-14691/scientist.jobless.foodmana I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
07-13 16:24:07.764  14691-14691/scientist.jobless.foodmana W/dalvikvm﹕ VFY: unable to resolve virtual method 513: Landroid/content/res/TypedArray;.getType (I)I
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ org.json.JSONException: No value for Name
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at scientist.jobless.foodmana.JsonLoadSubFirstFirst$LocalDownloadJSON.doInBackground(JsonLoadSubFirstFirst.java:141)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at scientist.jobless.foodmana.JsonLoadSubFirstFirst$LocalDownloadJSON.doInBackground(JsonLoadSubFirstFirst.java:80)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-13 16:24:07.780  14691-14742/scientist.jobless.foodmana W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
07-13 16:24:07.804  14691-14691/scientist.jobless.foodmana W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-13 16:24:07.812  14691-14691/scientist.jobless.foodmana W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-13 16:24:07.816  14691-14691/scientist.jobless.foodmana I/MemoryCache﹕ MemoryCache will use up to 16.0MB
07-13 16:24:07.816  14691-14691/scientist.jobless.foodmana W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa6266288)
07-13 16:24:07.816  14691-14691/scientist.jobless.foodmana E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at scientist.jobless.foodmana.ListViewAdapter.getCount(ListViewAdapter.java:39)
            at android.widget.ListView.setAdapter(ListView.java:460)
            at scientist.jobless.foodmana.JsonLoadSubFirstFirst$LocalDownloadJSON.onPostExecute(JsonLoadSubFirstFirst.java:176)
            at scientist.jobless.foodmana.JsonLoadSubFirstFirst$LocalDownloadJSON.onPostExecute(JsonLoadSubFirstFirst.java:80)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

ListViewAdapter.java

public class JsonLoadSubFirstFirst extends ActionBarActivity {
    // Declare Variables
//firstactivity seems like to be main, lets see

    ProgressDialog pd;
    JSONObject jsonobject;
    JSONObject jsonobject2;
    String myjsonstring;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    ArrayList<HashMap<String, String>> localarraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";

    static final String NAME = "Name";
    static final String TIME = "Time";
    static final String VENUE = "Serves";
    static final String ingredients = "ingredients";
    static final String PRIZE_MONEY2 = "prize2";
    static final String REGISTRATION_FEE = "date";
    static final String DESCRIPTION = "Description";


    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask

        if(isNetworkAvailable())
         new DownloadJSON(this).execute();
        else
            //setContentView(R.layout.nonet);
            new LocalDownloadJSON().execute();

    }


    private class LocalDownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(JsonLoadSubFirstFirst.this);

            pd.setMessage("Loading...");
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

            pd.setIndeterminate(true);
            pd.setCancelable(false);
            pd.show();
        }



        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            localarraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address

            StringBuffer sb = new StringBuffer();
            BufferedReader br = null;

            try {
                br = new BufferedReader(new InputStreamReader(getAssets().open("tch.txt")));
                String temp;
                while ((temp = br.readLine()) != null)
                    sb.append(temp);
            }
            catch (IOException e)
            {

                e.printStackTrace();
            }
            finally
            {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            myjsonstring = sb.toString();

            try{
                JSONObject jsonObj = new JSONObject(myjsonstring);
                JSONArray Attendance = jsonObj.getJSONArray("events");

                for (int i = 0; i < Attendance.length(); i++)

                {

                    JSONObject a = Attendance.getJSONObject(i);
                    String Name = a.getString("Name");
                    String time = a.getString("time");
                    String ingredients = a.getString("ingredients");
                    String Serves = a.getString("Serves");
                    String descr = a.getString("descr");
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put("event", Name);
                    contact.put("fee", time);
                    contact.put("prize1", ingredients);
                    contact.put("prize2", Serves);
                    contact.put("descr", descr);
                    // adding contact to contact list
                    localarraylist.add(contact);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            //setContentView(R.layout.listview_main);
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(JsonLoadSubFirstFirst.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            //  mProgressDialog.dismiss();

            //   textView.setVisibility(View.VISIBLE);
            pd.dismiss();

            super.onPostExecute(args);

        }
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        private final ProgressDialog progressDialog;

        public DownloadJSON(Context ctx) {
            progressDialog = MyCustomProgressDialog.ctor(ctx);
        }
        @Override
        protected void onPreExecute() {

            super.onPreExecute();


            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("https://lit-hamlet-6856.herokuapp.com/eventsList/TECHNICAL");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("events");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("Name", jsonobject.getString("Name"));
                    map.put("Time", jsonobject.getString("Time"));
                    map.put("Serves", jsonobject.getString("Serves"));
                    map.put("ingredients", jsonobject.getString("ingredients"));
                    map.put("Description",jsonobject.getString("Description"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            //setContentView(R.layout.listview_main);
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(JsonLoadSubFirstFirst.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
          //  mProgressDialog.dismiss();
            super.onPostExecute(args);
         //   textView.setVisibility(View.VISIBLE);
            progressDialog.hide();
            super.onPostExecute(args);
        }
    }
}

有谁能告诉我代码中有什么问题:-)?

1 个答案:

答案 0 :(得分:1)

LocalDownloadJSON课程中,您要将项目添加到localarraylist,然后在适配器构造函数中使用arraylist,这就是您总是获得空数据(blanc屏幕)的原因。< / p>

只需改变:

adapter = new ListViewAdapter(JsonLoadSubFirstFirst.this, arraylist);

adapter = new ListViewAdapter(JsonLoadSubFirstFirst.this, localarraylist);
<{1>} onPostExecute()方法中的