Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

php - not getting listview selected item to next activity using json android?

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 =

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...