Actualmente estoy desarrollando una aplicación de física que se supone que muestra una lista de fórmulas e incluso resuelve algunas de ellas (el único problema es el ListView
)
Este es mi diseño principal
Y esta es mi actividad principal
package com.wildsushii.quickphysics; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.view.Menu; import android.widget.ListView; public class CatList extends Activity { public static String AssetJSONFile (String filename, Context context) throws IOException { AssetManager manager = context.getAssets(); InputStream file = manager.open(filename); byte[] formArray = new byte[file.available()]; file.read(formArray); file.close(); return new String(formArray); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cat_list); ListView categoriesL = (ListView)findViewById(R.id.listFormulas); ArrayList<HashMap> formList = new ArrayList<HashMap>(); Context context = null; try { String jsonLocation = AssetJSONFile("formules.json", context); JSONObject formArray = (new JSONObject()).getJSONObject("formules"); String formule = formArray.getString("formule"); String url = formArray.getString("url"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } //My problem is here!! } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.cat_list, menu); return true; } }
De hecho, sé que puedo hacer esto sin usar JSON, pero necesito más práctica para analizar JSON. Por cierto, este es el JSON
{ "formules": [ { "formule": "Linear Motion", "url": "qp1" }, { "formule": "Constant Acceleration Motion", "url": "qp2" }, { "formule": "Projectile Motion", "url": "qp3" }, { "formule": "Force", "url": "qp4" }, { "formule": "Work, Power, Energy", "url": "qp5" }, { "formule": "Rotary Motion", "url": "qp6" }, { "formule": "Harmonic Motion", "url": "qp7" }, { "formule": "Gravity", "url": "qp8" }, { "formule": "Lateral and Longitudinal Waves", "url": "qp9" }, { "formule": "Sound Waves", "url": "qp10" }, { "formule": "Electrostatics", "url": "qp11" }, { "formule": "Direct Current", "url": "qp12" }, { "formule": "Magnetic Field", "url": "qp13" }, { "formule": "Alternating Current", "url": "qp14" }, { "formule": "Thermodynamics", "url": "qp15" }, { "formule": "Hydrogen Atom", "url": "qp16" }, { "formule": "Optics", "url": "qp17" }, { "formule": "Modern Physics", "url": "qp18" }, { "formule": "Hydrostatics", "url": "qp19" }, { "formule": "Astronomy", "url": "qp20" } ] }
He intentado muchas cosas e incluso he eliminado todo el proyecto para hacer uno nuevo 🙁
Como Faizan describe en su respuesta aquí :
Antes que nada, lea el archivo Json de su archivo de assests usando el código siguiente.
y luego simplemente puede leer esta cadena devuelta por esta función como
public String loadJSONFromAsset() { String json = null; try { InputStream is = getActivity().getAssets().open("yourfilename.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
y usa este método así
try { JSONObject obj = new JSONObject(loadJSONFromAsset()); JSONArray m_jArry = obj.getJSONArray("formules"); ArrayList> formList = new ArrayList>(); HashMap m_li; for (int i = 0; i < m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); Log.d("Details-->", jo_inside.getString("formule")); String formula_value = jo_inside.getString("formule"); String url_value = jo_inside.getString("url"); //Add your values in your `ArrayList` as below: m_li = new HashMap(); m_li.put("formule", formula_value); m_li.put("url", url_value); formList.add(m_li); } } catch (JSONException e) { e.printStackTrace(); }
Para más detalles sobre JSON Leer AQUÍ
{ // json object node "formules": [ // json array formules { // json object "formule": "Linear Motion", // string "url": "qp1" }
Qué estás haciendo
Context context = null; // context is null try { String jsonLocation = AssetJSONFile("formules.json", context);
Entonces cambie a
try { String jsonLocation = AssetJSONFile("formules.json", CatList.this);
Analizar
Creo que obtienes la cadena de la carpeta assests.
try { String jsonLocation = AssetJSONFile("formules.json", context); JSONObject jsonobject = new JSONObject(jsonLocation); JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules"); for(int i=0;i
Método para leer el archivo JSON de la carpeta Assets y regresar como un objeto de cadena.
public static String getAssetJsonData(Context context) { String json = null; try { InputStream is = context.getAssets().open("myJson.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } Log.e("data", json); return json; }
Ahora para analizar datos en su actividad:
String data = getAssetJsonData(getApplicationContext()); Type type = new TypeToken() { }.getType(); modelObject = new Gson().fromJson(data, type);