2015-07-13 2 views
0

Я пытаюсь загрузить данные json в мое устройство Android, однако есть условие.Не удалось загрузить локальные данные json в android

1.) Если есть Интернет, загрузите данные из Интернета по определенному URL-адресу.

2.) если нет Интернета, то используйте локальные данные, находящиеся в папке с ресурсами по имени tch.txt.

Я сделал это для проверки доступа в Интернет и выполнения требуемого класса.

Мой код работает правильно для извлечения данных, а есть интернет, но это дает мне следующее сообщение об ошибке

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 также имеет некоторые проблемы, но не мог понять. Я присоединяю свой класс JsonLoader и ListviewAdapterClass.

JsonLoadSubFirstFirst.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); 
     } 
    } 
} 

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter { 
    private int lastPosition = -1; 
    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    ImageLoader imageLoader; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 

    public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
     imageLoader = new ImageLoader(context); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     TextView rank; 
     TextView country; 
     TextView population; 
     ImageView flag; 
     TextView desc; 

     inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.listview_item, parent, false); 


     // Get the position 
     resultp = data.get(position); 


     // Locate the TextViews in listview_item.xml 
     rank = (TextView) itemView.findViewById(R.id.rank); 
     // YoYo.with(Techniques.Tada).duration(700).playOn(itemView.findViewById(R.id.rank)); good animation 
     country = (TextView) itemView.findViewById(R.id.country); 
     population = (TextView) itemView.findViewById(R.id.population); 
     desc=(TextView)itemView.findViewById(R.id.description); 
     // Locate the ImageView in listview_item.xml 
     flag = (ImageView) itemView.findViewById(R.id.flag); 

     // Capture position and set results to the TextViews 
     rank.setText(resultp.get(FirstActivity.NAME)); 
     country.setText(resultp.get(FirstActivity.TIME)); 

     /** Put only those Views which you want to show on the list**/ 
     // desc.setText(resultp.get(MainActivity.DESCRIPTION)); 
     //population.setText(resultp.get(MainActivity.VENUE));//Commented this line so that it is now seen in list view but can be seen in individual list 
     // Capture position and set results to the ImageView 
     // Passes flag images URL into ImageLoader.class 
     imageLoader.DisplayImage(resultp.get(FirstActivity.ingredients), flag); 


     Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top); 
     itemView.startAnimation(animation); 
     lastPosition = position; 




     // Capture ListView item click 
     itemView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Get the position 
       resultp = data.get(position); 
       Intent intent = new Intent(context, SingleItemView.class); 
       // Pass all data rank 
       intent.putExtra("Name", resultp.get(FirstActivity.NAME)); 
       // Pass all data country 
       intent.putExtra("Time", resultp.get(FirstActivity.TIME)); 
       // Pass all data population 
       intent.putExtra("Serves",resultp.get(FirstActivity.VENUE)); 
       // Pass all data flag 
       intent.putExtra("flag", resultp.get(FirstActivity.ingredients)); 

       intent.putExtra("description",resultp.get(FirstActivity.DESCRIPTION)); 
       // Start SingleItemView Class 
       context.startActivity(intent); 

      } 
     }); 
     return itemView; 
    } 
} 

Может кто-нибудь сказать мне, что случилось в коде :-)?

+0

Посмотрите на свои журналы: на 'Scientist.jobless.foodmana.ListViewAdapter.getCount (ListViewAdapter.java:39)'. Сделайте это: 'public int getCount() {return data! = Null? data.size(): 0; }. 'Это не идеально, ваша коллекция никогда не должна быть нулевой, сначала инициализируйте ее. –

+0

Приложение не сбой сейчас, это просто пустой экран, когда я пытаюсь загрузить локальные данные json. – penta

+0

Вам нужно было инициализировать данные. –

ответ

1

В вашем LocalDownloadJSON классе, вы добавляете элементы в localarraylist затем использовать arraylist в конструкторе адаптера, поэтому вы всегда получите пустые данные (экран блан).

Просто изменение:

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

в

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

в onPostExecute() методом LocalDownloadJSON.

+0

Добро пожаловать – Rami

+0

Het rami, я получаю null в своем списке ... знаешь почему? – penta

+0

Проверьте свой 'listview_main.xml', возможно, нет объекта ListView с' listview' как id, поэтому, когда вы вызываете '(ListView) findViewById (R.id.listview),' он возвращает нулевой объект. – Rami

Смежные вопросы