0

I am new to Android application programming and I have been struggling for several days now to pass information from an item in a listview on a click. I am posting what I have done to this point here.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private LeagueAdapter mLeagueAdapter;

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

        mLeagueAdapter = new LeagueAdapter();

        final ListView listLeague = (ListView) findViewById(R.id.listView);

        listLeague.setAdapter(mLeagueAdapter);


        // Handle clicks on the ListView
        listLeague.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {

                /*
                    Create  a temporary League
                    Which is a reference to the League
                    that has just been clicked
                */
                // Create a new dialog window
                //DialogShowLeague dialog = new DialogShowLeague();

                // Send in a reference to the League to be shown
                //dialog.sendLeagueSelected(tempLeague);

                // Show the dialog window with the League in it
                //dialog.show(getFragmentManager(), "");


                String selected = ListView[whichItem];
                Intent i = new Intent(getApplicationContext(), BowlersActivity.class);
                i.putExtra("name", selected);
                startActivity(i);
            }
        });
    }

    public void createNewLeague(League n){

        mLeagueAdapter.addLeague(n);

    }


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

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

        if (id == R.id.action_addLeague) {
            DialogNewLeague dialog = new DialogNewLeague();
            dialog.show(getFragmentManager(), "");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class LeagueAdapter extends BaseAdapter {

        List<League> leagueList = new ArrayList<League>();

        @Override
        public int getCount() {
            return leagueList.size();
        }

        @Override
        public League getItem(int whichItem) {
            // Returns the requested league
            return leagueList.get(whichItem);
        }

        @Override
        public long getItemId(int whichItem) {
            // Method used internally
            return whichItem;
        }

        @Override
        public View getView(
                int whichItem, View view, ViewGroup viewGroup) {

            /*
                Prepare a list item to show our data
                The list item is contained in the view parameter
                The position of the data in our ArrayList is contained
                in whichItem parameter
            */


            // Has view been inflated already
            if(view == null){

                // No. So do so here
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                view = inflater.inflate(R.layout.single_league_list_item, viewGroup,false);

            }// End if

            // Grab a reference to all our TextView and ImageView widgets
            TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);

            // Hide any ImageView widgets that are not relevant
            League tempLeague = leagueList.get(whichItem);

            // Add the text to the heading and description
            txtTitle.setText(tempLeague.getTitle());

            return view;
        }

        public void addLeague(League n){

            leagueList.add(n);
            notifyDataSetChanged();

        }


    }

}

DialogNewLeague.java

public class DialogNewLeague extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_new_league, null);

        final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancelLeague);
        Button btnOK = (Button) dialogView.findViewById(R.id.btnAddLeague);

        builder.setView(dialogView).setMessage("Add New mLeague");

        btnCancel.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        // Handle the OK button
        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Create a new note
                League newLeague = new League();

                // Set its variables to match the users entries on the form
                newLeague.setTitle(editTitle.getText().toString());

                // Get a reference to MainActivity
                MainActivity callingActivity = (MainActivity) getActivity();

                // Pass newNote back to MainActivity
                callingActivity.createNewLeague(newLeague);

                // Quit the dialog
                dismiss();
            }
        });


        return builder.create();

    }

}

League.java

package rvogl.ca.mydialog;

public class League {

    private String mLeague;

    public String getTitle() {
        return mLeague;
    }

    public void setTitle(String mLeague) {
        this.mLeague = mLeague;
    }
}

BowlersActivty.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class BowlersActivity extends AppCompatActivity {

    League mLeague;
    String title;
    String editText;

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

        Bundle extras = getIntent().getExtras();
        String name = extras.getString("name");
        editText.setText(name);

    }
}

I have been through almost all the posts on this site that I can find and I have tried several of them without any success.

At this point now the app just crashes when I click on an item in the league listview.

Any suggests and advice on how to accomplish this would be appreciated.

I am able to get the information to an Alert Dialog using the following:

DialogShowLeague

    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.app.DialogFragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class DialogShowLeague extends DialogFragment {

        League mLeague;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            LayoutInflater inflater = getActivity().getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.dialog_show_league, null);

            TextView txtTitle = (TextView) dialogView.findViewById(R.id.txtTitle);
            txtTitle.setText(mLeague.getTitle());


            Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);

            builder.setView(dialogView).setMessage("Your mLeague");

            btnOK.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });



        return builder.create();
    }


    public void sendLeagueSelected(League leagueSelected) {
        mLeague = leagueSelected;
    }

}

Is it not possible to accomplish this using something similar. I just don't know what to replace dialogView with.

