0

I am making an food ordering app, just recently download the source code from https://github.com/G-Maniteja/Android-PHP-MySQL-BootStrap-FoodOrder. I have fix few errors that i have but now i am stuck at this part. Can someone please tell me how to fix it?

The error

    java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
        at com.example.manitejagande.foodorder.MenuItemDataModel.fromJson(MenuItemDataModel.java:29)

The full error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.manitejagande.foodorder, PID: 15899
    java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
        at com.example.manitejagande.foodorder.MenuItemDataModel.fromJson(MenuItemDataModel.java:29)
        at com.example.manitejagande.foodorder.CartActivity$AsyncGet1.onPostExecute(CartActivity.java:387)
        at com.example.manitejagande.foodorder.CartActivity$AsyncGet1.onPostExecute(CartActivity.java:304)
        at android.os.AsyncTask.finish(AsyncTask.java:667)
        at android.os.AsyncTask.-wrap1(AsyncTask.java)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

MenuItemDataModel.Java

package com.example.manitejagande.foodorder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class MenuItemDataModel {
    public String itemname;
    public String itemprice;
`
    public MenuItemDataModel(JSONObject object) {

        try
        {
            this.itemname = object.getString("itemname");
            this.itemprice = object.getString("itemprice");
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    //itemname and itemprice values retrieval from JSON Array..
    public static ArrayList<MenuItemDataModel> fromJson(JSONArray jsonObjects)
    {
        ArrayList<MenuItemDataModel> menuitems = new ArrayList<MenuItemDataModel>();
        for (int i = 0; i < jsonObjects.length(); i++) //ERROR this line
        {
            try
            {
                menuitems.add(new MenuItemDataModel(jsonObjects.getJSONObject(i)));
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
        return menuitems;
    }

}

There is also an Adapter MenuItemAdapter.java

package com.example.manitejagande.foodorder;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;



public class MenuItemAdapter extends RecyclerView.Adapter<MenuItemAdapter.MenuItemViewHolder>
{
    Context context;
    ArrayList<MenuItemDataModel> data;

    public MenuItemAdapter(Context context,ArrayList<MenuItemDataModel> data) {
        this.data = data;
        this.context=context;
    }

    @NonNull
    @Override
    public MenuItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.menu_list_item, parent, false);
        MenuItemViewHolder myViewHolder = new MenuItemViewHolder(view);
        return myViewHolder;

    }
    public String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }

    @Override
    public void onBindViewHolder(@NonNull MenuItemViewHolder holder, int position) {
        TextView itemname=holder.itemname;
        TextView itemprice=holder.itemprice;
        Button additem=holder.additem;
        final Button qsub=holder.qsub;
        final TextView qty=holder.qty;
        Button qadd=holder.qadd;

        final String name=data.get(position).itemname.toString();
        final String price=data.get(position).itemprice.toString();

        itemname.setText(name);
        itemprice.setText(price);

        qty.setText("0");
        qsub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(qty.getText().toString().equals("0"))
                {
                    //Log.i("qwer123456","12345"+qty.getText().toString());
                    Toast.makeText(qsub.getContext(), "Cannot decrease the Quantity..",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    int qty1=Integer.parseInt(qty.getText().toString());
                    qty1--;
                    qty.setText(Integer.toString(qty1));
                }
            }
        });

        qadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int qty1=Integer.parseInt(qty.getText().toString());
                qty1++;
                qty.setText(Integer.toString(qty1));
            }
        });

        additem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //String url="https://inamtginamtg.000webhostapp.com/cart.php";
                if(qty.getText().toString().equals("0"))
                {
                    Toast.makeText(context,"Please add Quantity of the Item..",Toast.LENGTH_SHORT).show();
                }
                else {
                    String url = LoginActivity.weburl + "cart.php";

                    String email = getDefaults("userid", context);
                    Uri.Builder builder = new Uri.Builder()
                            .appendQueryParameter("email", email)
                            .appendQueryParameter("itemname", name)
                            .appendQueryParameter("itemprice", price)
                            .appendQueryParameter("qty",qty.getText().toString());


                    String query = builder.build().getEncodedQuery();
                    Log.i("url", query);
                    Toast.makeText(context, "Item Added Successfully..!", Toast.LENGTH_SHORT).show();
                    Async_Task a = new Async_Task(context, url, query, true);
                    a.execute();
                    Toast.makeText(context, "Item added to Cart", Toast.LENGTH_SHORT).show();

                }


            }
        });
    }


    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class MenuItemViewHolder extends RecyclerView.ViewHolder
    {
        TextView itemname;
        TextView itemprice;
        Button additem;
        Button qsub;
        Button qadd;
        TextView qty;

        public MenuItemViewHolder(View itemView) {
            super(itemView);
            this.itemname=(TextView)itemView.findViewById(R.id.itemname);
            this.itemprice=(TextView)itemView.findViewById(R.id.itemprice);
            this.additem=(Button)itemView.findViewById(R.id.additem);
            this.qsub=(Button)itemView.findViewById(R.id.qsub);
            this.qty=(TextView)itemView.findViewById(R.id.qty);
            this.qadd=(Button)itemView.findViewById(R.id.qadd);


        }
    }
}

CartActivity.Java

package com.example.manitejagande.foodorder;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import static com.example.manitejagande.foodorder.CartActivity.CONNECTION_TIMEOUT;
import static com.example.manitejagande.foodorder.CartActivity.READ_TIMEOUT;

public class CartActivity extends AppCompatActivity {
    public static final int CONNECTION_TIMEOUT=10000;
    public static final int READ_TIMEOUT=15000;
    Context context=this;
    String response;
    ListView listView;
    String email;
    String oids;
    int total=0;
    private static RecyclerView.Adapter adapter;
    private static RecyclerView.Adapter adapter1;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.LayoutManager layoutManager1;
    private static RecyclerView recyclerView;
    private static RecyclerView recyclerView1;
    Button placeorder;
    static TextView total_text;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        email=getDefaults("userid",this);

        total_text=(TextView)findViewById(R.id.totalprice);

        recyclerView = (RecyclerView) findViewById(R.id.recyclercart);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        placeorder=(Button)findViewById(R.id.placeorder);



        recyclerView1 = (RecyclerView) findViewById(R.id.cart_suggestion_recycler);
        recyclerView1.setHasFixedSize(true);

        layoutManager1 = new LinearLayoutManager(this);
        recyclerView1.setLayoutManager(layoutManager1);
        recyclerView1.setItemAnimator(new DefaultItemAnimator());


        //  String url="http://192.168.0.2/foodorder/showcart.php?email="+email;


        FloatingActionButton ca_fab=(FloatingActionButton)findViewById(R.id.ca_fab);
        ca_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent(CartActivity.this,MainActivity.class);
                startActivity(i);
            }


        });

        AsyncGet a=new AsyncGet();
        a.execute();








    }
    public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }



    public class AsyncGet extends AsyncTask<String, String, String>
    {

        ProgressDialog pdLoading = new ProgressDialog(CartActivity.this);
        HttpURLConnection conn;
        URL url = null;
        String results="";


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your php file resides
                // url = new URL("https://inamtginamtg.000webhostapp.com/showcart.php?email="+email);
                url = new URL(LoginActivity.weburl+"showcart.php?email="+email);
                Log.i("url1",url.toString());

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                //Uri.Builder builder = new Uri.Builder();

                //String query = builder.build().getEncodedQuery();
                Log.i("url2",url.toString());

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                //               writer.write(query);
                writer.write(url.toString());

                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                //if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                results=result.toString();
                response=results;



                Log.i("result",results);
                // Pass data to onPostExecute method
                return(result.toString());

//            }else{
//
//                return("unsuccessful");
//            }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();

            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ArrayList<CartItemDataModel> itemslist = CartItemDataModel.fromJson(jsonArray);
            //CartAdapter adapter = new CartAdapter(CartActivity.this, itemslist);
            //adapter.addAll(itemslist);
            //listView.setAdapter(adapter);

            adapter=new CartItemAdapter(context,itemslist);
            recyclerView.setAdapter(adapter);

            //total=((CartItemAdapter) adapter).getTotal();


            if(result!=null)
            {

                Toast.makeText(CartActivity.this, "Items Fetched successfully", Toast.LENGTH_LONG).show();

            }else{

                // If username and password does not match display a error message
                Toast.makeText(CartActivity.this, "Fetch Failed.", Toast.LENGTH_LONG).show();

            }
            total=((CartItemAdapter)adapter).grandTotal(itemslist);
            CartActivity.total_text.setText(String.valueOf(total));
            oids=((CartItemAdapter)adapter).return_oids();
            placeorder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //String url="https://inamtginamtg.000webhostapp.com/currentorders.php";
                    String url=LoginActivity.weburl+"currentorders.php";

                    Uri.Builder builder = new Uri.Builder()
                            .appendQueryParameter("oids", oids);


                    String query = builder.build().getEncodedQuery();
                    Log.i("items to current orders",query);
                    //Toast.makeText(context,"Item removed Successfully..!",Toast.LENGTH_SHORT);
                    Async_Task a=new Async_Task(context,url,query,true);
                    a.execute();
                    String r=a.getResult();
                    Intent i=new Intent(context,CurrentOrder.class);
                    startActivity(i);

                }
            });

            AsyncGet1 a1=new AsyncGet1();
            a1.execute();


        }
        String getjsonString()
        {
            return results;
        }



    }


    public class AsyncGet1 extends AsyncTask<String, String, String> //ERROR Here
    {

        ProgressDialog pdLoading = new ProgressDialog(CartActivity.this);
        HttpURLConnection conn;
        URL url = null;
        String results="";


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        @Override
        protected String doInBackground(String... params) {
            try {
                // url = new URL("https://inamtginamtg.000webhostapp.com/showcart.php?email="+email);
                url = new URL(LoginActivity.weburl+"cartsuggestions.php?email="+email);
                Log.i("url1",url.toString());

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                Log.i("url2",url.toString());
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(url.toString());
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {
                int response_code = conn.getResponseCode();
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                results=result.toString();
                response=results;
                Log.i("result",results);
                return(result.toString());
            }
            catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {
            pdLoading.dismiss();

            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ArrayList<MenuItemDataModel> itemslist = MenuItemDataModel.fromJson(jsonArray); // ERROR HERE
            //CartAdapter adapter = new CartAdapter(CartActivity.this, itemslist);
            //adapter.addAll(itemslist);
            //listView.setAdapter(adapter);

            //data=MenuItemDataModel.fromJson(jsonArray);
            adapter1 = new MenuItemAdapterCart(context, itemslist);
            recyclerView1.setAdapter(adapter1);


            if (result != null) {

                Toast.makeText(CartActivity.this, "Items Fetched successfully", Toast.LENGTH_LONG).show();

            } else {

                // If username and password does not match display a error message
                Toast.makeText(CartActivity.this, "Fetch Failed.", Toast.LENGTH_LONG).show();

            }



        }
    }

}

Thanks in advance for the help

Tom
  • 16,842
  • 17
  • 45
  • 54
Noneam
  • 1
  • 1
  • I am a beginner in java so i don't quite understand it. I don't even understand why do i have a null object. @dan1st – Noneam Dec 10 '20 at 11:14
  • You are calling `fromJson` with a parameter that is `null` but you didn't give the full stack trace (error text) so we do not know where you executed `fromJson`. – dan1st Dec 10 '20 at 11:15
  • How to make it not null? What should i do and where? @dan1st – Noneam Dec 10 '20 at 11:19
  • Where you call `fromJson()`, you pass an argument that is `null`. You need to set the argument to the correct object before calling `fromJson()`. – dan1st Dec 10 '20 at 11:20
  • I have added the all of the error code. What do you mean by set the argument to the correct object? how do i do that? @dan1st – Noneam Dec 10 '20 at 11:26
  • Does a `JSONException` occur before the `NullPointerException`? It seems that the json object fails to load. – dan1st Dec 10 '20 at 11:53
  • I finally found the problem, it's because i didn't make this code JSONArray jsonArray = null; Static. Thanks for the help @dan1st – Noneam Dec 10 '20 at 12:02

0 Answers0