简体   繁体   English

JSONArray到ListView数组数据未显示

[英]JSONArray to a ListView array data not shown

i want to when run the app make the jsonRequest without pressing any button and save the data. 我想在运行应用程序时不按任何按钮进行jsonRequest并保存数据。 i just add a method for internet connection check: 我只是添加了一种检查互联网连接的方法:

if the connection to the internet its true, make the json request pass to the spinner, and save de data. 如果与互联网的连接为真,则将json请求传递给微调框,然后保存数据。

and when the internet connection its false, just load the data from sharedPreferences to the spinner. 当互联网连接为假时,只需将数据从sharedPreferences加载到微调器。

The application runs totally fine with the buttons (with simple onClick methods) and without the verificaConexion method. 使用按钮(使用简单的onClick方法)并且不使用verificaConexion方法,该应用程序可以完全正常运行。

But when i remove the buttons, add the verificaConexion method and i have internet connection, just, make the json request, show the data in the spinner and not save the data And when I close the app, remove the wifi, open the app, the spinner shows nothing. 但是,当我删除按钮时,添加了verificaConexion方法,并且我可以连接互联网,只需发出json请求,在微调器中显示数据,而不保存数据。当我关闭应用程序时,请删除wifi,打开应用程序,微调框没有显示任何内容。

For any reason the methods save and load data doesn't works. 由于任何原因,该方法无法保存和加载数据。

This is my onCreate() 这是我的onCreate()

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnObtener = (Button) findViewById(R.id.btnObtener);
    spDelegaciones = (Spinner)findViewById(R.id.spDelegaciones);
    btnGuardar = (Button) findViewById(R.id.btnGuardar);
    btnCargar = (Button) findViewById(R.id.btnCargar);
    txJsonArray = (TextView) findViewById(R.id.txJsonArray);

    verificaConexion(this);

}

This is my json Request method, works fine: 这是我的json Request方法,可以正常工作:

public void request() {
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.e("jsonArray", "" + jsonArray);
                        if (jsonArray == null) {
                            Toast.makeText(MainActivity.this, "EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
                        } else {

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

                                try {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    //con el php JsonArrayRequest2.php
                                    // String contact = jsonObject.getString("delegacion");
                                    //con el php JsonArrayVariosCampos.php
                                    String contact = jsonObject.getString("Delegacion");
                                    arrayList.add(contact);


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

                            adapter.notifyDataSetChanged();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(MainActivity.this, "ERROR...", Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(jsonArrayRequest);

}

my guardarDatos method to save the data: 我的guardarDatos方法保存数据:

 public boolean guardarDatos(){

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
    mEdit1.putInt("Status_size", arrayList.size());

    for(int i=0;i<arrayList.size();i++)
    {
        mEdit1.remove("Status_" + i);
        mEdit1.putString("Status_" + i, arrayList.get(i));
    }

    Toast.makeText(MainActivity.this, " DATOS GUARDADOS ", Toast.LENGTH_SHORT).show();

    return mEdit1.commit();



}

and my cargarDatos method to load the data: 和我的cargarDatos方法加载数据:

public void cargarDatos(){

    SharedPreferences mSharedPreference1 =   PreferenceManager.getDefaultSharedPreferences(this);
    arrayList.clear();
    int size = mSharedPreference1.getInt("Status_size", 0);

    for(int i=0;i<size;i++)
    {
        arrayList.add(mSharedPreference1.getString("Status_" + i, null));
    }


    adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
    spDelegaciones.setAdapter(adapter);

    Toast.makeText(MainActivity.this, " DATOS CARGADOS ", Toast.LENGTH_SHORT).show();

}

and here is my class to check the internet connection: 这是我的课,检查互联网连接:

public boolean verificaConexion(Context ctx){
    boolean bConectado = false;
    ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] redes = connec.getAllNetworkInfo();
    for (int i = 0; i < 2; i++) {
        if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
           bConectado = true;
            if(bConectado) {
                Toast.makeText(MainActivity.this, " con conexion ", Toast.LENGTH_LONG).show();

                adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
                spDelegaciones.setAdapter(adapter);
                request();
                guardarDatos();

            }else {

                cargarDatos();
            }

        }else{




        }


    }
    return bConectado;

}

Since you are using only one string in contact class. 由于您仅在联系人类中使用一个字符串。 instead of arrayList<Contact> I will use ArrayList<String> 代替arrayList<Contact>我将使用ArrayList<String>

here I have removed singleTone class. 在这里,我删除了singleTone类。 and added jsonArrayRequest code inside in same class. 并在同一类中添加了jsonArrayRequest代码。 and after adding item in arraylist I have called adapter.notifyDataSetChanged(); 在arraylist中添加项目后,我调用了adapter.notifyDataSetChanged();

MainActivity.class MainActivity.class

public class MainActivity extends AppCompatActivity {

    TextView txdeleg_lista;
    Button btnObtener;
    ArrayList<String> arrayList = new ArrayList<String>();
    ListView listView;
    String json_url = "your url";
    ArrayAdapter<String> adapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnObtener = (Button) findViewById(R.id.btnObtener);
    txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
    listView = (ListView) findViewById(R.id.lvDelegacion);

    adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);

    btnObtener.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //startActivity(new Intent(MainActivity.this, DesplegarLista.class));

            listView.setAdapter(adapter);


            request();

        }
    });
  }

  public void request() {
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray jsonArray) {
                    Log.e("jsonArray",""+jsonArray);
                    if(jsonArray == null){
                        Toast.makeText(MainActivity.this,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
                    }
                    else {

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

                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String contact = jsonObject.getString("UFULLNAME");
                                arrayList.add(contact);


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

                        adapter.notifyDataSetChanged();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(MainActivity.this,"ERROR...", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    requestQueue.add(jsonArrayRequest);
    }
}

check and if you have any query comment. 检查以及您是否有任何查询注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM