Help!

PC-Problemen?
De vrijwilligers van Oplossing.be zoeken gratis met u mee!

Hulp bij posten

Recente topics

Auteur Topic: Value bepalen in class 1 en gebruiken in class 2  (gelezen 2453 keer)

0 leden en 1 gast bekijken dit topic.

Offline LV

  • Nieuw lid
  • Berichten: 5
  • Geslacht: Man
  • Oplossing.be
Value bepalen in class 1 en gebruiken in class 2
« Gepost op: 10 januari 2017, 21:49:25 »
Als laatste schakel om mijn app af te werken zoek ik een manier om een variabele in class BackgroundTask te maken en deze als voorwaarde te gebruiken in MainActivity om een beslissing uit te voeren met een If functie.

Hierna vindt U de code van de 2 classen die hiermee betrokken zijn in mijn app.
Bij de code heb ik een opmerking toegevoegd waar volgens mij iets dient te gebeuren.

Kan iemand mij hiermee verder helpen.

Alvast bedankt

MainActivity.java

package com.example.theappguruz.sqlitedemoandroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.FileWriter;

import static com.example.theappguruz.sqlitedemoandroid.R.id.inflateParentView;
import static com.example.theappguruz.sqlitedemoandroid.SQLiteHelper.TABLE_NAME;


public class MainActivity extends Activity {

    Button btnAddNewRecord;
    SQLiteHelper sQLiteHelper;

    LinearLayout parentLayout;
    LinearLayout layoutDisplayPeople;

    TextView tvNoRecordsFound;
    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();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        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);
    }

    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);
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    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("https://[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();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    public void userReg(View view) {
        Toast toast = Toast.makeText(this, "Content", Toast.LENGTH_LONG);

        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.id = contactModel.getID();
                holder.locatie = contactModel.getLocatie();
                holder.product = contactModel.getProduct();
                holder.kleurwaaier = contactModel.getKleurwaaier();
                holder.kleur = contactModel.getKleur();
                holder.inhoud = contactModel.getInhoud();

                String id = holder.id.toString();
                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";

//Hier wordt de data via de class BackgroundTask verstuurd naar een MySQL database.

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

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

//Bedoeling is dat volgende regel deleteRecord enkel wordt uitgevoerd als de functie van de BackgroundTask correct is uitgevoerd.
//Daarom dacht ik hier een If te voorzien die naar de waarde van vb een variabele vraagt.
//Deze variabele zou dan een waarde dienen te krijgen bij BackgroundTask

                sQLiteHelper.deleteRecord(contact);
                displayAllRecords();

            }

        }

    }

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

}


BackgroundTask.java

package com.example.theappguruz.sqlitedemoandroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import static android.R.attr.value;

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 = "https://www.xxxx.be/sync_app/register.php";
        String login_url = "https://www.xxxx.be/sync_app/login.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 "Export is gelukt ...";

//Hier zou een waarde dienen bepaald te worden die nadien opgevraagd kan worden in de MainActivity


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
/*        else if(method.equals("login"))
        {
            String id = params[1];

            try {
                URL url = new URL(login_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("id","UTF-8")+"="+URLEncoder.encode(id,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line = "";
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } 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("Export is gelukt ...")) {
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
        } else {

            alertDialog.setMessage(result);
            alertDialog.show();

        }
    }
}


 


www.combell.com