-6

i have MainActivity with ArrayList to hold items from server (in json) and now i need to pass the ArrayList data to my new activity-SecondActivity - i try to use Intent intent = new Intent(getApplicationContext(),SecondActivity.class); intent.putExtra(models.getName(),"name"); startActivity(intent); - but it does not passing the values:

public class MainActivity extends AppCompatActivity implements SortListener {

    Models models = new Models();
    final Context context = this;
    ArrayList<Models> arrayList = new ArrayList<>();
    ArrayList<Models> modelArrayList = new ArrayList<>();
    String tag = "test log";
    String msg = "test log";
    Locale myLocale;
    Button btnadd, btnDialog, btnSearch;

    private CustomAdapter adapter = null;
    //ViewPager viewPager;
    List<Models> modelList = new ArrayList<>();
    ListView lvProducts;
    Button btnSortPrice, btnSortAlpha;
    EditText eta, etb;
    private int seccess;
    private String urlString = "http://10.0.0.2/www/androidDiet/get_all_products.php";
    private ProgressDialog dialog;

    private GoogleApiClient client;

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


        dialog = new ProgressDialog(this);
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.setMessage("Loading. Please wait...");



        /*
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisk(true).build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .defaultDisplayImageOptions(defaultOptions).build();
        ImageLoader.getInstance().init(config); // Do it on Application start
        */
        eta = (EditText) findViewById(R.id.eta);
        etb = (EditText) findViewById(R.id.etb);
        lvProducts = (ListView) findViewById(R.id.listParseJson);
        btnSortPrice = (Button) findViewById(R.id.btnSortPrice);
        btnSortAlpha = (Button) findViewById(R.id.btnSortAlpha);
        btnadd = (Button) findViewById(R.id.btnAdd);


        new JSONTask().execute(urlString);

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


    private void btnPopDialog() {

    }


    @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();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://guydroid.co.il.basicconnectionurl/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @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.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://guydroid.co.il.basicconnectionurl/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    @Override
    public void onSortByName() {

    }

    @Override
    public void onSortByPrice() {

    }


    public class JSONTask extends AsyncTask<String, String, List<Models>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected List<Models> doInBackground(String... params) {

            HttpURLConnection hConnection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                hConnection = (HttpURLConnection) url.openConnection();
                hConnection.connect();
                InputStream stream = hConnection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
                // stringBuffer = holding the data from the url
                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                String finalJson = buffer.toString();
                JSONObject jsonObject = new JSONObject(finalJson);
                JSONArray jsonArray = jsonObject.getJSONArray("products");

                StringBuffer finalBuffer = new StringBuffer();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObjects = jsonArray.getJSONObject(i);
                    Models model = new Models();
                    model.setName(jsonObjects.getString("name"));
                    model.setDescription(jsonObjects.getString("description"));
                    model.setProtein(jsonObjects.getDouble("protein"));
                    modelList.add(model);
                }

                return modelList;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (hConnection != null) {
                    hConnection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(final List<Models> modelList) {
            super.onPostExecute(modelList);

            dialog.dismiss();
            final CustomAdapter adapter = new CustomAdapter(getApplicationContext(), R.layout.row, modelList);
            lvProducts.setAdapter(adapter);
            //adapter.notifyDataSetChanged();
            lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {
                    Models models = (Models) parent.getItemAtPosition(position);
                    Toast.makeText(getApplicationContext(), "item: " + parent + " " + models.getName(), Toast.LENGTH_LONG).show();
                }
            });

