-1

I am newbie on android. I am having TypeMenu Activity where all items are coming from server into listview, and other class SubMenu activity where also all items are coming from server with image.

Now I want only selected item from listview to come into SubMenu activity example in TypeMenu activity all items like Pizza, Pasta,etc are in a listview... So I want to show related items in next example if I choose pizza so in subMenu activity it should to show only items which is related with Pizza only and not all items. I am bit confused as to how will take the related item to next activity.

here is my TypeMenu Activity:

public class TypeMenu extends AppCompatActivity {

    private String TAG = TypeMenu.class.getSimpleName();
    String bid;

    private ProgressDialog pDialog;
    private ListView lv;
    private static final String TAG_BID = "bid";

    // URL to get contacts JSON
    private static String url = "http://cloud.granddubai.com/brtemp/index.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type_menu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();


        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // getting values from selected ListItem

                HashMap<String, String> selected = contactList.get(position);
                String keyId = new ArrayList<>(selected.keySet()).get(0);
                String type_items  = selected.get(keyId);
                Intent in = new Intent(getApplicationContext(), SubMenu.class);
               //  sending pid to next activity
                in.putExtra(TAG_BID ,type_items );
                startActivityForResult(in, 100);
                Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(TypeMenu.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
           // Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
         String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);





            if (jsonStr != null) {
                try {
                    JSONArray jsonArry = new JSONArray(jsonStr);

                    for (int i = 0; i < jsonArry.length(); i++)
                    {

                        JSONObject c = jsonArry.getJSONObject(i);
                        String id = c.getString("id");
                        String type = c.getString("type");
                        HashMap<String, String> contact = new HashMap<>();

                       contact.put("id", id);
                        contact.put("type", type);
                        contactList.add(contact);


                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    TypeMenu.this, contactList,
                    R.layout.list_item, new String[]{ "type","id"},
                    new int[]{
                    R.id.type});

            lv.setAdapter(adapter);
        }

}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
        }

here is my Submenu Activity:

   public class SubMenu extends AppCompatActivity {

    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "id";
    static String COUNTRY = "name";

    static String FLAG = "image";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_sub_menu);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        String SelectedId = getIntent().getStringExtra("id");


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);




        // Get the view from listview_main.xml

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener {

        // @Override
        //  protected void onPreExecute() {
        //  super.onPreExecute();
        // Create a progressdialog
        //   mProgressDialog = new ProgressDialog(SubMenu.this);
        // Set progressdialog title
        //   mProgressDialog.setTitle("Categories of Main categories.....");
        // Set progressdialog message
        //  mProgressDialog.setMessage("Loading...");
        //  mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        //  mProgressDialog.show();
        // }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonarray = JsonFunctions
                    .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
            try {
                // Locate the array name in JSON
//                    jsonarray = jsonobject.getJSONArray("main_menu_items");


                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();

                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    // map.put("id", jsonobject.getString("id"));
                    map.put("name", jsonobject.getString("name"));

                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.list1);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(SubMenu.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(this);
            // Close the progressdialog
            // mProgressDialog.dismiss();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            LayoutInflater layoutInflater
                    = (LayoutInflater)getBaseContext()
                    .getSystemService(LAYOUT_INFLATER_SERVICE);
            View popupView = layoutInflater.inflate(R.layout.popup, null);
            final PopupWindow popupWindow = new PopupWindow(
                    popupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);

            Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
            btnDismiss.setOnClickListener(new Button.OnClickListener(){

                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }});

            popupWindow.showAsDropDown(view, 3000, -90);







        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

here is my Php file for TypeMenu Activity:

<?php 
include ('config.php');
$id = $_GET['id'];
$sql = mysqli_query($conn,"SELECT * FROM menu_type ");
$arr = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['type']= $result['type'];
$i++;
}
echo json_encode($arr);

?>

here is my ANSWER which is working fine...finally i got the solution

<?php 
include ('config.php');


$id = $_GET['id'];

/* assuming main_menu_items table has field "menu_type" */

//$stmt = $mysqli->prepare("SELECT * FROM main_menu_items WHERE type_items=?");

