David Smyth
David Smyth

Reputation: 1

Hi, I am trying to figure out how to pass a string from one class to another

Sorry for all the code. The string I am trying to pass is contents. Let me know if you need any more info

I am new to java so I am probably making silly mistakes. I have tried making different methods to pass the string with no luck. If I was able to get the string to appear in an edittextbox, that would be great.

I'm new to this website; sorry if I am making rookie mistakes.

Main class:

package com.app.david.booktracker; 


public class MainActivity extends AppCompatActivity {

    static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void initToolBar() {

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Book Tracker");
        setSupportActionBar(toolbar);


    }

    public void newBook(View view) {
        Intent intent = new Intent(this, NewBook.class);
        startActivity(intent);
    }

    public void showListBook(View view) {
        Intent intent = new Intent(this, ShowAllBooks.class);
        startActivity(intent);
    }


    public void scanBar(View v) {
        try {
            Intent intent = new Intent(ACTION_SCAN);
            intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
            startActivityForResult(intent, 0);
        } catch (ActivityNotFoundException e) {
            showDialog(MainActivity.this, "No Scanner Found",
                    "Download a scanner code activity?", "Yes", "No").show();
        }
    }


    private static AlertDialog showDialog(final AppCompatActivity act,
                                          CharSequence title, CharSequence message, CharSequence buttonYes,
                                          CharSequence buttonNo) {

        AlertDialog.Builder dowloadDialog = new AlertDialog.Builder(act);
        dowloadDialog
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(buttonYes,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Uri uri = Uri.parse("market://search?q=pname:"
                                        + "com.google.zxing.client.android");

                                Intent intent = new Intent(Intent.ACTION_VIEW,
                                        uri);
                                try {
                                    act.startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                }

                            }
                        })
                .setNegativeButton(buttonNo,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                            }
                        });

        return dowloadDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(requestCode == 0) {
            if(resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                Toast.makeText(this,
                        "Content:" + contents + " Format:" + format,
                        Toast.LENGTH_LONG).show();
            }
        }
    }





    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

Destination class:

package com.app.david.booktracker;

public class NewBook extends AppCompatActivity {

    private final static String TAG= "group4.NewBook";

    private EditText ean;

    @Override

    protected  void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_book);
        //initToolBar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    public void initToolBar(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Book Tracker");

        setSupportActionBar(toolbar);

        toolbar.setNavigationIcon(R.drawable.ic_toolbar_arrow);
        toolbar.setNavigationOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), MainActivity.class);
                        startActivity(intent);
                    }
                }
        );
    }



    public void newBook(View view)
    {
        //Get the
        Intent intent=new Intent(this, MainActivity.class);
        EditText editTextBTitle=(EditText) findViewById(R.id.editTextFirstName);
        EditText editTextBAuthor=(EditText) findViewById(R.id.editTextSurname);

        String booktitle=editTextBTitle.getText().toString();
        String bookauthor=editTextBAuthor.getText().toString();

        String contents = intent.getStringExtra("SCAN_RESULT");
        DataHolder.bookadded(booktitle, bookauthor, contents);
        Log.d(TAG, " Added: " + booktitle + "  " + bookauthor + " " + contents);

        Toast.makeText(this, "Book Added! ", Toast.LENGTH_LONG).show();
        startActivity(intent);
    }

}

Upvotes: 0

Views: 69

Answers (2)

NoChinDeluxe
NoChinDeluxe

Reputation: 3444

There are a couple of ways to share data between Activities. The first way you are already using, so it should be somewhat familiar to you.

When you start a new Activity, you can attach data to the Intent that you pass to start that Activity. It looks something like this:

String dataToPass = "your data";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("dataKey", dataToPass);
startActivity(intent);

Then in the onCreate() of the new Activity, you can retrieve that data like this:

Bundle args = getIntent().getExtras();
if(args != null) {
    passedData = args.getString("dataKey");
}

Another way you can do it is to store your data in a public SharedPreferences file which can be accessible from both classes. You would save the data like this:

String dataToPass = "your data";
SharedPreferences prefs = getSharedPreferences("yourPrefsName", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("dataKey", dataToPass);
editor.apply();

And then you can retrieve it in the next Activity like this:

SharedPreferences prefs = getSharedPreferences("yourPrefsName", MODE_PRIVATE);
String passedData = prefs.getString("dataKey", null);

Hope that helps get you on the right track!

Upvotes: 1

wimkeir
wimkeir

Reputation: 65

If want to be able to access attributes outside of the class, the preferred way is to initialise them as private attributes and have "getter" methods. A simple method like this:

public static String getContents () {
    return contents;
}

will work. However, you'd have to initialise the variable as an attribute of the class, like this:

private static String contents;

which would have to be declared outside of any functions in the class (ie. just after the public static class MainActivity extents AppCombatActivity {). Don't forget to change the line where you initialised it originally from String contents to contents.

I can't help but notice, though, that you're initialising a String of the same name in the NewBook class. Is that where you're trying to plug in the original contents? If so, all you'd need to do, provided you've done all of the above, is to call MainActivity.getContents(), and it should return the String you're looking for.

Upvotes: 1

Related Questions