Android中AsyncTask的OnPostExecute之后的超出功能

时间:2017-01-14 16:21:12

标签: android mysql sqlite android-asynctask

在我的MainActivity代码中,我启动BackgroundTask将数据从我的SQLite写入MySQL数据库。到目前为止一切顺利。

在我调用BackgroundTask之后的代码中,我删除了Record,但这就是问题所在。记录被发送到MySQL数据库并删除记录,但是当传输到MySQL数据库出现问题时,记录也将被删除。搜索后,我发现我必须在代码添加到PostExecute的部分调用删除记录的执行。那就是问题所在。我无法找到如何做到这一点。有人可以帮我解决我的第一个应用程序的最后一点。感谢

public class MainActivity extends Activity {

Button btnAddNewRecord;
SQLiteHelper sQLiteHelper;
LinearLayout parentLayout;
LinearLayout layoutDisplayPeople;
TextView tvNoRecordsFound;
private TextView finalResult;
private String rowID = null;

private ArrayList<HashMap<String, String>> tableData = new ArrayList<HashMap<String, String>>();
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);

    getAllWidgets();
    sQLiteHelper = new SQLiteHelper(MainActivity.this);
    bindWidgetsWithEvent();
    displayAllRecords();

    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        String locatie = data.getStringExtra(Constants.LOCATIE);
        String product = data.getStringExtra(Constants.PRODUCT);
        String kleurwaaier = data.getStringExtra(Constants.KLEURWAAIER);
        String kleur = data.getStringExtra(Constants.KLEUR);
        String inhoud = data.getStringExtra(Constants.INHOUD);

        ContactModel contact = new ContactModel();
        contact.setLocatie(locatie);
        contact.setProduct(product);
        contact.setKleurwaaier(kleurwaaier);
        contact.setKleur(kleur);
        contact.setInhoud(inhoud);

        if (requestCode == Constants.ADD_RECORD) {
            //sQLiteHelper.insertRecord(locatie, product, kleurwaaier, kleur, inhoud);
            sQLiteHelper.insertRecord(contact);
        } else if (requestCode == Constants.UPDATE_RECORD) {
            contact.setID(rowID);
            //sQLiteHelper.updateRecord(locatie, product, kleurwaaier, kleur, inhoud, rowID);
            sQLiteHelper.updateRecord(contact);
        }
        displayAllRecords();
    }
}

private void getAllWidgets() {
    btnAddNewRecord = (Button) findViewById(R.id.btnAddNewRecord);

    parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
    layoutDisplayPeople = (LinearLayout) findViewById(R.id.layoutDisplayPeople);

    tvNoRecordsFound = (TextView) findViewById(R.id.tvNoRecordsFound);
    finalResult = (TextView) findViewById(R.id.tv_result);
}

private void bindWidgetsWithEvent() {
    btnAddNewRecord.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onAddRecord();
        }
    });
}

private void onAddRecord() {
    Intent intent = new Intent(MainActivity.this, TableManipulationActivity.class);
    intent.putExtra(Constants.DML_TYPE, Constants.INSERT);
    startActivityForResult(intent, Constants.ADD_RECORD);
}

private void onUpdateRecord(String locatie, String product, String kleurwaaier, String kleur, String inhoud) {
    Intent intent = new Intent(MainActivity.this, TableManipulationActivity.class);
    intent.putExtra(Constants.LOCATIE, locatie);
    intent.putExtra(Constants.PRODUCT, product);
    intent.putExtra(Constants.KLEURWAAIER, kleurwaaier);
    intent.putExtra(Constants.KLEUR, kleur);
    intent.putExtra(Constants.INHOUD, inhoud);
    intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);
    startActivityForResult(intent, Constants.UPDATE_RECORD);

}

