使用JSON和php使用日期在Listview中显示项目

时间:2014-07-17 20:21:39

标签: php android json listview

我几乎每周都在复习,但我仍然无法解决这个问题。我想查看listview中的项目,该项目是从datepicker的特定日期中选择的。

我这里有一个脚本,可以选择所有项目,但我想通过where子句查询它,并在应用程序中添加一些来自textview的日期。

get_all_dispatches.php

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM dispatches") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// dispatches node
$response["dispatches"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $dispatches = array();
    $dispatches["ticket_no"] = $row["ticket_no"];
    $dispatches["status"] = $row["status"];
    $dispatches["branch_code"] = $row["branch_code"];
    $dispatches["reported_by"] = $row["reported_by"];
    $dispatches["reported_on"] = $row["reported_on"];
    $dispatches["reported_date"] = $row["reported_date"];
$dispatches["problem"] = $row["problem"];
$dispatches["created_by"] = $row["created_by"];

    // push single product into final response array
    array_push($response["dispatches"], $dispatches);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No dispatch found";

// echo no users JSON
echo json_encode($response);
}
?>  

SchedulerActivity.java Datepicker类

public class SchedulerActivity extends Activity {


// Creating JSON Parser object
    JSONParser jParser = new JSONParser();

private TextView Output;
private Button changeDate, btnNext, btnBack;

private int year;
private int month;
private int day;

static final int DATE_PICKER_ID = 1111; 

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

    Output = (TextView) findViewById(R.id.Output);
    changeDate = (Button) findViewById(R.id.changeDate);
    btnNext = (Button) findViewById(R.id.btnNext);
    btnBack = (Button) findViewById(R.id.btnBack);


    // Get current date by calender

    final Calendar c = Calendar.getInstance();
    year  = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day   = c.get(Calendar.DAY_OF_MONTH);

    final String[] MONTHS = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",            "Sep", "Oct", "Nov", "Dec"};

    // Show current date

    Output.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(year).append("-").append(MONTHS[month]).append("-").append(day));

    // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL

    // Button listener to show date picker dialog

    changeDate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // On button click show datepicker dialog 
            showDialog(DATE_PICKER_ID);

        }

    });


            btnBack.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // starting background task to update product
                    Intent myIntent= new Intent(SchedulerActivity.this,     MainScreenActivity.class);
                    startActivity(myIntent);
                }
            });


            btnNext.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // starting background task to send date
                    String dataToPass = Output.getText().toString();
                    Intent intent= new Intent(SchedulerActivity.this, AllProductsActivity.class);
                    intent.putExtra("repdate", dataToPass);
                    startActivity(intent);
                }
            });

 }


@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_PICKER_ID:

        // open datepicker dialog. 
        // set date picker for current date 
        // add pickerListener listner to date picker
        return new DatePickerDialog(this, pickerListener, year, month,day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    @Override
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {

        year  = selectedYear;
        month = selectedMonth;
        day   = selectedDay;

        final String[] MONTHS = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

        // Show selected date 
        Output.setText(new StringBuilder().append(year).append("-").append(MONTHS[month])
                .append("-").append(day));

       }
    };
}

AllProductsActivity.java 这包含listview

public class AllProductsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> dispatchlist;

// url to get all products list
private static String url_all_dispatches = "http://pacificsunsolution.net84.net/get_all_dispatches.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DISPATCHES = "dispatches";
private static final String TAG_TICKETNO = "ticket_no";
private static final String TAG_REPDATE = "reported_date";
private static final String TAG_BRCODE = "branch_code";

// products JSONArray
JSONArray dispatches = null;

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


    Button btnBack; 


    btnBack = (Button) findViewById(R.id.btnBack);



    // Hashmap for ListView
    dispatchlist = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    btnBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            Intent myIntent= new Intent(AllProductsActivity.this, SchedulerActivity.class);
            startActivity(myIntent);
        }
    });

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_TICKETNO, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading dispatches. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        //getting date from datepicker
        TextView repdate;
        repdate = (TextView) findViewById(R.id.Date);
        String dataToCollect;
        Intent intent = getIntent();
        dataToCollect = intent.getStringExtra("repdate");
        repdate.setText(dataToCollect);



        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_dispatches, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                dispatches = json.getJSONArray(TAG_DISPATCHES);

                // looping through All Products
                for (int i = 0; i < dispatches.length(); i++) {
                    JSONObject c = dispatches.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_TICKETNO);
                    String name = c.getString(TAG_BRCODE);
                    String date = c.getString(TAG_REPDATE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_TICKETNO, id);
                    map.put(TAG_BRCODE, name);
                    map.put(TAG_REPDATE, date);

                    // adding HashList to ArrayList
                    dispatchlist.add(map);


                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, dispatchlist,
                        R.layout.list_item, new String[] { TAG_TICKETNO,
                                TAG_BRCODE, TAG_REPDATE},
                        new int[] { R.id.pid, R.id.name, R.id.date});
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

对不起,很长的帖子。我在祈祷,所以你可以帮助我! :)

0 个答案:

没有答案