2015-11-28 6 views
1

В настоящее время я использую операцию с двумя кнопками и текстовым просмотром. В textview я помещаю id того, какие заказы я хочу получить из базы данных через php. Затем я использую кнопку getJSON, которая получает данные, а затем мне в настоящее время требуется tu press parseJSON, который открывает список. Я бы хотел, чтобы это было достаточно, нажав одну из кнопок, и при извлечении данных, показывающих диалог, говорящий о загрузке.JSONArray to ListView - AsyncTask

настоящее время я использую этот код

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_width="wrap_content" 
    android:layout_height="wrap_content" 
    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_width="wrap_content" 
    android:layout_height="wrap_content" 
    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_width="100dp" 
    android:layout_height="30dp" 
    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_width="wrap_content" 
    android:layout_height="wrap_content" 
    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); 

     } 
    }); 


} 
+0

Вы вызываете contactAdapter.notifyDataSetChanged(); после добавления элементов? –

+0

Нет, но проблем со списком нет. Мне просто нужно, чтобы IT была одной кнопкой Вместо двух –

ответ

0

метод использования setOnLongPressClickListner для длительного нажатия кнопки.