【问题标题】:Displaying json data into two adjacent listview将 json 数据显示到两个相邻的列表视图中
【发布时间】:2023-03-11 04:28:01
【问题描述】:

我有一个应用程序应该从 URL 解析一个 json 对象并将其显示到两个相邻的列表视图中(json 对象本身是 MySQL 数据库查询的结果)。

我尝试使用以下代码,但似乎我需要 AsyncTask 类来完成此任务。

谁能帮我写相应的AsyncTask类,指导我在doinbackground、onPreExecute()、onPostExecute中写什么。

MainActivity

public class MainActivity extends Activity
{


    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect();
    }   

    private void connect() 
    {

      String data;
      List<String> r = new ArrayList<String>();

      ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
      ListView list=(ListView)findViewById(R.id.leftListView);
      ListView list2=(ListView)findViewById(R.id.rightListView);
      list2.setBackgroundColor(Color.BLUE);

        try 

        {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://192.168.1.16:89/Derdeery/Zaki.php");
            HttpResponse response = client.execute(request);
            HttpEntity entity=response.getEntity();
            data=EntityUtils.toString(entity);
            Log.e("STRING", data);


            try {


       JSONArray json=new JSONArray(data);

       for(int i=0;i<json.length(); i++)
       {

        JSONObject obj=json.getJSONObject(i);
        String name=obj.getString("Part_NAME");
        String id = obj.getString("Part_ID") ;
        Log.e("name", name);
        r.add(name+"-"+id);

        list.setAdapter(adapter);

          }

           } catch (JSONException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }

        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }


    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ListView
        android:id="@+id/leftListView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="2dp"
        android:layout_weight=".75" />

    <ListView
        android:id="@+id/rightListView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="2dp"
        android:layout_weight=".25" />

</LinearLayout>

编辑:我尝试使用此代码,但不幸的是应用程序已停止错误。

  public class MainActivity extends Activity {
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new GetData().execute();

}


private class GetData extends AsyncTask<Void, Void, Void> 
{
    ProgressDialog progressDialog;
    String data;
    List<String> r = new ArrayList<String>();
    ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);    
    ListView list =  (ListView)findViewById(R.id.right);
    ListView list2= (ListView)findViewById(R.id.left);

    public GetData()
    {


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);


        progressDialog.setCancelable(false);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }

    }



    @Override
    protected Void doInBackground(Void... params) {
    try 

    {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://192.168.1.5:89/Derdeery/Zaki.php");
        HttpResponse response = client.execute(request);
        HttpEntity entity=response.getEntity();
        data=EntityUtils.toString(entity);
        Log.e("STRING", data);

    } 
    catch (ClientProtocolException e) 
    {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
    }
    catch (IOException e) 
    {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
    }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         try {

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
           JSONArray json=new JSONArray(data);

           for(int i=0;i<json.length(); i++)
           {

            JSONObject obj=json.getJSONObject(i);
            String name=obj.getString("Part_NAME");
            String id = obj.getString("Part_ID") ;
            Log.e("name", name);
            r.add(name+"-"+id);



            }
            adapter.notifyDataSetChanged();


        } catch (JSONException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         }


      }}


         }

【问题讨论】:

标签: android android-asynctask


【解决方案1】:

我可以给你一个粗略的想法:

1.) 在 doInBackGround() 中执行网络操作,即从数据库中获取数据(在服务器端,将其转换为 json 等)。

2.) doInBackground() 将返回一个结果,该结果将由 onPostExecute() 接收,在 onPostExecute 内部,将该结果设置在 2 个列表视图上。

3.) onPreExecute() 将包含将在 doInBackground 运行时显示的进度对话框逻辑。

希望您可以尝试一次。否则请告诉我,我会进一步帮助您。

【讨论】:

  • doInbackground方法返回的json是否应该是onPostexecute方法的参数,并且它们的数据类型相同?
  • 这是我的 doInbackground 方法受保护的 JSONArray doInBackground(String...params) { String url=params[0];字符串数据; JSONArray json=null;;尝试 { DefaultHttpClient 客户端 = 新 DefaultHttpClient(); HttpGet 请求 = 新的 HttpGet(url); HttpResponse 响应;响应 = client.execute(request); HttpEntity 实体=response.getEntity();数据=EntityUtils.toString(实体); json = new JSONArray(data); } 捕捉(异常 e) { } 返回 json; }
【解决方案2】:

这样试试

private class GetData extends AsyncTask<Void, Void, Void> {
    ProgressDialog progressDialog;
    public GetData() {


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle(getResources().getString(
                R.string.progress_title));
        progressDialog.setMessage(getResources().getString(
                R.string.progress_message));
        progressDialog.setCancelable(false);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }

    }

    @Override
    protected Void doInBackground(Void... params) {
    try 

    {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://192.168.1.16:89/Derdeery/Zaki.php");
        HttpResponse response = client.execute(request);
        HttpEntity entity=response.getEntity();
        data=EntityUtils.toString(entity);
        Log.e("STRING", data);

    } catch (ClientProtocolException e) {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
    } catch (IOException e) {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
    }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         try {

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
           JSONArray json=new JSONArray(data);

           for(int i=0;i<json.length(); i++)
           {

            JSONObject obj=json.getJSONObject(i);
            String name=obj.getString("Part_NAME");
            String id = obj.getString("Part_ID") ;
            Log.e("name", name);
            r.add(name+"-"+id);



            }
            adapter.notifyDataSetChanged();


        } catch (JSONException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多