0

Can someone help me with following issue:

When I click on an item in the listview, I need to open a new activity with the data from the listview...

here is my code:

public class listar_clientes extends ListActivity {

    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://192.168.137.100:81/androidapp/listar_clientes.php";

    // JSON Node names

    private static final String TAG_CLIENTE= "clientes";
    private static final String TAG_NOME = "nome";
    private static final String TAG_ABV = "nome2";


    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listar_clientes);



        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();
        //  Log.v("COUNT-->",productsList.get(0).toString());
        // Get listview
     ListView list = getListView();
        // launching Edit Product Screen
//        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//
//                // Starting new intent
//                Intent in = new Intent(getApplicationContext(),
//                        list_item.class);
//                // sending pid to next activity
//                in.putExtra(TAG_PID, pid);
//
//                // starting new activity and expecting some response back
//                startActivityForResult(in, 100);
//            }
//        });

      /*  ListAdapter adapter = new SimpleAdapter(
                encomendas_user.this, productsList,
                R.layout.activity_list_item, new String[] { TAG_IDUSER,
                TAG_TITULO},
                new int[] { R.id.pid, R.id.name });
        // updating listview
        setListAdapter(adapter);*/
        // on seleting single product
        // launching Edit Product Screen

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }



    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(listar_clientes.this);
            pDialog.setMessage("A Carregar dados. Por favor Aguarde...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "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_IDUSER);
                //Log.d("NAMSUCCESSE: ", ""+success);
                //if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_CLIENTE);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);


                    // Storing each json item in variable
                    String name = c.getString(TAG_NOME);
                    String abv = c.getString(TAG_ABV);


                    Log.d("NAME TESTE: ", name);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_NOME, "Nome:"+" "+ name);
                    map.put(TAG_ABV,  "Abreviatura:"+" "+abv);



                   // if(UserInfo.userID==(Integer.parseInt(name))){
                        // adding HashList to ArrayList
                    productsList.add(map);
                   // }


                }
              /*  } else {
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                           // NewProductActivity.class);
                    // Closing all previous activities
                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                   // startActivity(i);
                }*/
            } 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(
                            listar_clientes.this, productsList,
                            R.layout.activity_list_item_clientes, new String[] { TAG_NOME, TAG_ABV},
                            new int[] { R.id.name, R.id.abv});
                    // updating listview
                    setListAdapter(adapter);

                }
            });

        }

        /*private AdapterView.OnItemClickListener OnListClick=new AdapterView.OnItemClickListener(){


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);
                in.putExtra(TAG_NOME, id_user.getText().toString());
                startActivity(i);
            }
        }*/

        public void detalhes (View v){
            Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);

        }
    }
}

here is the xml code:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="false">
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="5dp"
        android:longClickable="true"
        android:padding="10dp"
        android:onClick="detalhes"
        >

        <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
        <TextView
            android:id="@+id/pid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:paddingBottom="5dp"/>

        <!-- Name Label -->
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="6dip"
            android:paddingLeft="6dip"
            android:textSize="17dip"
            android:textStyle="bold"
            android:textColor="#ff014cff"
            android:text="Nome Cliente"
            android:paddingBottom="5dp"/>
        <TextView
            android:id="@+id/abv"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:paddingTop="6dip"
            android:paddingLeft="6dip"
            android:textSize="17dip"
            android:textStyle="bold"
            android:textColor="#ff000000"
            android:text="Abreviatura" />



    </RelativeLayout>
</ScrollView>
Basim Sherif
  • 5,384
  • 7
  • 48
  • 90
Marco Soares
  • 11
  • 1
  • 5
  • do you have a itemclick listener for your list; – Sree Jun 15 '15 at 12:38
  • Are use any model for store list...??? – Nils Jun 15 '15 at 12:42
  • 2
    What is your issue? List item click is not working or something else? – Mithun Jun 15 '15 at 12:53
  • just my 2 cents. As beginner I used to have such problem. The (smart) solution was to use Fragments. The main activity has all data you need and the fragments can access this data. https://developer.android.com/training/basics/fragments/creating.html – alex Jun 15 '15 at 13:08

2 Answers2

0

Just Change your method as per your data to be send.

public void detalhes (View v){
    Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);
    Bundle mBundle = new Bundle();
    mBundle.putString(key1, value1);
    mBundle.putInt(key2,value2);
    mBundle.putStringArray(key3, value3);
    mBundle.putStringArrayList(key4, value4);
    ..
    ....
    mBundle.putInt(key, value);
    i.putExtras(mBundle);
    startActivity(i);
}

for reference you can use this link for how you get back your data from the bundle and more clarity. may this will helpful ..Thanks

Community
  • 1
  • 1
sahu
  • 1,188
  • 10
  • 19
0

Pass data from onItemClick of ListView to other Activity

Initialize variable:

private ListView listView;

Bind View:

listView = (ListView)findViewById(R.id.listView);

onItemClick Of ListView:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(this, Your_New_Activity.class);
         intent.putExtra("key 1", "Value 1");
         intent.putExtra("key 2", "Value 2");
         intent.putExtra("key 3", "Value 3");
         startActivity(intent);
      }
   });

Now Receive data on onCreate of New Activity:

 String key_one = getIntent().getStringExtra("key 1");
 String key_two = getIntent().getStringExtra("key 2");
 String key_three = getIntent().getStringExtra("key 3");

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151