1

i'm trying to run an activity in order to submit all text information to mysql database and start a new activity but I always get unfortunately, app has stopped

here is DonateFood.java activity

public class DonateFood extends AppCompatActivity {

EditText txt_title, txt_desc, txt_amount, txt_date;
Spinner statuss;
Button btnSubmit;
String array;
String title, amount, desc, date, status;

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

    txt_title = (EditText)findViewById(R.id.txt_title);
    txt_amount = (EditText)findViewById(R.id.txt_amount);
    txt_desc = (EditText)findViewById(R.id.txt_desc);
    txt_date = (EditText)findViewById(R.id.txt_date);
    statuss = (Spinner)findViewById(R.id.status);
    btnSubmit = (Button) findViewById(R.id.btnSubmit);

    statuss.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            array=adapterView.getSelectedItem().toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            title =  txt_title.getText().toString();
            amount = txt_amount.getText().toString();
            desc = txt_desc.getText().toString();
            date = txt_date.getText().toString();

            String method = "addFood";

            AddFood addFood = new AddFood(con);
            addFood.execute(method,title,amount,desc,date,array);


        }
    });
}


public class AddFood extends AsyncTask<String, Void, String> {
    Context ctx;

    final String TAG = this.getClass().getName();

    //constructor
    AddFood(Context ctx){
        this.ctx=ctx;
    }

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

        String food_url = "http://10.0.3.2/MySqlDemo/addFood.php";

        String method = params[0];
        if(method.equals("addFood")){


            String title = params[1];
            String amount = params[2];
            String desc = params[3];
            String date = params[4];
            String array = params[5];

            try {
                URL url = new URL (food_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String data = URLEncoder.encode("title", "UTF-8")+"="+URLEncoder.encode(title, "UTF-8")+ "&"
                        +URLEncoder.encode("amount", "UTF-8")+"="+URLEncoder.encode(amount, "UTF-8")+ "&"
                        +URLEncoder.encode("desc", "UTF-8")+"="+URLEncoder.encode(desc, "UTF-8")+ "&"
                        +URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+ "&"
                        +URLEncoder.encode("array", "UTF-8")+"="+URLEncoder.encode(array, "UTF-8");
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                inputStream.close();

                return "Food added successfully";


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        return null;
    }

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

    @Override
    protected void onPostExecute(String result) {
        if (result == null) {
            Toast.makeText(ctx,"result was null", Toast.LENGTH_SHORT).show();
            return;
        }

       else if (result.equals("Food added successfully")) {
            Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();

            ctx.startActivity(new Intent(ctx, FoodView.class));

        }


    }


}

}

the logcat error :

02-24 17:21:45.465 5871-5871/alsaad.layla.mysqldemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  java.lang.NullPointerException
                                                                      at android.widget.Toast.<init>(Toast.java:92)
                                                                      at android.widget.Toast.makeText(Toast.java:238)
                                                                      at alsaad.layla.mysqldemo.DonateFood$AddFood.onPostExecute(DonateFood.java:161)
                                                                      at alsaad.layla.mysqldemo.DonateFood$AddFood.onPostExecute(DonateFood.java:90)
                                                                      at android.os.AsyncTask.finish(AsyncTask.java:631)
                                                                      at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                      at android.os.Looper.loop(Looper.java:137)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                      at java.lang.reflect.Method.invokeNative(Native Method)
                                                                      at java.lang.reflect.Method.invoke(Method.java:511)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                      at dalvik.system.NativeStart.main(Native Method)
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
layla7
  • 43
  • 6
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Bö macht Blau Feb 24 '17 at 17:54

5 Answers5

2

try using getApplicationContext() in your onPostExecute()

Toast.makeText(getApplicationContext(),"result was null", Toast.LENGTH_SHORT).show();

instead of:

Toast.makeText(ctx,"result was null", Toast.LENGTH_SHORT).show();
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
2

Kindly initialize Context object

con = getApplicationContext();
Aman
  • 458
  • 4
  • 16
0

Your problem is that the application could not get the Context in the application. It is not initialized anywhere and to display a toast we need to pass a context to it which is not null;

  Context con;

In onCreate method, just initialize the application context as

  con = getApplicationContext;

or just simply

  con = this;
Vikas Pal
  • 58
  • 9
  • it worked.. I got another problem, why do I get blank data instead when I add new values? help! – layla7 Feb 24 '17 at 18:02
  • @layla7 You mean the data does not get inserted properly into the database. There might be some problem with the URL encoding that you are passing into the URL. – Vikas Pal Feb 24 '17 at 18:07
0

I think you're not initialising the variable "con" so it is always null, you can initialise your variable "con" in your onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ... 
    con = this;
    ...
}

or you can delete your variable "con" and do something like this on your btnSubmit onClik listener

AddFood addFood = new AddFood(DonateFood.this);
addFood.execute(method,title,amount,desc,date,array);
krlos77
  • 331
  • 5
  • 13
0

You are not initializing your Context object. In oncreate method.Just add this line : con = getApplicationContext(); Also,Since you are within main activity class.You can use getApplicationContext() directly.

Jack
  • 308
  • 6
  • 15