Skip to main content
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Relanzada por el usuario Comunidad
Formateo codigo - Correccion ortografia - Quito mayusculas (NO NOS GRITES)
Origen Enlace
Ivan Botero
  • 6.8k
  • 10
  • 36
  • 57

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;


}
}

} }

Buenas tardesa todos primero 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 SERVIDOR. GRACIAS DE VERDAD.

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(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 {

// 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);
            }
        });
    }
}

}

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;

} }

Buenas tardes 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 al import traiga esa lista que se encuentra en un archivo .php en un servidor.

Gracias de verdad.

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(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 {

    // 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);
                }
            });
        }
    }
}
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;


}
}
Origen Enlace

Navigation Drawer Activity con un Fragment que tiene un Button que trae datos de un servidor

Buenas tardesa todos primero 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:

introducir la descripción de la imagen aquí

Donde las secciones Import - Gallery, etc las trato a cada una como un fragment

Como verán en la imagen de arriba al hacer click en Import en este caso llamamos a un fragment el cual contiene un Button llamado Actualizar.

Lo que quiero hacer es que cuando le doy click en el botón actualizar, me traiga un archivo php que tengo en un servidor.

Los datos lo logro traer correctamente en un activity como verán en la imagen de arriba, pero en un fragment no se como hacerlo no lo he logrado realizar.

Aca pueden ver que es lo que quiero traer cuando hago click en Import que vendria a ser un fragment...

Debajo dejo los codigos para que puedan ver y guiarme en como puedo solucionar esto. Muchas gracias.

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 SERVIDOR. GRACIAS DE VERDAD.

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(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;
}

}

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(),alquileres.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 :gracias: