getting error when getting array data with where condition from MYSQL in android

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

getting error when getting array data with where condition from MYSQL in android

Alpesh Savaliya
I want to get all data which is available with the specific username from the table in listview using adapter.

I got error "org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject".

below is code

PHP file is working perfectly. I get all data which is available with the specified username.

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; 
    }
    ?>

Here is 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();
        }

Here is 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;
        }

Code for 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();
        }
    }

Where am I doing wrong?

--
You received this message because you are subscribed to the Google Groups "android-platform" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To post to this group, send email to [hidden email].
Visit this group at https://groups.google.com/group/android-platform.
For more options, visit https://groups.google.com/d/optout.