Robert Vogl
  • 250
  • 5
  • 19
  • through an intent you can pass data, if its a custom class's object try using serizable/parcelable – Debu May 05 '18 at 15:56
  • What do you mean by crashes ? What's the error message ? – Greggz May 05 '18 at 15:57
  • At the moment I know I have a problem in with the following: app/src/main/java rvogl/ca/mydialog/MainActivity.java error: cannot find symbol variable ListView rvogl/ca/mydialog/BowlersActivity.java error: cannot find symbol method setText(String) This is because I have been messing around with different code samples from different post that I have been reading – Robert Vogl May 05 '18 at 16:06

2 Answers2

0

You can pass value on listview click like the code below. Implement Serializable interface in your model class i.e League

listLeague.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

    @Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) { 
         League selected = (League)adaper.getItemAtPosition(pos);

         Intent i = new Intent(getApplicationContext(), BowlersActivity.class); 
         i.putExtra("name", (Serializable)selected);             
         startActivity(i); 
    }
 });

Edit

Replace your model class with this

public class League implement Serializable { 
    private String mLeague; 

    public String getTitle() { 
        return mLeague; 
    } 

    public void setTitle(String mLeague) {
        this.mLeague = mLeague;
    } 
}

Get data on second activity like this

String name = extras.getSerializableExtra("name").getTitle();
Fazal Hussain
  • 1,129
  • 12
  • 28
  • I tried placing your code into my League class and I am getting unresolved method for getApplicationContext(). unresolved symbols for i.putExtra as well as an unresolved symbol for Serializeable and selected. I am not sure why I would be passing the data with intent in the League class when I already have a onclicklistener in the MainActivity which is passing the the intent to the new activity BowlersActivity. Can you explain this? – Robert Vogl May 05 '18 at 19:25
  • I put the code above in my MainActivity and tried recalling it from my BowlersActivity class with the following into my BowlersActivity Intent intent = getIntent(); String text = intent.getStringExtra(Intent.EXTRA_TEXT); TextView textView = (TextView) findViewById(R.id.tvLeagueName); textView.setText(text); When I click on an item in the listview it goes to the second activity but does not display the information from the list item that was click on. Also when I go back to the first activity the list information is gone. – Robert Vogl May 05 '18 at 20:11
  • How do I resolve symbol extras, I have tried resolving it with Bundle which worked but then .getSerializable('name") cannot be resolved. Not sure what I am doing wrong at this point. – Robert Vogl May 06 '18 at 11:53
  • Use getIntent.getSerializableExtra("name"); – Fazal Hussain May 06 '18 at 12:09
  • Unfortunately String name = getIntent.getSerializableExtra("name")... gives me the same result, getIntent is an unresolveable symbol. Is getIntent a string that needs to be declared? If I declare it .getSerializableExtra becomes unresolved – Robert Vogl May 06 '18 at 12:46
  • I have added my DialogShowLeague above. I am able to successfully show the information to an Alert Dialog, is it not possible use something similar to show the information in a new Activity? – Robert Vogl May 06 '18 at 13:20
  • I am now getting the following error : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference – Robert Vogl May 06 '18 at 14:05
  • My code looks like the following : public class BowlersActivity extends AppCompatActivity { League mLeague; private String name; public Intent getIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bowlers); getIntent.getSerializableExtra("name"); TextView textView = (TextView) findViewById(R.id.tvLeagueName); textView.setText(name); } } – Robert Vogl May 06 '18 at 14:05
  • By the way is there a way to enter in new code segments so they are formatted correctly rather than having it all bunched up like in my comment above? – Robert Vogl May 06 '18 at 14:07
  • Check the post https://stackoverflow.com/questions/2736389/how-to-pass-an-object-from-one-activity-to-another-on-android&ved=2ahUKEwjt-Y_7qPHaAhUJG5oKHc95DRMQFjAAegQIAxAB&usg=AOvVaw0-NQ9d-tH6A1N9rmsTBcew – Fazal Hussain May 06 '18 at 14:43
0

I have managed to figure this out using the following code:

MainActivity

mLeagueAdapter = new LeagueAdapter();

        final ListView listLeague = (ListView) findViewById(R.id.listView);

        listLeague.setAdapter(mLeagueAdapter);
        listLeague.setOnItemClickListener(new   AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {

                String leagueName = mLeagueAdapter.getItem(pos).getTitle();
                Intent myIntent = new Intent(getBaseContext(), BowlersActivity.class);
                myIntent.putExtra("value1", leagueName);
                startActivity(myIntent);
            }
        });

In my second Activity BowlersActivity.java

    String savedExtra = getIntent().getStringExtra("value1");
    TextView myText = (TextView) findViewById(R.id.tvLeagueName);
    myText.setText(savedExtra);

My problem was that I was attempting to get the league name from an empty variable "selected" Once I got the position of the League that I was clicking on in the list view by using the my mLeagueAdapter, passing it on by .putExtra was no longer an issue.

@Fazal Hussain thank-you so much for all your patience and assistance it was greatly appreciated.

Robert Vogl
  • 250
  • 5
  • 19