我正在努力将我的数据保存到MySQL数据库。我读到你需要使用一个新线程来打开数据库。我见过使用AsyncTask的例子。我如何访问doInBackground方法。我尝试了各种不同的方法调用,或者得到一个错误,或者程序没有使用AsyncTask。这是我的代码。我尝试过不同版本的AddtoSQLDB db = new AddtoSQLDB() 和CreateNewProduct cn = new CreateNewProduct()。
public class AddToMySQLDB extends Activity {
JSONParser jsonParser = new JSONParser();
// TODO Auto-generated method stub
// url to create new product
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private ProgressDialog pDialog;
static String name = "";
static String company = "";
static String timeIn = "";
static String signature;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public static void setVariable(String sDate, String visitorsName2, String visitorsCompany2, byte[] signature2) {
name = visitorsName2;
company = visitorsCompany2;
timeIn = sDate;
}
class CreateNewProduct extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// getting JSON Object
// Note that create product url accepts POST method
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("timeIn", timeIn));
params.add(new BasicNameValuePair("signature", signature));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
/* Intent i = new Intent(getApplicationContext(),
AllProductsActivity.class);
startActivity(i);*/
// closing this screen
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
答案 0 :(得分:1)
您需要execute
AsyncTask
:
CreateNewProduct cn = new CreateNewProduct();
cn.execute(""); //pass the params you want for doInBackground here