gpt4 book ai didi

java - 在ListView中显示JsonArray

转载 作者:行者123 更新时间:2023-11-29 09:01:00 25 4
gpt4 key购买 nike

我正在尝试编写一个应用程序,该应用程序将连接到数据库、提取数据并在手机上显示该数据。不过我遇到了一个问题。

我使用以下方式连接到数据库:

try {           
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://74.208.131.62/Androidtest/testscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("Connection Success","Connected To Database");
} catch(Exception e) {

}

test.php 是一个 sql,它将返回值:Item_ID(auto_inc_int)、OtherTerms(String)。

然后,我将其转换为字符串:

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
is.close();
result = sb.toString();
}

然后我用了这部分,我不太明白,只是从网上复制的:

int Item_id;
String Item_name;
String populate = new String();

try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Item_id = json_data.getInt("id");
Item_name = json_data.getString("item");
}
...

但是,我收到消息“未找到项目”。我尝试更改数据库名称,但在 LogCat 中没有收到“连接错误”,而是“未找到项目”。

我不知道我的应用程序是否成功连接到数据库。我需要将结果插入到 ListView 对象中。我做错了什么?

(另外,祝大家节日快乐!)

最佳答案

我正在开发一个应用程序,它完全可以完成您想要做的事情。

这是我的代码:

这是主要 Activity 。在这里,您连接到 php 文件并根据 JSON 结果创建一个数组。

public class mainActivity extends Activity {



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);

ArrayList<List> menuitems = getItems("android", 1); //Call to function to get results from web, you can put variables to pass here

ListView listView = (ListView) findViewById(R.id.Menu);
listView.setAdapter(new ListAdapter(this, R.layout.categorymenu, menuitems));

listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ON CLICK ACTIVITY GOES HERE




}
});
}

public ArrayList<List> getItems(String searchTerm, int page) {
String searchUrl = "URL TO YOUR PHP FILE GOES HERE";

ArrayList<List> lists = new ArrayList<List>();

HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);

ResponseHandler<String> responseHandler = new BasicResponseHandler();

String responseBody = null;
try{
responseBody = client.execute(get, responseHandler);
}catch(Exception ex) {
ex.printStackTrace();
}

JSONObject jsonObject = null;
JSONParser parser=new JSONParser();

try {
Object obj = parser.parse(responseBody);
jsonObject=(JSONObject)obj;

}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}

JSONArray arr = null;

try {
Object j = jsonObject.get("results");
arr = (JSONArray)j;
}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}

for(Object t : arr) {
List list = new List(
((JSONObject)t).get("categories_name").toString(),
((JSONObject)t).get("categories_id").toString()
);
lists.add(list);
}

return lists;


}

/** Classes **/

public class List {
public String name;
public String message;
public Boolean usernameSet = false;
public Boolean messageSet = false;

public List(String username, String message) {
this.name = username;
this.message = message;
}
}

}

然后我使用 menuListAdapater 类创建 ListView :

public class menuListAdapter extends ArrayAdapter<List> {
private ArrayList<List> lists;
private Activity activity;


public menuListAdapter(Activity a, int textViewResourceId, ArrayList<List> lists) {
super(a, textViewResourceId, lists);
this.lists = lists;
activity = a;

}

public static class ViewHolder{
public TextView name;
public TextView message;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.categorymenu, null);
holder = new ViewHolder();
holder.name = (TextView) v.findViewById(R.id.categoryname);
holder.message = (TextView) v.findViewById(R.id.message);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();

final List list = lists.get(position);
if (list != null) {
holder.name.setText(list.name);
holder.message.setText(list.message);
}

return v;
}

}

我强烈建议您在浏览器中测试 php 文件的输出,以确保您的查询和与数据库的连接正常工作。

祝你好运!

关于java - 在ListView中显示JsonArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8628742/

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