|
||
|
![]() |
![]() |
Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android |
![]() |
|
Herramientas |
#1
|
||||
|
||||
Navigation Drawer Activity con un Fragment que tiene un Button que trae datos de un servidor.
Gente es mi primera vez que voy a postear en este subforo, primero buenas noches y gracias a todos por su tiempo.
Comence hace un tiempo con android studio y me veo en un problema que no he podido encontrar la solucion en internet. Cree un nuevo proyecto seleccionando el Navigation Drawer Activity, como ven en la imagen, luego logre que cada una de esas opciones sea un fragment. Captura.PNG Luego lo que hice es que dentro de ese fragment cree un Button Captura2.PNG y que al seleccionarlo osea utlizando un OnClickListener me traiga una lista que tengo en un archivo php en un servidor. Algo asi. Captura3.PNG El problema que como ven la imagen de arriba solo logro hacerla funcionar en un activity y no en un fragment. Lo ideal seria no tener el boton y ni bien ingrese al fragment se actualice pero no logro hacerlo. Como puedo hacer para hacerlo funcionar? Si necesitan mas datos encantado en darselos, he buscado horas y horas, no pude encontrar nada en stackoverflow... Gracias, cualquier cosa sera bienvenida. SALUDOS.- ![]() |
|
#2
|
||||
|
||||
Has probado a hacer la llamada al servidor en el onCreate() del Fragment?
|
#3
|
||||
|
||||
Este es mi archivo JSON --------------------------------------------------------------------------------------------- public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; public JSONParser() { } public JSONObject makeHttpRequest(String url, String method, List params) { try { if(method == "POST"){ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; 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-1"), 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 { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } ------------------------------------------------------------------------------------------------------- Mi MainActivity public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(t his); } @override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); FragmentManager fragmentManager = getSupportFragmentManager(); if (id == R.id.nav_camera) { fragmentManager.beginTransaction().replace(R.id.co ntent_main,new FragmentImport()).commit(); } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } } --------------------------------------------------------------------------------------------------------- Alquileres para comunicarme al servidor public class alquileres extends ActionBarActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> empresaList; // url to get all products list private static String url_all_empresas = "http://deltaintegralelectromecanica.com/arcan.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCTS = "empresas"; private static final String TAG_ID = "id"; private static final String TAG_NOMBRE = "nombre"; // products JSONArray JSONArray products = null; ListView lista; @override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alquilerese); // Hashmap para el ListView empresaList = new ArrayList<HashMap<String, String>>(); // Cargar los productos en el Background Thread new LoadAllProducts().execute(); lista = (ListView) findViewById(R.id.listAllProducts); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); }//fin onCreate class LoadAllProducts extends AsyncTask<String, String, String> { /** * Antes de empezar el background thread Show Progress Dialog * * @override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(alquileres.this); pDialog.setMessage("Cargando comercios. Por favor espere..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * obteniendo todos los productos * * protected String doInBackground(String... args) { // Building Parameters List params = new ArrayList(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params); // Check your log cat for JSON reponse Log.d("All Products: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products //Log.i("ramiro", "produtos.length" + products.length()); for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NOMBRE); // creating new HashMap HashMap map = new HashMap(); // adding each child node to HashMap key => value map.put(TAG_ID, id); map.put(TAG_NOMBRE, name); empresaList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * ** protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * * ListAdapter adapter = new SimpleAdapter( alquileres.this, empresaList, R.layout.single_post, new String[] { TAG_ID, TAG_NOMBRE, }, new int[] { R.id.single_post_tv_id, R.id.single_post_tv_nombre, }); // updating listview //setListAdapter(adapter); lista.setAdapter(adapter); } }); } } } ----------------------------------------------------------------------------------------------------- Y el fragment public class FragmentImport extends Fragment { private Button btn; public FragmentImport() { // Required empty public constructor } @override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_fragment_import , container, false); btn = (Button) view.findViewById(R.id.buttonUpdate); btn.setOnClickListener(new View.OnClickListener() { @override public void onClick(View v) { Intent ListSong = new Intent(getActivity().getApplicationContext(),alqui leres.class); startActivity(ListSong); } }); return view; } } ------------------------------------------------------------------------------------------------------ Al hacer click en el boton actualizar del fragment la aplicacion se detiene, se que hay algo mal ahi pero no me doy cuenta como solucionarlo busque mile de maneras en internet pero no le encuentro la vuelta. EL tema para una actividad me esta funcionando pero en un fragment me esta reventando la cabeza. Gracias y disculpas ![]() |
#4
|
||||
|
||||
Yo me olvidaria de usar DefaultHttpClient, HttpPost, ya que estan obsoletas (deprecated) y usaria Volley con Gson para manejar JSON , aunque tambien puedes usar Retrofit o HttpURLConnection.
Yo usaria Volley con Gson . Ahora bien, si te emperras en hacerlo con HttoPost y JSON a pelo habria que ver donde esta el fallo en el Log y ver el error que tienes. A ver que comentan los expertos ![]() |
Gracias de parte de: | ||
#5
|
||||
|
||||
Yo me olvidaria de usar DefaultHttpClient, HttpPost, ya que estan obsoletas (deprecated) y usaria Volley con Gson para manejar JSON , aunque tambien puedes usar Retrofit o HttpURLConnection.
Yo usaria Volley con Gson . Ahora bien, si te emperras en hacerlo con HttoPost y JSON a pelo habria que ver donde esta el fallo en el Log y ver el error que tienes. A ver que comentan los expertos ![]() ![]() |
#6
|
||||
|
||||
Alguien mas??
|
![]() |
![]() |
||||||
|