JSONArray 到 ListView - AsyncTask

Posted

技术标签:

【中文标题】JSONArray 到 ListView - AsyncTask【英文标题】:JSONArray to ListView - AsyncTask 【发布时间】:2016-03-02 16:13:50 【问题描述】:

我目前正在使用一个带有两个按钮和一个文本视图的活动。在文本视图中,我输入了我想通过 php 从数据库中获取的订单的 ID。然后我使用 getJSON 按钮获取数据,然后我现在需要按 parseJSON 打开列表。我希望按下其中一个按钮就足够了,并且在获取数据时会显示一个显示正在加载的对话框。

我目前正在使用下面的代码

FetchOrderList.java

public class FetchOrderList extends AppCompatActivity 
String json_string;
SQL akep = new SQL();

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();


//Called when pressing getJSON (The first button)
public void getJSON(View view) 
    TextView txt = (TextView) findViewById(R.id.editText);
    new BackgroundTask(txt.getText().toString()).execute();




class BackgroundTask extends AsyncTask<Void, Void, String>

    String json_url = "MYURL";
    String JSON_STRING;
    String sendID;

    protected BackgroundTask(String id)
        sendID = id;
    

    @Override
    protected String doInBackground(Void... params) 
        String data;
        try 
            data = URLEncoder.encode("id", "UTF-8") + "=" +   URLEncoder.encode(sendID, "UTF-8");

            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            OutputStreamWriter wr = new  OutputStreamWriter(httpURLConnection.getOutputStream());

            wr.write(data);
            wr.flush();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            while ((JSON_STRING = bufferedReader.readLine())!=null)
            
                stringBuilder.append(JSON_STRING+"\n");

            

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        

        return null;
    

    @Override
    protected void onProgressUpdate(Void... values) 
        super.onProgressUpdate(values);
    

    @Override
    protected void onPostExecute(String result) 
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(result);
        json_string = result;
    


//Called when pressing the parseJSON button (The second button)
public void parseJSON(View view)

    if(json_string==null)
    
        Toast.makeText(getApplicationContext(), "First Get JSON", Toast.LENGTH_LONG).show();
    
    else
    
        Intent intent = new Intent(this, DisplayListView.class);
        intent.putExtra("json_data", json_string);
        startActivity(intent);
    


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:layout_
    android:layout_
    android:text="GET JSON"
    android:id="@+id/b1"
    android:background="#989898"
    android:onClick="getJSON"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_
    android:layout_
    android:text="PARSE JSON"
    android:id="@+id/b2"
    android:background="#989898"
    android:onClick="parseJSON"
    android:layout_marginTop="46dp"
    android:layout_below="@+id/editText"
    android:layout_alignParentEnd="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_
    android:layout_
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:layout_below="@+id/b2"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="20dp" />

<EditText
    android:layout_
    android:layout_
    android:inputType="number"
    android:ems="10"
    android:id="@+id/editText"
    android:hint="Tur id"
    android:gravity="center"
    android:onClick="getJSON"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

DisplayListView.java

public class DisplayListView extends AppCompatActivity 

String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_list_view);
    getSupportActionBar().hide();
    listView = (ListView)findViewById(R.id.listview);
    contactAdapter = new ContactAdapter(this, R.layout.row_layout);
    listView.setAdapter(contactAdapter);
    json_string = getIntent().getExtras().getString("json_data");

    try 
        jsonObject = new JSONObject(json_string);
        jsonArray = jsonObject.getJSONArray("akep_orders");
        int count = 0;
        String id, customer_id, customer_name;

        while(count<jsonArray.length()) 

            JSONObject JO = jsonArray.getJSONObject(count);
            id = JO.getString("id");
            customer_id = JO.getString("customer_id");
            customer_name = JO.getString("customer_name");
            Contacts contacts = new Contacts(id, customer_id, customer_name);
            contactAdapter.add(contacts);
            count++;
        

     catch (JSONException e) 
        e.printStackTrace();
    

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            TextView theid = (TextView)view.findViewById(R.id.tx_id);
            TextView thecustomerid = (TextView)view.findViewById(R.id.tx_customerid);
            TextView thecustomername = (TextView)view.findViewById(R.id.tx_customername);

            String itemId = theid.getText().toString();
            String itemCustomerid = thecustomerid.getText().toString();
            String itemCustomername = thecustomername.getText().toString();

            Intent intent = new Intent(DisplayListView.this, OrderView.class);
            intent.putExtra("id", itemId);
            intent.putExtra("cid", itemCustomerid);
            intent.putExtra("cname", itemCustomername);
            startActivity(intent);

        
    );



【问题讨论】:

你打电话给contactAdapter.notifyDataSetChanged();添加项目后? 没有,但是列表没有问题。我只需要它是一个按钮而不是两个 【参考方案1】:

使用 setOnLongPressClickListner 方法长按按钮。

【讨论】:

以上是关于JSONArray 到 ListView - AsyncTask的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Listview 访问多个 JSONArray?

意图值(json 数组)到 Listview

如何在 Android 中将 JSONArray 转换为 ListView? [复制]

notifyDataSetChanged()刷新ListView(使用JSONArray绑定的Adapter)

jsonArray请求没有响应[关闭]

将 ArrayList<MyCustomClass> 转换为 JSONArray