没有使用json android获取listview所选项目到下一个活动?

时间:2016-12-25 04:33:00

标签: php android json listview

我是android上的新手。我正在使用TypeMenu Activity,其中所有项目都从服务器进入listview,以及其他类SubMenu活动,其中所有项目都来自带图像的服务器。

现在我只希望listview中的所选项目进入TypeMenu活动中的SubMenu活动示例所有项目如Pizza,Pasta等都在listview中...所以我想在下一个例子中显示相关项目,如果我选择披萨那么在subMenu活动中,它应该只显示与Pizza相关的项目,而不是所有项目。关于如何将相关项目带到下一个活动,我感到有点困惑。

这是我的TypeMenu活动:

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

这是我的子菜单活动:

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

这是我的TypeMenu活动的Php文件:

<?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);

?>

这是我的答案,它正常工作......最后我得到了解决方案

<?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);

?>

2 个答案:

答案 0 :(得分:0)

由于您将选定的ID传递给下一个活动,因此请在SubMenu活动中通过意图获取您传递的ID并使用该ID进行api调用以获取相关响应并更新您的列表视图

<强>被修改

将您选择的ID传递给onItemClick内的SubMenu活动,如此

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

现在在子菜单活动中获取您的selectedId这样的额外内容并请求服务器获得相应的响应

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

答案 1 :(得分:0)

以下是如何修改php代码以获取所需的子菜单项。在代码中,我假设 main_menu_items 表中有 menu_type 字段。将其替换为实际的字段名称。

<?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);

?>

在您的SubMenu活动中,您需要从extras读取Id值并将其作为参数传递给php网页。为此,您需要替换此代码行:

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

以下内容:

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

另外,不要忘记将类型ID传递给第二个活动,因为 sohan shetty 在他的回答中建议。