我正在尝试构建在线商店应用程序。我有一个列表视图,其中包含:玩具图片,价格,描述和复选框。当用户单击复选框时,我创建了CustomObject,然后单击按钮" Buy"我必须将CustomObject存储在mysql数据库中。主要问题是我不知道如何在listview中获取选择对象以及如何发送到mysql数据库。
private RequestQueue requestQueue;
private StringRequest request;
private Button btnBuy;
private ListView lvProducts;
List<CustomObject>customObjects=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
new JSONTask().execute("http://192.168.1.4:80/Mobilno/Products.php");
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
lvProducts=(ListView)findViewById(R.id.lvProducts);
btnBuy=(Button)findViewById(R.id.btnBuy);
btnBuy.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
request=new StringRequest(Request.Method.POST,"http://192.168.1.4/Mobilno/BuyToy.php",new Response.Listener<String>(){
@Override
public void onResponse(String response) {
try
{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),"success:"+jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
}else{ Toast.makeText(getApplicationContext(),"error:"+jsonObject.getString("error"),Toast.LENGTH_SHORT).show();}
}
catch (JSONException e){e.printStackTrace();}
}
},new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();
}
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
String json_string ="{\"buy\":[";
for(int i=0;i<customObjects.size();i++)
{
JSONObject obj_new = new JSONObject();
try {
obj_new.put("email", customObjects.get(i));
obj_new.put("productID", customObjects.get(i));
obj_new.put("price", customObjects.get(i));
json_string = json_string + obj_new.toString() + ",";
} catch (JSONException e) {
e.printStackTrace();
}
}
json_string = json_string.substring(0, json_string.length()-1);
json_string += "]}";
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("",json_string);
return hashMap;
}
};
requestQueue.add(request);
}
});
}
-
public class JSONTask extends AsyncTask<String,String,List<Prozivod>>
{
@Override
protected List<Product> doInBackground(String... params) {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer=new StringBuffer();
String line="";
while((line=reader.readLine())!=null)
{
buffer.append(line);
}
String finalJson=buffer.toString();
JSONArray jsonArray=new JSONArray(finalJson);
Log.i(finalJson,"json objekat");
List<Product> listProducts=new ArrayList<>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject proizvodJson=jsonArray.getJSONObject(i);
Product p=new Product();
p.setProizvodID(proizvodJson.getInt("ProductID"));
p.setCena(proizvodJson.getInt("Price"));
p.setOpis(proizvodJson.getString("Description"));
p.setSlika(proizvodJson.getString("Image"));
listProducts.add(p);
}
return listProducts;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}finally {
if(connection!=null){connection.disconnect();}
}
try{if(reader!=null){reader.close();}}
catch (IOException e) {
e.printStackTrace();
}
return null ;
}
@Override
protected void onPostExecute(final List<Product> result) {
super.onPostExecute(result);
ProductAdapter adapter=new ProductAdapter (getApplicationContext(),R.layout.red,result);
lvProducts.setAdapter(adapter);
}
}
-
public class ProductAdapter extends ArrayAdapter{
private List<Product>listProducts;
private int resource;
private LayoutInflater inflater;
public ProductAdapter (@NonNull Context context, @LayoutRes int resource, @NonNull List<Product> objects) {
super(context, resource, objects);
listProducts=objects;
this.resource=resource;
inflater=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder holder=null;
if(convertView==null)
{
holder=new ViewHolder();
convertView=inflater.inflate(resource,null);
holder.txtImg=(ImageView)convertView.findViewById(R.id.imgProduct);
holder.txtDescription=(TextView)convertView.findViewById(R.id.txtDescription);
holder.checkbox=(CheckBox)convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
}
else {
holder=(ViewHolder) convertView.getTag();
}
ImageLoader.getInstance().displayImage(listProducts.get(position).getImage(),holder.imgProducts);
convertView.setTag(holder.checkbox);
holder.checkbox.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
CheckBox cb=(CheckBox)v;
Product pro=(Product)cb.getTag();
CustomObject customObject=new CustomObject();
customObject.setProductID(pro.getProductID());
customObject.setPrice(pro.getCena());
customObject.setEmail(UlogujSe.email);
customObjects.add(customObject);
}
});
return convertView;
}
class ViewHolder
{
private ImageView txtImg;
private TextView txtDescription;
private CheckBox checkbox;
}
}
这是我的php脚本,用于测试当我从json对象的android获取数组并且它在postman中工作时:
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = "mobilno";
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//echo "Connected to MySQL";
$json = file_get_contents('C:\Users\nadaj\Desktop\streamPhp.txt');
$count=0;
$array = json_decode($json, true);
foreach ($array['buy'] as $item){
$email= $item['email'];
$productID= $item['productID'];
$price=$item['price'];
$sql = "insert into kupio(email,productID,price) values('$email','$productID','$price')";
if(mysqli_query($mysqli,$sql))
{
$count++;
}
}
if($count>0){echo $json_odgovor['success']='uspesno!';}
if($count==0){echo $json_odgovor['error']='neuspesno!';}
return $count;
}
echo json_encode($json_odgovor);
mysqli_close($mysqli);
?>
<!/ P>
答案 0 :(得分:0)
我认为您没有意识到这不是正确发送您的数据。
hashMap.put("",json_string);
return hashMap;
您需要hashMap.put("buy",listOfToys);
此外,凌空不会默认发送json。您需要将Content-type标头设置为application / json
如果你想发送一个{"buy":[]}
json对象,我建议你使用Volley的JSONObjectRequest,并在用于POST json数据的URL之后使用JSONObject参数。
使用该方法的警告:您的PHP必须返回JSON