private void displayAllRecords() {

    com.rey.material.widget.LinearLayout inflateParentView;
    parentLayout.removeAllViews();

    ArrayList<ContactModel> contacts = sQLiteHelper.getAllRecords();

    if (contacts.size() > 0) {
        tvNoRecordsFound.setVisibility(View.GONE);
        ContactModel contactModel;
        for (int i = 0; i < contacts.size(); i++) {

            contactModel = contacts.get(i);

            final Holder holder = new Holder();
            final View view = LayoutInflater.from(this).inflate(R.layout.inflate_record, null);
            inflateParentView = (com.rey.material.widget.LinearLayout) view.findViewById(R.id.inflateParentView);

            holder.tvFullName = (TextView) view.findViewById(R.id.tvFullName);

            view.setTag(contactModel.getID());
            holder.locatie = contactModel.getLocatie();
            holder.product = contactModel.getProduct();
            holder.kleurwaaier = contactModel.getKleurwaaier();
            holder.kleur = contactModel.getKleur();
            holder.inhoud = contactModel.getInhoud();
            String personName = holder.locatie + "\n" + holder.product + "\n" + holder.kleurwaaier + " " + holder.kleur + " - [ " + holder.inhoud + "/4 ]";
            holder.tvFullName.setText(personName);

            final CharSequence[] items = {Constants.UPDATE, Constants.DELETE};
            inflateParentView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {

                                rowID = view.getTag().toString();
                                onUpdateRecord(holder.locatie, holder.product, holder.kleurwaaier, holder.kleur, holder.inhoud.toString());
                            } else {
                                AlertDialog.Builder deleteDialogOk = new AlertDialog.Builder(MainActivity.this);
                                deleteDialogOk.setTitle("Verwijder Product ?");
                                deleteDialogOk.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //sQLiteHelper.deleteRecord(view.getTag().toString());
                                                ContactModel contact = new ContactModel();
                                                contact.setID(view.getTag().toString());
                                                sQLiteHelper.deleteRecord(contact);
                                                displayAllRecords();
                                            }
                                        }
                                );
                                deleteDialogOk.setNegativeButton("Terug", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                                deleteDialogOk.show();
                            }
                        }
                    });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                    return true;
                }
            });
            parentLayout.addView(view);
        }
    } else {
        tvNoRecordsFound.setVisibility(View.VISIBLE);
    }
}

public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("Main Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();

    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();

    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}

public void userReg(View view) {

    ArrayList<ContactModel> contacts = sQLiteHelper.getAllRecords();

    if (contacts.size() > 0) {
        ContactModel contactModel;
        for (int i = 0; i < contacts.size(); i++) {

            contactModel = contacts.get(i);
            final Holder holder = new Holder();
            //final View view = LayoutInflater.from(this).inflate(R.layout.inflate_record, null);
            //inflateParentView = (com.rey.material.widget.LinearLayout) view.findViewById(R.id.inflateParentView);

            holder.tvFullName = (TextView) view.findViewById(R.id.tvFullName);

            view.setTag(contactModel.getID());
            holder.locatie = contactModel.getLocatie();
            holder.product = contactModel.getProduct();
            holder.kleurwaaier = contactModel.getKleurwaaier();
            holder.kleur = contactModel.getKleur();
            holder.inhoud = contactModel.getInhoud();

            String id = "test";
            String locatie = holder.locatie.toString();
            String product = holder.product.toString();
            String kleurwaaier = holder.kleurwaaier.toString();
            String kleur = holder.kleur.toString();
            String inhoud = holder.inhoud.toString();

            String method = "register";

            BackgroundTask backgroundTask = new BackgroundTask(this);
            backgroundTask.execute(method, id, locatie, product, kleurwaaier, kleur, inhoud);

            //String status = backgroundTask.getStatus().toString();
            /*
            ContactModel contact = new ContactModel();
            contact.setID(view.getTag().toString());

            sQLiteHelper.deleteRecord(contact);
            displayAllRecords();
           */
        }

    }

}

public class BackgroundTask extends AsyncTask<String, Void, String> {

    AlertDialog alertDialog;
    Context ctx;

    BackgroundTask(Context ctx) {
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Login Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://xxx/register.php";

        String method = params[0];
        if (method.equals("register")) {
            String id = params[1];
            String locatie = params[2];
            String product = params[3];
            String kleurwaaier = params[4];
            String kleur = params[5];
            String inhoud = params[6];

            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                //httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8") + "&" +
                        URLEncoder.encode("locatie", "UTF-8") + "=" + URLEncoder.encode(locatie, "UTF-8") + "&" +
                        URLEncoder.encode("product", "UTF-8") + "=" + URLEncoder.encode(product, "UTF-8") + "&" +
                        URLEncoder.encode("kleurwaaier", "UTF-8") + "=" + URLEncoder.encode(kleurwaaier, "UTF-8") + "&" +
                        URLEncoder.encode("kleur", "UTF-8") + "=" + URLEncoder.encode(kleur, "UTF-8") + "&" +
                        URLEncoder.encode("inhoud", "UTF-8") + "=" + URLEncoder.encode(inhoud, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpURLConnection.getInputStream();
                IS.close();
                //httpURLConnection.connect();
                httpURLConnection.disconnect();
                return "Registration Success...";

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

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        if (result.equals("Registration Success...")) {
            //Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            finalResult.setText(result);

            ContactModel contact = new ContactModel();
            contact.setID(view.getTag().toString());

            sQLiteHelper.deleteRecord(contact);

        } else {
            alertDialog.setMessage(result);
            alertDialog.show();
        }
    }

}


public String getText() {
    finalResult = (TextView) findViewById(R.id.tv_result);
    String text = finalResult.getText().toString();
    return text;
}

private class Holder {
    TextView tvFullName;
    String locatie;
    String product;
    String kleurwaaier;
    String kleur;
    String inhoud;
}

}

0 个答案:

没有答案