            AdapterView.OnItemClickListener clickListener = new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
                    Models models = (Models) parent.getItemAtPosition(position);
                    Toast.makeText(getApplicationContext(), "item: " + parent + " " + models.getName(), Toast.LENGTH_LONG).show();

                }
            };
            lvProducts.setOnItemClickListener(clickListener);
            //******************** Here is the issue with the intent put extra ******************///////
            btnDialog = (Button) findViewById(R.id.btnDialog);
            btnDialog.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    StringBuffer responseText = new StringBuffer();
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                    alertDialogBuilder.setTitle("Diet Product");
                    responseText.append("The products you choose:" + "\n");

                    for (int i = 0; i < modelList.size(); i++) {
                        Models models = modelList.get(i);
                        if (models.isSelected()) {
                            responseText.append("\n" + models.getName() + " : " + models.getProtein() + "\n");
                        }
                    }

                    alertDialogBuilder
                            .setMessage(responseText.append("\n" + "Create Meal" + "\n" + "-OR-" + "\n" + "Back to change" + "\n"))
                            .setCancelable(false)
                            .setPositiveButton("CREATE NEW MEAL", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, close current activity
                                    //MainActivity.this.finish();
                                    Intent intent = new Intent(getApplicationContext(), ItemActivity.class);
                                    //intent.putStringArrayListExtra("name",modelArrayList);
                                    intent.putExtra(models.getName(), "name");
                                    startActivity(intent);
                                }
                            })
                            .setNegativeButton("   BACK  ", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.cancel();
                                }
                            });
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                    // Toast.makeText(getApplicationContext(), responseText, Toast.LENGTH_LONG).show();


                }
            });
            adapter.notifyDataSetChanged();


            btnSearch = (Button) findViewById(R.id.btnSearch);
            btnSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "btn search", Toast.LENGTH_LONG).show();
                }
            });
            btnSortPrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Collection
                    Toast.makeText(getApplicationContext(), "button sort clicked 1", Toast.LENGTH_SHORT).show();

                    /* sorting isue took from slidenerd on YOUTUBE
                    * https://www.youtube.com/watch?v=hXY4dRgHfks&index=42&list=PLonJJ3BVjZW6CtAMbJz1XD8ELUs1KXaTD
                    */
                    Collections.sort(modelList, new Comparator<Models>() {
                        @Override
                        public int compare(Models lhs, Models rhs) {


                            double priceLhs = lhs.getProtein();
                            double priceRhs = rhs.getProtein();
                            if (priceLhs < priceRhs) {
                                return 1;
                            } else if (priceLhs > priceRhs) {
                                return -1;
                            } else {
                                return 0;
                            }
                        }
                    });
                    adapter.notifyDataSetChanged();
                }

            });
            btnSortAlpha.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "button sort Alpha clicked 2", Toast.LENGTH_SHORT).show();


                    //setLocal("he");

                    Collections.sort(modelList, new Comparator<Models>() {
                        @Override
                        public int compare(Models lhs, Models rhs) {

                            return lhs.getName().compareTo(rhs.getName());

                        }
                    });
                    adapter.notifyDataSetChanged();
                }
            });

        }
    }

}

picture attached

3 Answers3

1

Use Intent put parcelable and in Class Model extend class Parcelable

Community
  • 1
  • 1
Thror
  • 437
  • 4
  • 4
0

So just pass the references to the edit text from the left window into the right. Inside your dialog box read the values that they entered (make sure they are not null and remove any non digit characters). Now set the reference to the edit texts on the left. This example only shows one you would have to repeat this process two more times. Also I just used generic reference names whatever you actually call those edit texts or text boxes change.

 .setPositiveButton("CREATE NEW MEAL", new 
    DialogInterface.OnClickListener() 
            {
             if ((editTextBox1.getText().toString()) != null)
             double EditTextBox1Double=Double.parseDouble(editdegree.getText().toString().replaceAll("[^\\d.]", ""));
             ReferenceToTextEdit1InsideOtherView.setText(EditTextBox1Double)

            }
MikeB0317
  • 1
  • 1
  • hi - i even try the simple as it: MainActivity .setPositiveButton("CREATE NEW MEAL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(getApplicationContext(), ItemActivity.class); String value = null; intent.putExtra("name",value); startActivity(intent); – guydroid123 Oct 21 '16 at 19:25
  • and at the SecondActivity: textView = (TextView)findViewById(R.id.tvGetStringName); Intent intent = getIntent(); String sName = intent.getStringExtra("name"); textView.setText(sName); AND I GET NULL!!!! - what m i doing wrong ? – guydroid123 Oct 21 '16 at 19:33
  • You need to inflate your views. Pass the inflated view into the class of the second object. You can then store references to that views elements inside that class and do whatever you need to. – MikeB0317 Oct 21 '16 at 20:08
0

As I see you're passing as first argument a value and then name but it's vice versa, first name and then value

misha
  • 134
  • 1
  • 10