//$stmt->bind_param("i", $id)
$stmt ="SELECT * FROM main_menu_items WHERE type_items='".$id."'";
/*now only submenu items of given type will be selected*/
$sql = mysqli_query($conn, $stmt);

$arr = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['name']= $result['name'];
$arr[$i]['image']=$result['image'];
$i++;
}
echo json_encode($arr);

?>
Julien Marrec
  • 11,605
  • 4
  • 46
  • 63
z.al
  • 279
  • 1
  • 6
  • 21

2 Answers2

0

Since you are passing selected id to next activity , So get your passed id through intent in SubMenu activity and do api call with that id to get your relevant response and upate your listview

Edited

Pass your selected id to SubMenu activity inside onItemClick like this

            @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // getting values from selected ListItem
            HashMap<String, String> selected = contactList.get(position);
            String selectedId= selected.get("id");
            Intent in = new Intent(getApplicationContext(), SubMenu.class);
           //  sending pid to next activity
            in.putExtra("id",selectedId);
            startActivityForResult(in, 100);
            Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
        }
    });

Now get your selectedId throug extras like this in submenu activity and request server to get respective response

String SelectedId = getIntent.getStringExtra("id");
sohan shetty
  • 289
  • 1
  • 16
  • kindly through coding explain it...i tried earlier many codes but then nothing shows in listview activity – z.al Dec 25 '16 at 05:41
  • i want to get only selected item in SubMenu activity...actually it is json based thts why i m confused as to where i put code to get selected item – z.al Dec 25 '16 at 06:01
  • Correct me if am wrong In Submenu activity you are calling server to get the selected item response with the selected id which was passed from previous activity right? – sohan shetty Dec 25 '16 at 06:08
  • thts d issue i m not passing any selected id i want it tht code in my class as to how to pass selected item into next activity – z.al Dec 25 '16 at 06:10
  • as it is json based thts why i m confued – z.al Dec 25 '16 at 06:11
  • yes i am getting the selected id in toast in My TypeMenu Activity....now where to assign this id in my SubMenuActivity so tht i can get only related item ..i have edited my SubMenu Activity – z.al Dec 25 '16 at 08:32
  • you should pass as query parameter in your url to get only related item – sohan shetty Dec 25 '16 at 08:35
  • and how can i edit my php to get only related code in subMenu activity..kindly help as i m half done with ur answer..only remaining ..plz help – z.al Dec 25 '16 at 08:35
  • i have given my submenu php file above – z.al Dec 25 '16 at 08:38
0

Here is how you can modify your php code to get only required sub menu items. In the code I assume there is menu_type field in your main_menu_items table. Replace it with the actual field name.

<?php 
include ('config.php');


$id = $_GET['id'];

/* assuming main_menu_items table has field "menu_type" */
$stmt = $mysqli->prepare("SELECT * FROM main_menu_items WHERE menu_type=?");
$stmt->bind_param("i", $id)

/*now only submenu items of given type will be selected*/
$sql = mysqli_query($conn, $stmt);

$arr = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['name']= $result['name'];
$arr[$i]['image']=$result['image'];
$i++;
}
echo json_encode($arr);

?>

In your SubMenu activity you need to read the Id value from extras and pass it to the php webpage as a parameter. For that you need to replace this code line:

       jsonarray = JsonFunctions
                .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php");

with the following:

       jsonarray = JsonFunctions
                .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php?id=" + getIntent.getStringExtra("id"));

Also don't forget to pass the type id to the second activity as sohan shetty suggested in his answer.

Alexey
  • 1,521
  • 1
  • 13
  • 24
  • i have edited my submenu activity and php file plz see it – z.al Dec 25 '16 at 10:20
  • Your php doesn't return anything now. Please check php server logs for any error and also please show what you have in your main_menu_items table. – Alexey Dec 25 '16 at 10:45
  • i got the solution...see my edited php..for future preference for other – z.al Dec 25 '16 at 10:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131471/discussion-between-alexey-and-z-al). – Alexey Dec 26 '16 at 06:51
  • see my question here...http://stackoverflow.com/questions/41327265/how-can-i-make-my-alert-dialog-box-in-android – z.al Dec 26 '16 at 06:58