gpt4 book ai didi

java - 在android中的 ListView 上无法从服务器获取数据

转载 作者:行者123 更新时间:2023-12-01 09:06:40 25 4
gpt4 key购买 nike

我正在处理 json 解析,在我的 TypeMenu java 文件中,我从服务器获取响应,当我单击 ListView 中的项目时,我应该在 ListView 中的下一个 Activity 中获取相关项目..该 ListView 项目也来自服务器...这里我只想从选定的项目中获取项目..但是我在下一个 Activity 中从数据库获取所有项目,即 SubMenu.java...就像如果我选择 Pizza,那么在下一个 Activity 中我应该获得与项目相关的项目只含披萨这是我的 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);

}

最佳答案

将 SubMenu.java 类的 GetContacts 的 for 循环替换为以下内容:

  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 匹配,只需将该数据保存在列表中并中断循环。

关于java - 在android中的 ListView 上无法从服务器获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41216105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com