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

Respuesta
 
Herramientas
  #1  
Viejo 13/02/17, 00:22:38
Array

[xs_avatar]
lixar22
Usuario invitado
 
Mensajes: n/a

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.-
Responder Con Cita


  #2  
Viejo 13/02/17, 11:33:30
Array

[xs_avatar]
manolazo manolazo no está en línea
Miembro del foro
 
Fecha de registro: jun 2012
Localización: Madrid
Mensajes: 218
Modelo de smartphone: Samsung Galaxy S7 edge
Tu operador: Pepephone
Has probado a hacer la llamada al servidor en el onCreate() del Fragment?
Responder Con Cita
  #3  
Viejo 13/02/17, 12:40:13
Array

[xs_avatar]
lixar22
Usuario invitado
 
Mensajes: n/a

 Cita: Originalmente Escrito por manolazo Ver Mensaje
Has probado a hacer la llamada al servidor en el onCreate() del Fragment?
Como seria?

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
Responder Con Cita
  #4  
Viejo 13/02/17, 14:43:31
Array

[xs_avatar]
manolazo manolazo no está en línea
Miembro del foro
 
Fecha de registro: jun 2012
Localización: Madrid
Mensajes: 218
Modelo de smartphone: Samsung Galaxy S7 edge
Tu operador: Pepephone
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
Responder Con Cita
Gracias de parte de:
  #5  
Viejo 13/02/17, 18:32:12
Array

[xs_avatar]
lixar22
Usuario invitado
 
Mensajes: n/a

 Cita: Originalmente Escrito por manolazo Ver Mensaje
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 por la aclaracion, voy a investigar sobre Volley y Gson y ver como puedo replicarlo. Saludos.-
Responder Con Cita
  #6  
Viejo 14/02/17, 20:28:42
Array

[xs_avatar]
lixar22
Usuario invitado
 
Mensajes: n/a

Alguien mas??
Responder Con Cita
Respuesta

Estás aquí
Regresar   Portal | Indice > Todo sobre Android > Programación y Desarrollo para Android



Hora actual: 03:43:04 (GMT +2)



User Alert System provided by Advanced User Tagging (Lite) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.

Contactar por correo / Contact by mail / 邮件联系 /