I am attempting to POST to a SQL server upon the click of a confirmation button in my main activity. However, when I click the button I receive a fatal error:

Could not find a method create(View) in the activity class com.example.habitabilitystudy.MainActivity for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'confirm'

Is there a best practice for handling this sort of call?

Please find my code below:

Main Activity:

public class MainActivity extends AppCompatActivity implements
    TimePickerFragment.FragmentCallbacks {

private PendingIntent pendingIntent;
private AlarmManager manager;

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

    SharedPreferences sp = this.getSharedPreferences("user",
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("name", "codohert");
    editor.commit();

    Log.i("main", "Start prediction update");

    new UpdatePrediction(this).execute("");

    // Retrieve a PendingIntent that will perform a broadcast
    Intent alarmIntent = new Intent(this, PredictionUpdateReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
    startAlarm();

    // Use the current time as the default values for the picker
    SharedPreferences sharedPref = this.getSharedPreferences("prediction",
            Context.MODE_PRIVATE);

    final Calendar c = Calendar.getInstance();
    int defaultHour = c.get(Calendar.HOUR_OF_DAY);
    int defaultMinute = c.get(Calendar.MINUTE);

    int hour = sharedPref.getInt("prediction_hour", defaultHour);
    int minute = sharedPref.getInt("prediction_min", defaultMinute);

    String timeString = makeTimeString(hour, minute);

    TextView predictionText = (TextView) findViewById(R.id.prediction_time);
    predictionText.setText(timeString);
}

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.confirm:
        new SubmitConfirmation(this).execute("");
        startActivity(new Intent(this, MainActivity.class));
        break;
    }

}

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getFragmentManager(), "timePicker");

}

public void showUserNameEdit(View c) {
    EditNameDialog newFragment = new EditNameDialog();
    newFragment.show(getSupportFragmentManager(), "editName");
}

@Override
public void TimeUpdated(int hour, int minute) {
    Toast.makeText(this, "Hour: " + hour + " Minute: " + minute,
            Toast.LENGTH_SHORT).show();

    String timeString = Integer.toString(hour) + ":"
            + Integer.toString(minute);
    TextView predictionText = (TextView) findViewById(R.id.prediction_time);
    predictionText.setText(timeString);
}

public void startAlarm() {
    manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 60000;

    manager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), interval, pendingIntent);
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}

public String makeTimeString(int hour, int minute) {
    String hs = Integer.toString(hour);
    String ms = Integer.toString(minute);
    if (hour < 10) {
        hs = "0" + hs;
    }
    if (minute < 10) {
        ms = "0" + ms;
    }
    String timeString = hs + ":" + ms;
    return timeString;
}
}

View layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/expectedOcc"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textColor="@+color/Blue_SteelBlue"
    android:textSize="25sp"
    android:textStyle="italic"
    android:text="Expected occupation:" /> 

<TextView
    android:id="@+id/prediction_time"
    android:layout_width="fill_parent"
    android:layout_below="@+id/expectedOcc"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textColor="@+color/Blue_SteelBlue"
    android:textSize="60sp"
    android:textStyle="italic"
    android:text="No time today" /> 

<Button
        android:id="@+id/confirm"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/prediction_time"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:layout_marginTop="8dp"
        android:textSize="25dp"
        android:onClick="create"
        android:text="CONFIRM" />

<Button
        android:id="@+id/adjust"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/confirm"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:textSize="25dp"
        android:onClick="showTimePickerDialog"
        android:text="ADJUST" />

<Button
        android:id="@+id/nameEdit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/adjust"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:textSize="25dp"
        android:onClick="showUserNameEdit"
        android:text="LOGIN" />

My Async Post:

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

String user;
String confirm;
String occ_pred;
String occ_adj;
String usage_t;
String current_t;
String timeString;

int success;
Context context;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PREDICTION = "prediction";
private static final String TAG_OCCUPANCY_PREDICTION = "occupancy_prediction";

private static final String url_usage = "http://10.0.2.2/android_connect/submit_usage.php";

/**
 * Getting product details in background thread
 * */

public SubmitConfirmation(Context context) {
    this.context = context;
}

protected String doInBackground(String... param) {

    Log.i("confirmation", "started");
    /*
     * SharedPreferences sharedPref = context.getSharedPreferences("user",
     * Context.MODE_PRIVATE); user = sharedPref.getString("name",
     * "codohert");
     */

    SharedPreferences sharedPref = context.getSharedPreferences(
            "prediction", Context.MODE_PRIVATE);

    int hour = sharedPref.getInt("prediction_hour", 12);
    int minute = sharedPref.getInt("prediction_min", 0);

    current_t = getCurrentTimeStamp();
    timeString = makeTimeString(hour, minute);

    user = "codohert";
    confirm = "1";
    occ_pred = occ_pred.substring(0, 11) + timeString
            + occ_pred.substring(16);
    Log.i("confirm", "occ_pred" + occ_pred);
    occ_adj = occ_pred.substring(0, 11) + timeString
            + occ_pred.substring(16);
    usage_t = current_t;

    try {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user", user));
        params.add(new BasicNameValuePair("confirm", confirm));
        params.add(new BasicNameValuePair("occupation_prediction", occ_pred));
        params.add(new BasicNameValuePair("occupation_adjustment", occ_adj));
        params.add(new BasicNameValuePair("usage_time", usage_t));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_usage, "POST",
                params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        success = json.getInt(TAG_SUCCESS);
        if (success != 1) {
            Log.i("confirm", "failed");
        }
        return null;

    } catch (JSONException e) {
        Log.i("update", "catch");
        e.printStackTrace();
        return null;
    }
}

public static String getCurrentTimeStamp() {
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// dd/MM/yyyy
    Date now = new Date();
    String strDate = sdfDate.format(now);
    return strDate;
}

public String formatTime(int value) {
    String t = Integer.toString(value);
    if (value < 10) {
        t = "0" + t;
    }
    return t;

}

public String makeTimeString(int hour, int minute) {
    String hs = Integer.toString(hour);
    String ms = Integer.toString(minute);
    if (hour < 10) {
        hs = "0" + hs;
    }
    if (minute < 10) {
        ms = "0" + ms;
    }
    String timeString = hs + ":" + ms;
    return timeString;
}

}
2

There are 2 answers

0
mattfred On

As the error states, you need to have a method named create in your main activity class.

public void create(View view) {
    new SubmitConfirmation(this).execute("");
    startActivity(new Intent(this, MainActivity.class));
}

Your confirm button is looking for this method when it is clicked. It looks like you are trying to use the onClick method for this button click incorrectly.

0
adhithiyan On

In XML, you have given android:onClick="create" for the Button Widget. Hence the function should be named create and not as onClick.

You should define the function as:

public void create(View v) {
    switch (v.getId()) {
        case R.id.confirm:
        new SubmitConfirmation(this).execute("");
        startActivity(new Intent(this, MainActivity.class));
        break;
    }
}

and not as

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.confirm:
        new SubmitConfirmation(this).execute("");
        startActivity(new Intent(this, MainActivity.class));
        break;
    }
}