java - 在ListView中显示JsonArray

标签 java android mysql database listview

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

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

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/

相关文章:

java - jpa原生查询控制实体(第3部分)

mysql - 无法删除或更新父行: a foreign key constraint fails

mysql - 如何从 Perl MySQL DBI 句柄中获取数据库名称?

java - Hashmap 1 个键 2 个值 - 使用 containsvalue

android - 错误:(45, 36) error: cannot find symbol method findViewbyId(int)

android - 将 android Activity 定义为带有浅色主题的对话框

java - Android Intent 应用程序崩溃

java - 使用 Guice 注入(inject) Map 的值

java - libGDX Box2DDebugRenderer 绘制框太大和太小

java - Jetty 自定义错误处理程序类被调用但没有可抛出对象