当我尝试在单击按钮时运行 AsyncTask 时,我收到一个致命错误“在 MainActivity 中找不到方法 createView(View)”

Posted

技术标签:

【中文标题】当我尝试在单击按钮时运行 AsyncTask 时,我收到一个致命错误“在 MainActivity 中找不到方法 createView(View)”【英文标题】:When I try to run an AsyncTask on a button click, I receive a fatal error "Could not find a method createView(View) in MainActivity" 【发布时间】:2015-09-02 01:12:40 【问题描述】:

我正在尝试在我的主要活动中单击确认按钮后发布到 SQL 服务器。但是,当我单击按钮时,我收到一个致命错误:

在视图类 android.support.v7.widget.AppCompatButton 上的 onClick 处理程序的活动类 com.example.habitabilitystudy.MainActivity 中找不到方法 create(View),id 为“确认”

是否有处理此类呼叫的最佳做法?

请在下面找到我的代码:

主要活动:

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;


视图布局:

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

<TextView
    android:id="@+id/expectedOcc"
    android:layout_
    android:layout_
    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_
    android:layout_below="@+id/expectedOcc"
    android:layout_
    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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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" />

我的异步帖子:

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;



【问题讨论】:

【参考方案1】:

如错误所述,您需要在主活动类中有一个名为 create 的方法。

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

您的确认按钮在被点击时正在寻找此方法。您似乎正在尝试使用 onClick 方法来错误地单击此按钮。

【讨论】:

【参考方案2】:

在 XML 中,您为 Button Widget 提供了 android:onClick="create"。因此函数应该命名为create,而不是onClick

你应该将函数定义为:

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

作为

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

【讨论】:

以上是关于当我尝试在单击按钮时运行 AsyncTask 时,我收到一个致命错误“在 MainActivity 中找不到方法 createView(View)”的主要内容,如果未能解决你的问题,请参考以下文章

Asynctask 中的同步方法。 Asynctask 不是线程,是吗?

Android - 仅在 AsyncTask 未完成时单击按钮时显示进度对话框

一个奇怪的 NetWorkOnMainThreadException

重工作的Asynctask替代方案(在UI中添加大量片段)

android socket客户端pc服务器使用asynctask

当我单击按钮进入下一个屏幕时,移动 Android 应用程序崩溃