我想使用适配器从列表视图的表中获取特定用户名可用的所有数据。
我收到错误消息“ org.json.JSONException:org.json.JSONArray类型的值[]无法转换为JSONObject”。
下面是代码
PHP文件运行正常。我获得了所有可用于指定用户名的数据。
ExpenseList.php
<?php
require_once("Config.php");
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'expense':
if(isTheseParametersAvailable(array('username'))){
$username = $_POST['username'];
$stmt = $con->prepare("SELECT * FROM Expense_Master WHERE VV_User_Name = '$username' ORDER BY VD_Expense_Date ASC");
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$stmt->bind_result($expenseid, $userid, $username, $entrydate, $expensedate, $credit, $debit, $description, $modifieddate);
$products = array();
while($stmt->fetch()){
$temp = array();
$temp['expenseid'] = $expenseid;
$temp['userid'] = $userid;
$temp['username'] = $username;
$temp['entrydate'] = $entrydate;
$temp['expensedate'] = $expensedate;
$temp['credit'] = $credit;
$temp['debit'] = $debit;
$temp['description'] = $description;
$temp['modifieddate'] = $modifieddate;
array_push($products, $temp);
$response['error'] = false;
$response['message'] = 'Fetch successfull';
}
}else{
$response['error'] = false;
$response['message'] = 'Invalid username';
}
}
break;
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}else{
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}
echo json_encode($response);
echo json_encode($products);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
?>
这是ExpenseList.JAVA
private static final String EXPENSE_URL = "http:server.com/ExpenseList.php?apicall=expense";
private List<ExpenseListNotes> userNotes = new ArrayList<>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expense_list);
spinnerUserNotes = new ArrayList<SpinnerUserNotes>();
expenseData();
}
private void expenseData() {
//if everything is fine
class expenseData extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
userNotes.add(new ExpenseListNotes(
product.getInt("expenseid"),
product.getString("userid"),
product.getString("username"),
product.getString("entrydate"),
product.getString("expensedate"),
product.getString("credit"),
product.getString("debit"),
product.getString("description")));
}
ExpenseListAdapter adapter = new ExpenseListAdapter(ExpenseList.this, userNotes);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error : "+e.toString(), Toast.LENGTH_LONG).show();
Log.e("Error", e.toString());
}
}
@Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", "Alpesh");
//returing the response
return requestHandler.sendPostRequest(URL_EXPENSE, params);
}
}
expenseData ul = new expenseData();
ul.execute();
}
这是AdapterClass
private class ExpenseListAdapter extends BaseAdapter
{
private Context context;
private List<ExpenseListNotes> invoiceModelArrayList;
public ExpenseListAdapter(Context context, List<ExpenseListNotes> invoiceModelArrayList) {
this.context = context;
this.invoiceModelArrayList = (List<ExpenseListNotes>) invoiceModelArrayList;
}
@Override
public int getCount() {
return invoiceModelArrayList.size();
}
@Override
public Object getItem(int i) {
return invoiceModelArrayList.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View v, ViewGroup viewGroup)
{
final ViewHolder holder;
ButterKnife.bind(this, v);
if (v == null)
{
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_expense_list, null, true);
holder.tvRELUserid = v.findViewById(R.id.tvRELUserid);
holder.tvRELExpenseID = v.findViewById(R.id.tvRELExpenseID);
holder.tvRELUsername = v.findViewById(R.id.tvRELUsername);
holder.tvRELCredit = v.findViewById(R.id.tvRELCredit);
holder.tvRELDebit = v.findViewById(R.id.tvRELDebit);
holder.tvRELExpenseDate = v.findViewById(R.id.tvRELExpenseDate);
holder.tvRELEntryDate = v.findViewById(R.id.tvRELEntryDate);
holder.tvRELDescription = v.findViewById(R.id.tvRELDescription);
holder.btnDelete = v.findViewById(R.id.btnRELDelete);
holder.btnUpdate = v.findViewById(R.id.btnRELUpdate);
v.setTag(holder);
}
else
{
holder = (ViewHolder)v.getTag();
}
holder.tvRELExpenseID.setText(String.valueOf(invoiceModelArrayList.get(i).getExpenseID()));
holder.tvRELUserid.setText(String.valueOf(invoiceModelArrayList.get(i).getUserID()));
holder.tvRELUsername.setText(String.valueOf(invoiceModelArrayList.get(i).getUsername()));
holder.tvRELCredit.setText(String.valueOf(invoiceModelArrayList.get(i).getCredit()));
holder.tvRELDebit.setText(String.valueOf(invoiceModelArrayList.get(i).getDebit()));
holder.tvRELExpenseDate.setText(String.valueOf(invoiceModelArrayList.get(i).getExpenseDate()));
holder.tvRELEntryDate.setText(String.valueOf(invoiceModelArrayList.get(i).getEntryDate()));
holder.tvRELDescription.setText(String.valueOf(invoiceModelArrayList.get(i).getDescription()));
return v;
}
public void setFilter(List<ExpenseListNotes> newList)
{
invoiceModelArrayList = new ArrayList<>();
invoiceModelArrayList.addAll(newList);
notifyDataSetChanged();
}
}
private class ViewHolder {
TextView tvRELUserid, tvRELExpenseID, tvRELUsername, tvRELCredit, tvRELDebit, tvRELExpenseDate, tvRELEntryDate, tvRELDescription;
Button btnDelete, btnUpdate;
}
RequestHandler.Class的代码
public class RequestHandler
{
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams)
{
URL url;
StringBuilder sb = new StringBuilder();
try
{
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return sb.toString();
}
//this method is converting keyvalue pairs data into a query string as needed to send to the server
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet())
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
我在哪里做错了?