Ali Boulala
Ali Boulala

Reputation: 99

Entered Username won't appear after App title

I'm developing a simple to do list application, where on the welcome page, you enter your name and when you click to goto your tasks (on tasks page) your username which you just entered should appear at the top of the screen (For example: "App: Username") but when I tried this it appeared as "App: null" on the welcome page and "null: null" on the tasks page. Can anyone see why? Thank you.

Welcome.java

package winfield.joe.assignment.two; 

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.ProgressDialog;
import android.widget.CheckBox;

public class Welcome extends Activity {

    //global vars
    private CheckBox check;
    private ProgressDialog progress;
    private ToggleButton toggleButton;
    private RatingBar ratingBar;

    private String givenTitle;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        givenTitle = (String) this.getTitle();

        progress = new ProgressDialog(this);

        addListenerOnCheck();
        addListenerOnButton();
        addListenerOnRatingBar();

    }

    //on click CheckBox displays a toast message - CLICK!
    public void addListenerOnCheck() {

        check = (CheckBox) findViewById(R.id.check);
        check.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               StringBuffer result = new StringBuffer();
               result.append("CLICK!");
               Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
            }

        });

    }

    //on click toggle button displays on/off
    public void addListenerOnButton() {

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        toggleButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               StringBuffer result = new StringBuffer();
               result.append("Toggle = ").append(toggleButton.getText());          
               Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();   
            }

        });

    }

    //Give a rating - Toast appears of star rating
    public void addListenerOnRatingBar() {

        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        //if rating value has changed, display the current rating on a toast
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {  
                Toast.makeText(Welcome.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_SHORT).show();
            }

        });

    }

    //Onclick - go to About
    public void aboutMe(View view) {

        Intent intent = new Intent(Welcome.this, About.class);

        startActivity(intent);

    }

    //Onclick - go to Tasks
    public void doStuff(View view) {

        this.setTitle(givenTitle + ": " + username);

        Intent intent = new Intent(Welcome.this, Tasks.class);
        startActivity(intent);

        //ProgressBarDialog appears saying its finding yours tasks and loads to 100 and changes activity
        progress.setMessage("Finding tasks...");
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setIndeterminate(true);
        progress.show();

        //Goes to 100
        final int totalProgressTime = 100;

        final Thread t = new Thread(){

           @Override
           public void run(){

              //Goes from 0 to 100 in jumps of 5 until the total amount of jumps reaches 100/total progress time
              int jumpTime = 0;
              while(jumpTime < totalProgressTime){
                 try {
                    Thread.sleep(200);
                    jumpTime += 5;
                    progress.setProgress(jumpTime);
                 } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                 }
              }

           }

       }; t.start();

    }

}

Tasks.java

package winfield.joe.assignment.two;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import winfield.joe.assignment.two.database.TaskContract;
import winfield.joe.assignment.two.database.TaskDBHelper;

public class Tasks extends ListActivity {

    //add required global variables
    private ListAdapter listAdapter;
    private TaskDBHelper helper;

    private String givenTitle;
    private String username;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);
        updateUI();

        this.setTitle(givenTitle + ": " + username);

    }

    //add in the menu (refers to menu.xml file)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    //to get selected tasks from menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task:
                //create new alert dialog which asks you if you want to make a new task entry
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Add a new task");
                builder.setMessage("What do you need to do?");
                final EditText inputField = new EditText(this);
                builder.setView(inputField);
                //if 'add' then place it into the db, update it
                builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //Clicking add - stores data in the database
                        String task = inputField.getText().toString();
                        helper = new TaskDBHelper(Tasks.this);
                        SQLiteDatabase db = helper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.clear();
                        values.put(TaskContract.Columns.TASK,task);
                        db.insertWithOnConflict(TaskContract.TABLE,null,values,SQLiteDatabase.CONFLICT_IGNORE);
                        updateUI();
                    }
                });

                //quits out of alert dialog and goes back to the task list if 'cancel'
                builder.setNegativeButton("Cancel",null);

                builder.create().show();
                return true;

            default:
                return false;
        }
    }

    //Show database entries on the tasks page
    private void updateUI() {
        helper = new TaskDBHelper(Tasks.this);
        SQLiteDatabase sqlDB = helper.getReadableDatabase();
        Cursor cursor = sqlDB.query(TaskContract.TABLE, new String[]{
                TaskContract.Columns._ID, TaskContract.Columns.TASK
        },
                null, null, null, null, null);
        listAdapter = new SimpleCursorAdapter(
                this,
                R.layout.task_view,
                cursor,
                new String[]{TaskContract.Columns.TASK},
                new int[]{R.id.taskTextView},
                0
        );
        this.setListAdapter(listAdapter);
    }

    //Deletes tasks (clicking done next to them)
    public void onDoneButtonClick(View view) {
        View v = (View) view.getParent();
        TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
        String task = taskTextView.getText().toString();
        //This query deletes the entry associated with the id/button pressed
        String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
                        TaskContract.TABLE,
                        TaskContract.Columns.TASK,
                        task);

        helper = new TaskDBHelper(Tasks.this);
        SQLiteDatabase sqlDB = helper.getWritableDatabase();
        sqlDB.execSQL(sql);
        updateUI();
    }

    //onClick finished method assigned to the 'Finished' button
    public void finished(View view) {

            //Make alert dialog box appear and give it it's title
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.alert));

                // set dialog message
                builder.setCancelable(false)

                        //Positive response = return to list (tasks page)
                        .setPositiveButton(getString(R.string.positive),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                //You return to the Tasks 
                                dialog.cancel();
                            }
                        })

                        //Neutral response = go to about (about page)
                        .setNeutralButton(getString(R.string.neutral),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                //You go to About Activity  
                                Intent intent = new Intent(Tasks.this, About.class);
                                startActivity(intent);
                            }
                        })

                        //Negative response = exit app (homescreen)
                        .setNegativeButton(getString(R.string.negative),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, exit app to homescreen
                                Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.addCategory(Intent.CATEGORY_HOME);
                                startActivity(intent);
                            }
                        });

            //create it and show it
            AlertDialog alert = builder.create();
            alert.show();

        }

}

Username within activity_welcome.xml

<EditText
    android:ems="10"
    android:hint="@+string/username"
    android:id="@+id/username"
    android:inputType="text"
    android:layout_height="wrap_content"
    android:layout_marginEnd="30dp"
    android:layout_marginStart="30dp"
    android:layout_marginTop="30dp"
    android:layout_width="match_parent">

    <requestFocus/>
</EditText>

Relevant strings from strings.xml

<string name="app_name">ForYouToDo</string>
<string name="username">Username</string>

Upvotes: 0

Views: 72

Answers (1)

M D
M D

Reputation: 47817

Go to Android - Pass Data Between Two Activities get NullPointerException

A complete guide(How to pass data between two activity?)

and do in your Tasks Activity

this.setTitle(getResources().getString(R.string.app_name)+ ": " + username);

Upvotes: 2

Related Questions