Buenas tardesatardes a todos primero quiero darles las gracias por tomarse el tiempo de resolverme una duda que tengo. Ahora vamos a lo que nos concierne. Cree un proyecto de tipo Navigation Drawer Activity como veran en la imagen de abajo:
LO IDEAL SERIA QUE NO ESTE EL BOTON ACTUALIZAR QUE SOLO AL INGRESAR A IMPORT TRAIGA ESA LISTA QUE SE ENCUENTRA EN UN ARCHIVO PHP EN UN SERVIDORLo ideal seria que no este el boton "Actualizar", que solo al ingresar al import traiga esa lista que se encuentra en un archivo . GRACIAS DE VERDADphp en un servidor.
Este es mi archivo JSON
Gracias de verdad.
public class JSONParser {
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 {
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(this);
}
@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.content_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;
}
}
}
public class alquileres extends ActionBarActivity {
//public Progressclass Dialog
privatealquileres ProgressDialogextends pDialog;ActionBarActivity {
// CreatingProgress JSONDialog
Parser object
JSONParser jParser =private newProgressDialog JSONParser();pDialog;
ArrayList<HashMap<String, String>> empresaList; // 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// staticurl finalto Stringget TAG_PRODUCTSall =products "empresas";list
private static final String TAG_ID = "id";
private static final String TAG_NOMBREurl_all_empresas = "nombre";"http://deltaintegralelectromecanica.com/arcan.php";
// productsJSON JSONArrayNode names
JSONArray products private static final String TAG_SUCCESS = null;"success";
private static final String TAG_PRODUCTS = "empresas";
private static final String TAG_ID = "id";
private static final String TAG_NOMBRE = "nombre";
ListView lista; // products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView setContentView(R.layout.activity_alquilerese);lista;
//@Override
Hashmap para el ListViewpublic void onCreate(Bundle savedInstanceState) {
empresaList = new ArrayList<HashMap<String, String>>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alquilerese);
// Cargar los productos en// elHashmap Backgroundpara Threadel ListView
new LoadAllProducts().execute();
listaempresaList = (ListView)new findViewByIdArrayList<HashMap<String, String>>(R.id.listAllProducts);
ActionBar actionBar = getSupportActionBar // Cargar los productos en el Background Thread
new LoadAllProducts().execute();
actionBar.setDisplayHomeAsUpEnabled lista = (trueListView) findViewById(R.id.listAllProducts);
}//fin onCreate 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
class LoadAllProducts extends protectedAsyncTask<String, voidString, onPreExecute()String> {
super.onPreExecute();
pDialog = new ProgressDialog(alquileres.this);
pDialog.setMessage("Cargando comercios. Por favor espere...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* obteniendoAntes todosde losempezar productosel background thread Show Progress Dialog
* */
@Override
protected Stringvoid doInBackgroundonPreExecute(String... args) {
// Building Parameters super.onPreExecute();
List params pDialog = new ArrayListProgressDialog(alquileres.this);
// getting JSON string frompDialog.setMessage("Cargando URLcomercios. Por favor espere...");
JSONObject json = jParser pDialog.makeHttpRequestsetIndeterminate(url_all_empresas,false);
"GET", params pDialog.setCancelable(false);
pDialog.show();
}
//**
Check your log cat for JSON reponse * obteniendo todos los productos
Log * */
protected String doInBackground(String.d.. args) {
// Building Parameters
List params = new ArrayList("All);
Products: ", // getting JSON string from URL
JSONObject json = jParser.toStringmakeHttpRequest()url_all_empresas, "GET", params);
try {
// Check your //log Checkingcat for SUCCESSJSON TAGreponse
intLog.d("All successProducts: =", json.getInttoString(TAG_SUCCESS));
if (success == 1)try {
// products found
// GettingChecking Arrayfor ofSUCCESS ProductsTAG
productsint success = json.getJSONArraygetInt(TAG_PRODUCTSTAG_SUCCESS);
//if looping(success through== All1) Products{
//Log.i("ramiro", "produtos.length" + // products.length());
found
for (int i = 0; i// <Getting products.length();Array i++)of {Products
JSONObject cproducts = productsjson.getJSONObjectgetJSONArray(iTAG_PRODUCTS);
// Storinglooping eachthrough jsonAll itemProducts
in variable //Log.i("ramiro", "produtos.length" + products.length());
Stringfor id(int i = c0; i < products.getStringlength(TAG_ID); i++) {
String name = JSONObject c = products.getStringgetJSONObject(TAG_NOMBREi);
// creatingStoring neweach HashMapjson item in variable
HashMap map String id = newc.getString(TAG_ID);
HashMap String name = c.getString(TAG_NOMBRE);
// adding each child node to HashMap// keycreating =>new valueHashMap
map.put(TAG_ID, id);
HashMap map = new map.putHashMap(TAG_NOMBRE, name);
// 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();
}
} catch (JSONException e) {
return e.printStackTrace();null;
}
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);
}
});
}
}
}
}
public class FragmentImport extends 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(),alquileres.class);
startActivity(ListSong);
}
});
return view;
}
}
} }