我正在研究json解析在我的TypeMenu java文件中我从服务器获得响应,当我点击listview中的项目时,我应该在listview中的下一个活动中获取相关项目。该listview项目也来自服务器...这里我想从所选项目中获取项目..但是我在下一个活动中从SubMenu.java获取数据库中的所有项目...就像我选择披萨所以在下一个活动中我应该得到项目相关只有披萨 这是我的TypeMenu.java文件 包com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
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,R.id.id});
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);
}
}
}
这是我的SubMenu.java文件
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SubMenu extends AppCompatActivity {
private String TAG = SubMenu.class.getSimpleName();
String type_items ;
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/broccoli/menu_typeitem.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);
Intent i = getIntent();
// getting product id (pid) from intent
type_items = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();
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) {
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Loading book details.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
// 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 ,text);
//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(SubMenu.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 name = c.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
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(
SubMenu.this, contactList,
R.layout.list_item, new String[]{ "name","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);
}
}
}
这里是我的php文件..我知道它会显示所有的数据..我尝试了其他代码但也没有工作..在这至少表中的所有数据都显示..但我只想选择数据
<?php
if($_SERVER['REQUEST_METHOD']=='GET')
{
$id = $_GET['type_items'];
require_once('config.php');
$sql = "SELECT * FROM main_menu_items WHERE type_item='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array("name"=>$res['name'],)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
答案 0 :(得分:1)
用以下代码替换SubMenu.java类的GetContacts循环:
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String type = c.getString("type");
if (type.equalsIgnoreCase(type_items)) {
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
break;
}
}
在子菜单类中,您需要检查所选ID是否与id匹配,只需将该数据保存在列表中并打破循环。