不能使用json android将listview选定的项目移至下一个活动? [英] not getting listview selected item to next activity using json android?

查看:95
本文介绍了不能使用json android将listview选定的项目移至下一个活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android上的新手.我正在使用TypeMenu Activity,其中所有项均来自服务器进入列表视图,而在其他类SubMenu活动中,所有项均来自具有图像的服务器.

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.

现在,我只希望从列表视图中选择项目进入TypeMenu活动的SubMenu活动示例中,所有比萨,意大利面等项目都在列表视图中.因此,如果我选择披萨,那么我想在下一个示例中显示相关项目在subMenu活动中,应仅显示仅与Pizza相关的项目,而不是所有项目.我对如何将相关项目带到下一个活动感到困惑.

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.

这是我的TypeMenu活动:

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

这是我的子菜单活动:

   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文件:

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

?>

这是我的ANSWER,它运行正常...最终我找到了解决方案

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

?>

推荐答案

在这里,您可以修改php代码以仅获取必需的子菜单项.在代码中,我假设您的 main_menu_items 表中有一个 menu_type 字段.将其替换为实际的字段名称.

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

?>

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

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

具有以下内容:

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

也不要忘记按照 sohan shetty 在他的回答中建议的方式将类型ID传递给第二个活动.

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

这篇关于不能使用json android将listview选定的项目移至下一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